prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>hazc_device.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 from zeroconf import Zeroconf, ServiceInfo import socket import configparser from . import hazc_cmd # import pdb class hazc_device: #Forward constants NO_PARAM = hazc_cmd.NO_PARAM BOOL = hazc_cmd.BOOL FLOAT = hazc_cmd.FLOAT STRING = hazc_cmd.STRING INT = hazc_cmd.INT global running running = False def __init__(self, ipaddr): self.version = "0.1" self.config = configparser.ConfigParser() self.config.read('config.ini') self.MSGLEN = 1024 self.END_OF_MSG = '*' self.ip = ipaddr self.buffer = 20 # self.commands = {'version?':self.version_cmd,'commands?':self.commands_cmd,'status?':self.status_cmd} hcvc = hazc_cmd.hazc_cmd('version?', self.version_cmd, self.NO_PARAM) hccc = hazc_cmd.hazc_cmd('commands?', self.commands_cmd, self.NO_PARAM) hcsc = hazc_cmd.hazc_cmd('status?', self.status_cmd, self.STRING) self.commands = {'version': hcvc, 'commands': hccc, 'status': hcsc} # probably want to add a debug log status self.status = {'exec_status': self.exec_status} #Adds a function - not as preferred as addControl #Does NOT auto add status def addFunction(self, name, handler, paramtype): # pdb.settrace() #log("This is not the preferred way to add controls, see addControl") if not('?' in name or '!' in name): # log("Function name requires a '?' or '!', assuming '!'") name += '!' self.commands[name] = hazc_cmd.hazc_cmd(name, handler, paramtype) #Adds a control vector #controlname should just be a name like 'temp' or 'position' - it'll be the same for the status def addControl(self, controlname, handler, statushandler, paramtype=NO_PARAM): cmd_name = 'set-'+controlname self.commands[cmd_name] = hazc_cmd.hazc_cmd(cmd_name+'?', handler, paramtype) self.addStatus(controlname, statushandler) #adds a unique status not already included in control vector. name is just the name, as in 'temp' def addStatus(self, name, handler): self.status[name] = handler def advertise(self): postfix = self.config['global']['service_prefix'] self.port = int(self.config['global']['port']) #print(self.config['device']['hostname']+postfix) info = ServiceInfo(postfix, self.config['device']['hostname']+"."+postfix, socket.inet_aton(self.ip), self.port, 0, 0, {'info': self.config['device']['description']}, "hazc.local.") self.bindConnection() zeroconf = Zeroconf() zeroconf.register_service(info) try: while True: # try: print("Ready") self.conn, self.addr = self.webcontrol.accept() self.listen() self.conn.close() except KeyboardInterrupt: pass finally: print() print("Unregistering...") zeroconf.unregister_service(info) zeroconf.close() try: print("Shutting down socket") self.webcontrol.shutdown(socket.SHUT_RDWR) except Exception as e: print(e) def listen(self): data = bytes() rbytes = 0 while rbytes < self.MSGLEN: d = self.conn.recv(self.buffer) if not d: break data += d rbytes += len(d) # print data.decode('utf-8') self.handledata(data) def handledata(self, data): command, param = self.cleanandstringdata(data) print('->' + command + ';' + param) # replystr = "ERROR" try: replystr = self.commands[command].execute(param) except KeyError: if(command==''): command = "(empty string)" print("ERROR! Unknown command: " + command) replystr = "" # replystr = self.commands['version'].execute('') if(replystr == None): print("WARNING! " + command + " should return a string to send to the master. Sending 'NO_REPLY'") replystr = 'NO_REPLY' print(replystr) self.reply(replystr) def reply(self, msg): longmsg = msg while len(longmsg) < self.MSGLEN: longmsg += self.END_OF_MSG # print(longmsg) self.conn.send(longmsg.encode('utf-8')) def cleanandstringdata(self, data): dstr = data.decode('utf-8') full = dstr.strip(self.END_OF_MSG) if '?' in full: li = full.split('?') param = li[-1] cmd = li[0] elif '!' in full: li = full.split('!') param = li[-1] cmd = li[0] else: param = '' cmd = full return (cmd, param) def bindConnection(self): try: self.webcontrol = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.webcontrol.bind((self.ip, self.port)) self.webcontrol.listen(1) except OSError as e: print(e) quit() def exec_status(self): return "Running" def version_cmd(self): <|fim_middle|> def paramtype_tostring(self, paramnum): if paramnum == self.BOOL: return 'BOOL' elif paramnum == self.FLOAT: return 'FLOAT' elif paramnum == self.STRING: return 'STRING' elif paramnum == self.INT: return 'INT' else: return 'PARAM_ERROR' def commands_cmd(self): rstr = "" for key in self.commands: rstr += key if self.commands[key].paramtype is not self.NO_PARAM: # pdb.set_trace() rstr += ':' + self.paramtype_tostring(self.commands[key].paramtype) rstr += ";" return rstr def status_cmd(self, specific_status=''): str = '' if len(specific_status) > 0: str = self.status[specific_status] else: for st in self.status: str += st + ',' + self.status[st]() + ';' return str[:self.MSGLEN-1] # Some debugging methods def debug_cmds(self): print("Commands: " + str(self.commands)) print("Statuses: " + str(self.status))<|fim▁end|>
return self.version
<|file_name|>hazc_device.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 from zeroconf import Zeroconf, ServiceInfo import socket import configparser from . import hazc_cmd # import pdb class hazc_device: #Forward constants NO_PARAM = hazc_cmd.NO_PARAM BOOL = hazc_cmd.BOOL FLOAT = hazc_cmd.FLOAT STRING = hazc_cmd.STRING INT = hazc_cmd.INT global running running = False def __init__(self, ipaddr): self.version = "0.1" self.config = configparser.ConfigParser() self.config.read('config.ini') self.MSGLEN = 1024 self.END_OF_MSG = '*' self.ip = ipaddr self.buffer = 20 # self.commands = {'version?':self.version_cmd,'commands?':self.commands_cmd,'status?':self.status_cmd} hcvc = hazc_cmd.hazc_cmd('version?', self.version_cmd, self.NO_PARAM) hccc = hazc_cmd.hazc_cmd('commands?', self.commands_cmd, self.NO_PARAM) hcsc = hazc_cmd.hazc_cmd('status?', self.status_cmd, self.STRING) self.commands = {'version': hcvc, 'commands': hccc, 'status': hcsc} # probably want to add a debug log status self.status = {'exec_status': self.exec_status} #Adds a function - not as preferred as addControl #Does NOT auto add status def addFunction(self, name, handler, paramtype): # pdb.settrace() #log("This is not the preferred way to add controls, see addControl") if not('?' in name or '!' in name): # log("Function name requires a '?' or '!', assuming '!'") name += '!' self.commands[name] = hazc_cmd.hazc_cmd(name, handler, paramtype) #Adds a control vector #controlname should just be a name like 'temp' or 'position' - it'll be the same for the status def addControl(self, controlname, handler, statushandler, paramtype=NO_PARAM): cmd_name = 'set-'+controlname self.commands[cmd_name] = hazc_cmd.hazc_cmd(cmd_name+'?', handler, paramtype) self.addStatus(controlname, statushandler) #adds a unique status not already included in control vector. name is just the name, as in 'temp' def addStatus(self, name, handler): self.status[name] = handler def advertise(self): postfix = self.config['global']['service_prefix'] self.port = int(self.config['global']['port']) #print(self.config['device']['hostname']+postfix) info = ServiceInfo(postfix, self.config['device']['hostname']+"."+postfix, socket.inet_aton(self.ip), self.port, 0, 0, {'info': self.config['device']['description']}, "hazc.local.") self.bindConnection() zeroconf = Zeroconf() zeroconf.register_service(info) try: while True: # try: print("Ready") self.conn, self.addr = self.webcontrol.accept() self.listen() self.conn.close() except KeyboardInterrupt: pass finally: print() print("Unregistering...") zeroconf.unregister_service(info) zeroconf.close() try: print("Shutting down socket") self.webcontrol.shutdown(socket.SHUT_RDWR) except Exception as e: print(e) def listen(self): data = bytes() rbytes = 0 while rbytes < self.MSGLEN: d = self.conn.recv(self.buffer) if not d: break data += d rbytes += len(d) # print data.decode('utf-8') self.handledata(data) def handledata(self, data): command, param = self.cleanandstringdata(data) print('->' + command + ';' + param) # replystr = "ERROR" try: replystr = self.commands[command].execute(param) except KeyError: if(command==''): command = "(empty string)" print("ERROR! Unknown command: " + command) replystr = "" # replystr = self.commands['version'].execute('') if(replystr == None): print("WARNING! " + command + " should return a string to send to the master. Sending 'NO_REPLY'") replystr = 'NO_REPLY' print(replystr) self.reply(replystr) def reply(self, msg): longmsg = msg while len(longmsg) < self.MSGLEN: longmsg += self.END_OF_MSG # print(longmsg) self.conn.send(longmsg.encode('utf-8')) def cleanandstringdata(self, data): dstr = data.decode('utf-8') full = dstr.strip(self.END_OF_MSG) if '?' in full: li = full.split('?') param = li[-1] cmd = li[0] elif '!' in full: li = full.split('!') param = li[-1] cmd = li[0] else: param = '' cmd = full return (cmd, param) def bindConnection(self): try: self.webcontrol = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.webcontrol.bind((self.ip, self.port)) self.webcontrol.listen(1) except OSError as e: print(e) quit() def exec_status(self): return "Running" def version_cmd(self): return self.version def paramtype_tostring(self, paramnum): <|fim_middle|> def commands_cmd(self): rstr = "" for key in self.commands: rstr += key if self.commands[key].paramtype is not self.NO_PARAM: # pdb.set_trace() rstr += ':' + self.paramtype_tostring(self.commands[key].paramtype) rstr += ";" return rstr def status_cmd(self, specific_status=''): str = '' if len(specific_status) > 0: str = self.status[specific_status] else: for st in self.status: str += st + ',' + self.status[st]() + ';' return str[:self.MSGLEN-1] # Some debugging methods def debug_cmds(self): print("Commands: " + str(self.commands)) print("Statuses: " + str(self.status))<|fim▁end|>
if paramnum == self.BOOL: return 'BOOL' elif paramnum == self.FLOAT: return 'FLOAT' elif paramnum == self.STRING: return 'STRING' elif paramnum == self.INT: return 'INT' else: return 'PARAM_ERROR'
<|file_name|>hazc_device.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 from zeroconf import Zeroconf, ServiceInfo import socket import configparser from . import hazc_cmd # import pdb class hazc_device: #Forward constants NO_PARAM = hazc_cmd.NO_PARAM BOOL = hazc_cmd.BOOL FLOAT = hazc_cmd.FLOAT STRING = hazc_cmd.STRING INT = hazc_cmd.INT global running running = False def __init__(self, ipaddr): self.version = "0.1" self.config = configparser.ConfigParser() self.config.read('config.ini') self.MSGLEN = 1024 self.END_OF_MSG = '*' self.ip = ipaddr self.buffer = 20 # self.commands = {'version?':self.version_cmd,'commands?':self.commands_cmd,'status?':self.status_cmd} hcvc = hazc_cmd.hazc_cmd('version?', self.version_cmd, self.NO_PARAM) hccc = hazc_cmd.hazc_cmd('commands?', self.commands_cmd, self.NO_PARAM) hcsc = hazc_cmd.hazc_cmd('status?', self.status_cmd, self.STRING) self.commands = {'version': hcvc, 'commands': hccc, 'status': hcsc} # probably want to add a debug log status self.status = {'exec_status': self.exec_status} #Adds a function - not as preferred as addControl #Does NOT auto add status def addFunction(self, name, handler, paramtype): # pdb.settrace() #log("This is not the preferred way to add controls, see addControl") if not('?' in name or '!' in name): # log("Function name requires a '?' or '!', assuming '!'") name += '!' self.commands[name] = hazc_cmd.hazc_cmd(name, handler, paramtype) #Adds a control vector #controlname should just be a name like 'temp' or 'position' - it'll be the same for the status def addControl(self, controlname, handler, statushandler, paramtype=NO_PARAM): cmd_name = 'set-'+controlname self.commands[cmd_name] = hazc_cmd.hazc_cmd(cmd_name+'?', handler, paramtype) self.addStatus(controlname, statushandler) #adds a unique status not already included in control vector. name is just the name, as in 'temp' def addStatus(self, name, handler): self.status[name] = handler def advertise(self): postfix = self.config['global']['service_prefix'] self.port = int(self.config['global']['port']) #print(self.config['device']['hostname']+postfix) info = ServiceInfo(postfix, self.config['device']['hostname']+"."+postfix, socket.inet_aton(self.ip), self.port, 0, 0, {'info': self.config['device']['description']}, "hazc.local.") self.bindConnection() zeroconf = Zeroconf() zeroconf.register_service(info) try: while True: # try: print("Ready") self.conn, self.addr = self.webcontrol.accept() self.listen() self.conn.close() except KeyboardInterrupt: pass finally: print() print("Unregistering...") zeroconf.unregister_service(info) zeroconf.close() try: print("Shutting down socket") self.webcontrol.shutdown(socket.SHUT_RDWR) except Exception as e: print(e) def listen(self): data = bytes() rbytes = 0 while rbytes < self.MSGLEN: d = self.conn.recv(self.buffer) if not d: break data += d rbytes += len(d) # print data.decode('utf-8') self.handledata(data) def handledata(self, data): command, param = self.cleanandstringdata(data) print('->' + command + ';' + param) # replystr = "ERROR" try: replystr = self.commands[command].execute(param) except KeyError: if(command==''): command = "(empty string)" print("ERROR! Unknown command: " + command) replystr = "" # replystr = self.commands['version'].execute('') if(replystr == None): print("WARNING! " + command + " should return a string to send to the master. Sending 'NO_REPLY'") replystr = 'NO_REPLY' print(replystr) self.reply(replystr) def reply(self, msg): longmsg = msg while len(longmsg) < self.MSGLEN: longmsg += self.END_OF_MSG # print(longmsg) self.conn.send(longmsg.encode('utf-8')) def cleanandstringdata(self, data): dstr = data.decode('utf-8') full = dstr.strip(self.END_OF_MSG) if '?' in full: li = full.split('?') param = li[-1] cmd = li[0] elif '!' in full: li = full.split('!') param = li[-1] cmd = li[0] else: param = '' cmd = full return (cmd, param) def bindConnection(self): try: self.webcontrol = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.webcontrol.bind((self.ip, self.port)) self.webcontrol.listen(1) except OSError as e: print(e) quit() def exec_status(self): return "Running" def version_cmd(self): return self.version def paramtype_tostring(self, paramnum): if paramnum == self.BOOL: return 'BOOL' elif paramnum == self.FLOAT: return 'FLOAT' elif paramnum == self.STRING: return 'STRING' elif paramnum == self.INT: return 'INT' else: return 'PARAM_ERROR' def commands_cmd(self): <|fim_middle|> def status_cmd(self, specific_status=''): str = '' if len(specific_status) > 0: str = self.status[specific_status] else: for st in self.status: str += st + ',' + self.status[st]() + ';' return str[:self.MSGLEN-1] # Some debugging methods def debug_cmds(self): print("Commands: " + str(self.commands)) print("Statuses: " + str(self.status))<|fim▁end|>
rstr = "" for key in self.commands: rstr += key if self.commands[key].paramtype is not self.NO_PARAM: # pdb.set_trace() rstr += ':' + self.paramtype_tostring(self.commands[key].paramtype) rstr += ";" return rstr
<|file_name|>hazc_device.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 from zeroconf import Zeroconf, ServiceInfo import socket import configparser from . import hazc_cmd # import pdb class hazc_device: #Forward constants NO_PARAM = hazc_cmd.NO_PARAM BOOL = hazc_cmd.BOOL FLOAT = hazc_cmd.FLOAT STRING = hazc_cmd.STRING INT = hazc_cmd.INT global running running = False def __init__(self, ipaddr): self.version = "0.1" self.config = configparser.ConfigParser() self.config.read('config.ini') self.MSGLEN = 1024 self.END_OF_MSG = '*' self.ip = ipaddr self.buffer = 20 # self.commands = {'version?':self.version_cmd,'commands?':self.commands_cmd,'status?':self.status_cmd} hcvc = hazc_cmd.hazc_cmd('version?', self.version_cmd, self.NO_PARAM) hccc = hazc_cmd.hazc_cmd('commands?', self.commands_cmd, self.NO_PARAM) hcsc = hazc_cmd.hazc_cmd('status?', self.status_cmd, self.STRING) self.commands = {'version': hcvc, 'commands': hccc, 'status': hcsc} # probably want to add a debug log status self.status = {'exec_status': self.exec_status} #Adds a function - not as preferred as addControl #Does NOT auto add status def addFunction(self, name, handler, paramtype): # pdb.settrace() #log("This is not the preferred way to add controls, see addControl") if not('?' in name or '!' in name): # log("Function name requires a '?' or '!', assuming '!'") name += '!' self.commands[name] = hazc_cmd.hazc_cmd(name, handler, paramtype) #Adds a control vector #controlname should just be a name like 'temp' or 'position' - it'll be the same for the status def addControl(self, controlname, handler, statushandler, paramtype=NO_PARAM): cmd_name = 'set-'+controlname self.commands[cmd_name] = hazc_cmd.hazc_cmd(cmd_name+'?', handler, paramtype) self.addStatus(controlname, statushandler) #adds a unique status not already included in control vector. name is just the name, as in 'temp' def addStatus(self, name, handler): self.status[name] = handler def advertise(self): postfix = self.config['global']['service_prefix'] self.port = int(self.config['global']['port']) #print(self.config['device']['hostname']+postfix) info = ServiceInfo(postfix, self.config['device']['hostname']+"."+postfix, socket.inet_aton(self.ip), self.port, 0, 0, {'info': self.config['device']['description']}, "hazc.local.") self.bindConnection() zeroconf = Zeroconf() zeroconf.register_service(info) try: while True: # try: print("Ready") self.conn, self.addr = self.webcontrol.accept() self.listen() self.conn.close() except KeyboardInterrupt: pass finally: print() print("Unregistering...") zeroconf.unregister_service(info) zeroconf.close() try: print("Shutting down socket") self.webcontrol.shutdown(socket.SHUT_RDWR) except Exception as e: print(e) def listen(self): data = bytes() rbytes = 0 while rbytes < self.MSGLEN: d = self.conn.recv(self.buffer) if not d: break data += d rbytes += len(d) # print data.decode('utf-8') self.handledata(data) def handledata(self, data): command, param = self.cleanandstringdata(data) print('->' + command + ';' + param) # replystr = "ERROR" try: replystr = self.commands[command].execute(param) except KeyError: if(command==''): command = "(empty string)" print("ERROR! Unknown command: " + command) replystr = "" # replystr = self.commands['version'].execute('') if(replystr == None): print("WARNING! " + command + " should return a string to send to the master. Sending 'NO_REPLY'") replystr = 'NO_REPLY' print(replystr) self.reply(replystr) def reply(self, msg): longmsg = msg while len(longmsg) < self.MSGLEN: longmsg += self.END_OF_MSG # print(longmsg) self.conn.send(longmsg.encode('utf-8')) def cleanandstringdata(self, data): dstr = data.decode('utf-8') full = dstr.strip(self.END_OF_MSG) if '?' in full: li = full.split('?') param = li[-1] cmd = li[0] elif '!' in full: li = full.split('!') param = li[-1] cmd = li[0] else: param = '' cmd = full return (cmd, param) def bindConnection(self): try: self.webcontrol = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.webcontrol.bind((self.ip, self.port)) self.webcontrol.listen(1) except OSError as e: print(e) quit() def exec_status(self): return "Running" def version_cmd(self): return self.version def paramtype_tostring(self, paramnum): if paramnum == self.BOOL: return 'BOOL' elif paramnum == self.FLOAT: return 'FLOAT' elif paramnum == self.STRING: return 'STRING' elif paramnum == self.INT: return 'INT' else: return 'PARAM_ERROR' def commands_cmd(self): rstr = "" for key in self.commands: rstr += key if self.commands[key].paramtype is not self.NO_PARAM: # pdb.set_trace() rstr += ':' + self.paramtype_tostring(self.commands[key].paramtype) rstr += ";" return rstr def status_cmd(self, specific_status=''): <|fim_middle|> # Some debugging methods def debug_cmds(self): print("Commands: " + str(self.commands)) print("Statuses: " + str(self.status))<|fim▁end|>
str = '' if len(specific_status) > 0: str = self.status[specific_status] else: for st in self.status: str += st + ',' + self.status[st]() + ';' return str[:self.MSGLEN-1]
<|file_name|>hazc_device.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 from zeroconf import Zeroconf, ServiceInfo import socket import configparser from . import hazc_cmd # import pdb class hazc_device: #Forward constants NO_PARAM = hazc_cmd.NO_PARAM BOOL = hazc_cmd.BOOL FLOAT = hazc_cmd.FLOAT STRING = hazc_cmd.STRING INT = hazc_cmd.INT global running running = False def __init__(self, ipaddr): self.version = "0.1" self.config = configparser.ConfigParser() self.config.read('config.ini') self.MSGLEN = 1024 self.END_OF_MSG = '*' self.ip = ipaddr self.buffer = 20 # self.commands = {'version?':self.version_cmd,'commands?':self.commands_cmd,'status?':self.status_cmd} hcvc = hazc_cmd.hazc_cmd('version?', self.version_cmd, self.NO_PARAM) hccc = hazc_cmd.hazc_cmd('commands?', self.commands_cmd, self.NO_PARAM) hcsc = hazc_cmd.hazc_cmd('status?', self.status_cmd, self.STRING) self.commands = {'version': hcvc, 'commands': hccc, 'status': hcsc} # probably want to add a debug log status self.status = {'exec_status': self.exec_status} #Adds a function - not as preferred as addControl #Does NOT auto add status def addFunction(self, name, handler, paramtype): # pdb.settrace() #log("This is not the preferred way to add controls, see addControl") if not('?' in name or '!' in name): # log("Function name requires a '?' or '!', assuming '!'") name += '!' self.commands[name] = hazc_cmd.hazc_cmd(name, handler, paramtype) #Adds a control vector #controlname should just be a name like 'temp' or 'position' - it'll be the same for the status def addControl(self, controlname, handler, statushandler, paramtype=NO_PARAM): cmd_name = 'set-'+controlname self.commands[cmd_name] = hazc_cmd.hazc_cmd(cmd_name+'?', handler, paramtype) self.addStatus(controlname, statushandler) #adds a unique status not already included in control vector. name is just the name, as in 'temp' def addStatus(self, name, handler): self.status[name] = handler def advertise(self): postfix = self.config['global']['service_prefix'] self.port = int(self.config['global']['port']) #print(self.config['device']['hostname']+postfix) info = ServiceInfo(postfix, self.config['device']['hostname']+"."+postfix, socket.inet_aton(self.ip), self.port, 0, 0, {'info': self.config['device']['description']}, "hazc.local.") self.bindConnection() zeroconf = Zeroconf() zeroconf.register_service(info) try: while True: # try: print("Ready") self.conn, self.addr = self.webcontrol.accept() self.listen() self.conn.close() except KeyboardInterrupt: pass finally: print() print("Unregistering...") zeroconf.unregister_service(info) zeroconf.close() try: print("Shutting down socket") self.webcontrol.shutdown(socket.SHUT_RDWR) except Exception as e: print(e) def listen(self): data = bytes() rbytes = 0 while rbytes < self.MSGLEN: d = self.conn.recv(self.buffer) if not d: break data += d rbytes += len(d) # print data.decode('utf-8') self.handledata(data) def handledata(self, data): command, param = self.cleanandstringdata(data) print('->' + command + ';' + param) # replystr = "ERROR" try: replystr = self.commands[command].execute(param) except KeyError: if(command==''): command = "(empty string)" print("ERROR! Unknown command: " + command) replystr = "" # replystr = self.commands['version'].execute('') if(replystr == None): print("WARNING! " + command + " should return a string to send to the master. Sending 'NO_REPLY'") replystr = 'NO_REPLY' print(replystr) self.reply(replystr) def reply(self, msg): longmsg = msg while len(longmsg) < self.MSGLEN: longmsg += self.END_OF_MSG # print(longmsg) self.conn.send(longmsg.encode('utf-8')) def cleanandstringdata(self, data): dstr = data.decode('utf-8') full = dstr.strip(self.END_OF_MSG) if '?' in full: li = full.split('?') param = li[-1] cmd = li[0] elif '!' in full: li = full.split('!') param = li[-1] cmd = li[0] else: param = '' cmd = full return (cmd, param) def bindConnection(self): try: self.webcontrol = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.webcontrol.bind((self.ip, self.port)) self.webcontrol.listen(1) except OSError as e: print(e) quit() def exec_status(self): return "Running" def version_cmd(self): return self.version def paramtype_tostring(self, paramnum): if paramnum == self.BOOL: return 'BOOL' elif paramnum == self.FLOAT: return 'FLOAT' elif paramnum == self.STRING: return 'STRING' elif paramnum == self.INT: return 'INT' else: return 'PARAM_ERROR' def commands_cmd(self): rstr = "" for key in self.commands: rstr += key if self.commands[key].paramtype is not self.NO_PARAM: # pdb.set_trace() rstr += ':' + self.paramtype_tostring(self.commands[key].paramtype) rstr += ";" return rstr def status_cmd(self, specific_status=''): str = '' if len(specific_status) > 0: str = self.status[specific_status] else: for st in self.status: str += st + ',' + self.status[st]() + ';' return str[:self.MSGLEN-1] # Some debugging methods def debug_cmds(self): <|fim_middle|> <|fim▁end|>
print("Commands: " + str(self.commands)) print("Statuses: " + str(self.status))
<|file_name|>hazc_device.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 from zeroconf import Zeroconf, ServiceInfo import socket import configparser from . import hazc_cmd # import pdb class hazc_device: #Forward constants NO_PARAM = hazc_cmd.NO_PARAM BOOL = hazc_cmd.BOOL FLOAT = hazc_cmd.FLOAT STRING = hazc_cmd.STRING INT = hazc_cmd.INT global running running = False def __init__(self, ipaddr): self.version = "0.1" self.config = configparser.ConfigParser() self.config.read('config.ini') self.MSGLEN = 1024 self.END_OF_MSG = '*' self.ip = ipaddr self.buffer = 20 # self.commands = {'version?':self.version_cmd,'commands?':self.commands_cmd,'status?':self.status_cmd} hcvc = hazc_cmd.hazc_cmd('version?', self.version_cmd, self.NO_PARAM) hccc = hazc_cmd.hazc_cmd('commands?', self.commands_cmd, self.NO_PARAM) hcsc = hazc_cmd.hazc_cmd('status?', self.status_cmd, self.STRING) self.commands = {'version': hcvc, 'commands': hccc, 'status': hcsc} # probably want to add a debug log status self.status = {'exec_status': self.exec_status} #Adds a function - not as preferred as addControl #Does NOT auto add status def addFunction(self, name, handler, paramtype): # pdb.settrace() #log("This is not the preferred way to add controls, see addControl") if not('?' in name or '!' in name): # log("Function name requires a '?' or '!', assuming '!'") <|fim_middle|> self.commands[name] = hazc_cmd.hazc_cmd(name, handler, paramtype) #Adds a control vector #controlname should just be a name like 'temp' or 'position' - it'll be the same for the status def addControl(self, controlname, handler, statushandler, paramtype=NO_PARAM): cmd_name = 'set-'+controlname self.commands[cmd_name] = hazc_cmd.hazc_cmd(cmd_name+'?', handler, paramtype) self.addStatus(controlname, statushandler) #adds a unique status not already included in control vector. name is just the name, as in 'temp' def addStatus(self, name, handler): self.status[name] = handler def advertise(self): postfix = self.config['global']['service_prefix'] self.port = int(self.config['global']['port']) #print(self.config['device']['hostname']+postfix) info = ServiceInfo(postfix, self.config['device']['hostname']+"."+postfix, socket.inet_aton(self.ip), self.port, 0, 0, {'info': self.config['device']['description']}, "hazc.local.") self.bindConnection() zeroconf = Zeroconf() zeroconf.register_service(info) try: while True: # try: print("Ready") self.conn, self.addr = self.webcontrol.accept() self.listen() self.conn.close() except KeyboardInterrupt: pass finally: print() print("Unregistering...") zeroconf.unregister_service(info) zeroconf.close() try: print("Shutting down socket") self.webcontrol.shutdown(socket.SHUT_RDWR) except Exception as e: print(e) def listen(self): data = bytes() rbytes = 0 while rbytes < self.MSGLEN: d = self.conn.recv(self.buffer) if not d: break data += d rbytes += len(d) # print data.decode('utf-8') self.handledata(data) def handledata(self, data): command, param = self.cleanandstringdata(data) print('->' + command + ';' + param) # replystr = "ERROR" try: replystr = self.commands[command].execute(param) except KeyError: if(command==''): command = "(empty string)" print("ERROR! Unknown command: " + command) replystr = "" # replystr = self.commands['version'].execute('') if(replystr == None): print("WARNING! " + command + " should return a string to send to the master. Sending 'NO_REPLY'") replystr = 'NO_REPLY' print(replystr) self.reply(replystr) def reply(self, msg): longmsg = msg while len(longmsg) < self.MSGLEN: longmsg += self.END_OF_MSG # print(longmsg) self.conn.send(longmsg.encode('utf-8')) def cleanandstringdata(self, data): dstr = data.decode('utf-8') full = dstr.strip(self.END_OF_MSG) if '?' in full: li = full.split('?') param = li[-1] cmd = li[0] elif '!' in full: li = full.split('!') param = li[-1] cmd = li[0] else: param = '' cmd = full return (cmd, param) def bindConnection(self): try: self.webcontrol = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.webcontrol.bind((self.ip, self.port)) self.webcontrol.listen(1) except OSError as e: print(e) quit() def exec_status(self): return "Running" def version_cmd(self): return self.version def paramtype_tostring(self, paramnum): if paramnum == self.BOOL: return 'BOOL' elif paramnum == self.FLOAT: return 'FLOAT' elif paramnum == self.STRING: return 'STRING' elif paramnum == self.INT: return 'INT' else: return 'PARAM_ERROR' def commands_cmd(self): rstr = "" for key in self.commands: rstr += key if self.commands[key].paramtype is not self.NO_PARAM: # pdb.set_trace() rstr += ':' + self.paramtype_tostring(self.commands[key].paramtype) rstr += ";" return rstr def status_cmd(self, specific_status=''): str = '' if len(specific_status) > 0: str = self.status[specific_status] else: for st in self.status: str += st + ',' + self.status[st]() + ';' return str[:self.MSGLEN-1] # Some debugging methods def debug_cmds(self): print("Commands: " + str(self.commands)) print("Statuses: " + str(self.status))<|fim▁end|>
name += '!'
<|file_name|>hazc_device.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 from zeroconf import Zeroconf, ServiceInfo import socket import configparser from . import hazc_cmd # import pdb class hazc_device: #Forward constants NO_PARAM = hazc_cmd.NO_PARAM BOOL = hazc_cmd.BOOL FLOAT = hazc_cmd.FLOAT STRING = hazc_cmd.STRING INT = hazc_cmd.INT global running running = False def __init__(self, ipaddr): self.version = "0.1" self.config = configparser.ConfigParser() self.config.read('config.ini') self.MSGLEN = 1024 self.END_OF_MSG = '*' self.ip = ipaddr self.buffer = 20 # self.commands = {'version?':self.version_cmd,'commands?':self.commands_cmd,'status?':self.status_cmd} hcvc = hazc_cmd.hazc_cmd('version?', self.version_cmd, self.NO_PARAM) hccc = hazc_cmd.hazc_cmd('commands?', self.commands_cmd, self.NO_PARAM) hcsc = hazc_cmd.hazc_cmd('status?', self.status_cmd, self.STRING) self.commands = {'version': hcvc, 'commands': hccc, 'status': hcsc} # probably want to add a debug log status self.status = {'exec_status': self.exec_status} #Adds a function - not as preferred as addControl #Does NOT auto add status def addFunction(self, name, handler, paramtype): # pdb.settrace() #log("This is not the preferred way to add controls, see addControl") if not('?' in name or '!' in name): # log("Function name requires a '?' or '!', assuming '!'") name += '!' self.commands[name] = hazc_cmd.hazc_cmd(name, handler, paramtype) #Adds a control vector #controlname should just be a name like 'temp' or 'position' - it'll be the same for the status def addControl(self, controlname, handler, statushandler, paramtype=NO_PARAM): cmd_name = 'set-'+controlname self.commands[cmd_name] = hazc_cmd.hazc_cmd(cmd_name+'?', handler, paramtype) self.addStatus(controlname, statushandler) #adds a unique status not already included in control vector. name is just the name, as in 'temp' def addStatus(self, name, handler): self.status[name] = handler def advertise(self): postfix = self.config['global']['service_prefix'] self.port = int(self.config['global']['port']) #print(self.config['device']['hostname']+postfix) info = ServiceInfo(postfix, self.config['device']['hostname']+"."+postfix, socket.inet_aton(self.ip), self.port, 0, 0, {'info': self.config['device']['description']}, "hazc.local.") self.bindConnection() zeroconf = Zeroconf() zeroconf.register_service(info) try: while True: # try: print("Ready") self.conn, self.addr = self.webcontrol.accept() self.listen() self.conn.close() except KeyboardInterrupt: pass finally: print() print("Unregistering...") zeroconf.unregister_service(info) zeroconf.close() try: print("Shutting down socket") self.webcontrol.shutdown(socket.SHUT_RDWR) except Exception as e: print(e) def listen(self): data = bytes() rbytes = 0 while rbytes < self.MSGLEN: d = self.conn.recv(self.buffer) if not d: <|fim_middle|> data += d rbytes += len(d) # print data.decode('utf-8') self.handledata(data) def handledata(self, data): command, param = self.cleanandstringdata(data) print('->' + command + ';' + param) # replystr = "ERROR" try: replystr = self.commands[command].execute(param) except KeyError: if(command==''): command = "(empty string)" print("ERROR! Unknown command: " + command) replystr = "" # replystr = self.commands['version'].execute('') if(replystr == None): print("WARNING! " + command + " should return a string to send to the master. Sending 'NO_REPLY'") replystr = 'NO_REPLY' print(replystr) self.reply(replystr) def reply(self, msg): longmsg = msg while len(longmsg) < self.MSGLEN: longmsg += self.END_OF_MSG # print(longmsg) self.conn.send(longmsg.encode('utf-8')) def cleanandstringdata(self, data): dstr = data.decode('utf-8') full = dstr.strip(self.END_OF_MSG) if '?' in full: li = full.split('?') param = li[-1] cmd = li[0] elif '!' in full: li = full.split('!') param = li[-1] cmd = li[0] else: param = '' cmd = full return (cmd, param) def bindConnection(self): try: self.webcontrol = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.webcontrol.bind((self.ip, self.port)) self.webcontrol.listen(1) except OSError as e: print(e) quit() def exec_status(self): return "Running" def version_cmd(self): return self.version def paramtype_tostring(self, paramnum): if paramnum == self.BOOL: return 'BOOL' elif paramnum == self.FLOAT: return 'FLOAT' elif paramnum == self.STRING: return 'STRING' elif paramnum == self.INT: return 'INT' else: return 'PARAM_ERROR' def commands_cmd(self): rstr = "" for key in self.commands: rstr += key if self.commands[key].paramtype is not self.NO_PARAM: # pdb.set_trace() rstr += ':' + self.paramtype_tostring(self.commands[key].paramtype) rstr += ";" return rstr def status_cmd(self, specific_status=''): str = '' if len(specific_status) > 0: str = self.status[specific_status] else: for st in self.status: str += st + ',' + self.status[st]() + ';' return str[:self.MSGLEN-1] # Some debugging methods def debug_cmds(self): print("Commands: " + str(self.commands)) print("Statuses: " + str(self.status))<|fim▁end|>
break
<|file_name|>hazc_device.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 from zeroconf import Zeroconf, ServiceInfo import socket import configparser from . import hazc_cmd # import pdb class hazc_device: #Forward constants NO_PARAM = hazc_cmd.NO_PARAM BOOL = hazc_cmd.BOOL FLOAT = hazc_cmd.FLOAT STRING = hazc_cmd.STRING INT = hazc_cmd.INT global running running = False def __init__(self, ipaddr): self.version = "0.1" self.config = configparser.ConfigParser() self.config.read('config.ini') self.MSGLEN = 1024 self.END_OF_MSG = '*' self.ip = ipaddr self.buffer = 20 # self.commands = {'version?':self.version_cmd,'commands?':self.commands_cmd,'status?':self.status_cmd} hcvc = hazc_cmd.hazc_cmd('version?', self.version_cmd, self.NO_PARAM) hccc = hazc_cmd.hazc_cmd('commands?', self.commands_cmd, self.NO_PARAM) hcsc = hazc_cmd.hazc_cmd('status?', self.status_cmd, self.STRING) self.commands = {'version': hcvc, 'commands': hccc, 'status': hcsc} # probably want to add a debug log status self.status = {'exec_status': self.exec_status} #Adds a function - not as preferred as addControl #Does NOT auto add status def addFunction(self, name, handler, paramtype): # pdb.settrace() #log("This is not the preferred way to add controls, see addControl") if not('?' in name or '!' in name): # log("Function name requires a '?' or '!', assuming '!'") name += '!' self.commands[name] = hazc_cmd.hazc_cmd(name, handler, paramtype) #Adds a control vector #controlname should just be a name like 'temp' or 'position' - it'll be the same for the status def addControl(self, controlname, handler, statushandler, paramtype=NO_PARAM): cmd_name = 'set-'+controlname self.commands[cmd_name] = hazc_cmd.hazc_cmd(cmd_name+'?', handler, paramtype) self.addStatus(controlname, statushandler) #adds a unique status not already included in control vector. name is just the name, as in 'temp' def addStatus(self, name, handler): self.status[name] = handler def advertise(self): postfix = self.config['global']['service_prefix'] self.port = int(self.config['global']['port']) #print(self.config['device']['hostname']+postfix) info = ServiceInfo(postfix, self.config['device']['hostname']+"."+postfix, socket.inet_aton(self.ip), self.port, 0, 0, {'info': self.config['device']['description']}, "hazc.local.") self.bindConnection() zeroconf = Zeroconf() zeroconf.register_service(info) try: while True: # try: print("Ready") self.conn, self.addr = self.webcontrol.accept() self.listen() self.conn.close() except KeyboardInterrupt: pass finally: print() print("Unregistering...") zeroconf.unregister_service(info) zeroconf.close() try: print("Shutting down socket") self.webcontrol.shutdown(socket.SHUT_RDWR) except Exception as e: print(e) def listen(self): data = bytes() rbytes = 0 while rbytes < self.MSGLEN: d = self.conn.recv(self.buffer) if not d: break data += d rbytes += len(d) # print data.decode('utf-8') self.handledata(data) def handledata(self, data): command, param = self.cleanandstringdata(data) print('->' + command + ';' + param) # replystr = "ERROR" try: replystr = self.commands[command].execute(param) except KeyError: if(command==''): <|fim_middle|> print("ERROR! Unknown command: " + command) replystr = "" # replystr = self.commands['version'].execute('') if(replystr == None): print("WARNING! " + command + " should return a string to send to the master. Sending 'NO_REPLY'") replystr = 'NO_REPLY' print(replystr) self.reply(replystr) def reply(self, msg): longmsg = msg while len(longmsg) < self.MSGLEN: longmsg += self.END_OF_MSG # print(longmsg) self.conn.send(longmsg.encode('utf-8')) def cleanandstringdata(self, data): dstr = data.decode('utf-8') full = dstr.strip(self.END_OF_MSG) if '?' in full: li = full.split('?') param = li[-1] cmd = li[0] elif '!' in full: li = full.split('!') param = li[-1] cmd = li[0] else: param = '' cmd = full return (cmd, param) def bindConnection(self): try: self.webcontrol = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.webcontrol.bind((self.ip, self.port)) self.webcontrol.listen(1) except OSError as e: print(e) quit() def exec_status(self): return "Running" def version_cmd(self): return self.version def paramtype_tostring(self, paramnum): if paramnum == self.BOOL: return 'BOOL' elif paramnum == self.FLOAT: return 'FLOAT' elif paramnum == self.STRING: return 'STRING' elif paramnum == self.INT: return 'INT' else: return 'PARAM_ERROR' def commands_cmd(self): rstr = "" for key in self.commands: rstr += key if self.commands[key].paramtype is not self.NO_PARAM: # pdb.set_trace() rstr += ':' + self.paramtype_tostring(self.commands[key].paramtype) rstr += ";" return rstr def status_cmd(self, specific_status=''): str = '' if len(specific_status) > 0: str = self.status[specific_status] else: for st in self.status: str += st + ',' + self.status[st]() + ';' return str[:self.MSGLEN-1] # Some debugging methods def debug_cmds(self): print("Commands: " + str(self.commands)) print("Statuses: " + str(self.status))<|fim▁end|>
command = "(empty string)"
<|file_name|>hazc_device.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 from zeroconf import Zeroconf, ServiceInfo import socket import configparser from . import hazc_cmd # import pdb class hazc_device: #Forward constants NO_PARAM = hazc_cmd.NO_PARAM BOOL = hazc_cmd.BOOL FLOAT = hazc_cmd.FLOAT STRING = hazc_cmd.STRING INT = hazc_cmd.INT global running running = False def __init__(self, ipaddr): self.version = "0.1" self.config = configparser.ConfigParser() self.config.read('config.ini') self.MSGLEN = 1024 self.END_OF_MSG = '*' self.ip = ipaddr self.buffer = 20 # self.commands = {'version?':self.version_cmd,'commands?':self.commands_cmd,'status?':self.status_cmd} hcvc = hazc_cmd.hazc_cmd('version?', self.version_cmd, self.NO_PARAM) hccc = hazc_cmd.hazc_cmd('commands?', self.commands_cmd, self.NO_PARAM) hcsc = hazc_cmd.hazc_cmd('status?', self.status_cmd, self.STRING) self.commands = {'version': hcvc, 'commands': hccc, 'status': hcsc} # probably want to add a debug log status self.status = {'exec_status': self.exec_status} #Adds a function - not as preferred as addControl #Does NOT auto add status def addFunction(self, name, handler, paramtype): # pdb.settrace() #log("This is not the preferred way to add controls, see addControl") if not('?' in name or '!' in name): # log("Function name requires a '?' or '!', assuming '!'") name += '!' self.commands[name] = hazc_cmd.hazc_cmd(name, handler, paramtype) #Adds a control vector #controlname should just be a name like 'temp' or 'position' - it'll be the same for the status def addControl(self, controlname, handler, statushandler, paramtype=NO_PARAM): cmd_name = 'set-'+controlname self.commands[cmd_name] = hazc_cmd.hazc_cmd(cmd_name+'?', handler, paramtype) self.addStatus(controlname, statushandler) #adds a unique status not already included in control vector. name is just the name, as in 'temp' def addStatus(self, name, handler): self.status[name] = handler def advertise(self): postfix = self.config['global']['service_prefix'] self.port = int(self.config['global']['port']) #print(self.config['device']['hostname']+postfix) info = ServiceInfo(postfix, self.config['device']['hostname']+"."+postfix, socket.inet_aton(self.ip), self.port, 0, 0, {'info': self.config['device']['description']}, "hazc.local.") self.bindConnection() zeroconf = Zeroconf() zeroconf.register_service(info) try: while True: # try: print("Ready") self.conn, self.addr = self.webcontrol.accept() self.listen() self.conn.close() except KeyboardInterrupt: pass finally: print() print("Unregistering...") zeroconf.unregister_service(info) zeroconf.close() try: print("Shutting down socket") self.webcontrol.shutdown(socket.SHUT_RDWR) except Exception as e: print(e) def listen(self): data = bytes() rbytes = 0 while rbytes < self.MSGLEN: d = self.conn.recv(self.buffer) if not d: break data += d rbytes += len(d) # print data.decode('utf-8') self.handledata(data) def handledata(self, data): command, param = self.cleanandstringdata(data) print('->' + command + ';' + param) # replystr = "ERROR" try: replystr = self.commands[command].execute(param) except KeyError: if(command==''): command = "(empty string)" print("ERROR! Unknown command: " + command) replystr = "" # replystr = self.commands['version'].execute('') if(replystr == None): <|fim_middle|> print(replystr) self.reply(replystr) def reply(self, msg): longmsg = msg while len(longmsg) < self.MSGLEN: longmsg += self.END_OF_MSG # print(longmsg) self.conn.send(longmsg.encode('utf-8')) def cleanandstringdata(self, data): dstr = data.decode('utf-8') full = dstr.strip(self.END_OF_MSG) if '?' in full: li = full.split('?') param = li[-1] cmd = li[0] elif '!' in full: li = full.split('!') param = li[-1] cmd = li[0] else: param = '' cmd = full return (cmd, param) def bindConnection(self): try: self.webcontrol = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.webcontrol.bind((self.ip, self.port)) self.webcontrol.listen(1) except OSError as e: print(e) quit() def exec_status(self): return "Running" def version_cmd(self): return self.version def paramtype_tostring(self, paramnum): if paramnum == self.BOOL: return 'BOOL' elif paramnum == self.FLOAT: return 'FLOAT' elif paramnum == self.STRING: return 'STRING' elif paramnum == self.INT: return 'INT' else: return 'PARAM_ERROR' def commands_cmd(self): rstr = "" for key in self.commands: rstr += key if self.commands[key].paramtype is not self.NO_PARAM: # pdb.set_trace() rstr += ':' + self.paramtype_tostring(self.commands[key].paramtype) rstr += ";" return rstr def status_cmd(self, specific_status=''): str = '' if len(specific_status) > 0: str = self.status[specific_status] else: for st in self.status: str += st + ',' + self.status[st]() + ';' return str[:self.MSGLEN-1] # Some debugging methods def debug_cmds(self): print("Commands: " + str(self.commands)) print("Statuses: " + str(self.status))<|fim▁end|>
print("WARNING! " + command + " should return a string to send to the master. Sending 'NO_REPLY'") replystr = 'NO_REPLY'
<|file_name|>hazc_device.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 from zeroconf import Zeroconf, ServiceInfo import socket import configparser from . import hazc_cmd # import pdb class hazc_device: #Forward constants NO_PARAM = hazc_cmd.NO_PARAM BOOL = hazc_cmd.BOOL FLOAT = hazc_cmd.FLOAT STRING = hazc_cmd.STRING INT = hazc_cmd.INT global running running = False def __init__(self, ipaddr): self.version = "0.1" self.config = configparser.ConfigParser() self.config.read('config.ini') self.MSGLEN = 1024 self.END_OF_MSG = '*' self.ip = ipaddr self.buffer = 20 # self.commands = {'version?':self.version_cmd,'commands?':self.commands_cmd,'status?':self.status_cmd} hcvc = hazc_cmd.hazc_cmd('version?', self.version_cmd, self.NO_PARAM) hccc = hazc_cmd.hazc_cmd('commands?', self.commands_cmd, self.NO_PARAM) hcsc = hazc_cmd.hazc_cmd('status?', self.status_cmd, self.STRING) self.commands = {'version': hcvc, 'commands': hccc, 'status': hcsc} # probably want to add a debug log status self.status = {'exec_status': self.exec_status} #Adds a function - not as preferred as addControl #Does NOT auto add status def addFunction(self, name, handler, paramtype): # pdb.settrace() #log("This is not the preferred way to add controls, see addControl") if not('?' in name or '!' in name): # log("Function name requires a '?' or '!', assuming '!'") name += '!' self.commands[name] = hazc_cmd.hazc_cmd(name, handler, paramtype) #Adds a control vector #controlname should just be a name like 'temp' or 'position' - it'll be the same for the status def addControl(self, controlname, handler, statushandler, paramtype=NO_PARAM): cmd_name = 'set-'+controlname self.commands[cmd_name] = hazc_cmd.hazc_cmd(cmd_name+'?', handler, paramtype) self.addStatus(controlname, statushandler) #adds a unique status not already included in control vector. name is just the name, as in 'temp' def addStatus(self, name, handler): self.status[name] = handler def advertise(self): postfix = self.config['global']['service_prefix'] self.port = int(self.config['global']['port']) #print(self.config['device']['hostname']+postfix) info = ServiceInfo(postfix, self.config['device']['hostname']+"."+postfix, socket.inet_aton(self.ip), self.port, 0, 0, {'info': self.config['device']['description']}, "hazc.local.") self.bindConnection() zeroconf = Zeroconf() zeroconf.register_service(info) try: while True: # try: print("Ready") self.conn, self.addr = self.webcontrol.accept() self.listen() self.conn.close() except KeyboardInterrupt: pass finally: print() print("Unregistering...") zeroconf.unregister_service(info) zeroconf.close() try: print("Shutting down socket") self.webcontrol.shutdown(socket.SHUT_RDWR) except Exception as e: print(e) def listen(self): data = bytes() rbytes = 0 while rbytes < self.MSGLEN: d = self.conn.recv(self.buffer) if not d: break data += d rbytes += len(d) # print data.decode('utf-8') self.handledata(data) def handledata(self, data): command, param = self.cleanandstringdata(data) print('->' + command + ';' + param) # replystr = "ERROR" try: replystr = self.commands[command].execute(param) except KeyError: if(command==''): command = "(empty string)" print("ERROR! Unknown command: " + command) replystr = "" # replystr = self.commands['version'].execute('') if(replystr == None): print("WARNING! " + command + " should return a string to send to the master. Sending 'NO_REPLY'") replystr = 'NO_REPLY' print(replystr) self.reply(replystr) def reply(self, msg): longmsg = msg while len(longmsg) < self.MSGLEN: longmsg += self.END_OF_MSG # print(longmsg) self.conn.send(longmsg.encode('utf-8')) def cleanandstringdata(self, data): dstr = data.decode('utf-8') full = dstr.strip(self.END_OF_MSG) if '?' in full: <|fim_middle|> elif '!' in full: li = full.split('!') param = li[-1] cmd = li[0] else: param = '' cmd = full return (cmd, param) def bindConnection(self): try: self.webcontrol = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.webcontrol.bind((self.ip, self.port)) self.webcontrol.listen(1) except OSError as e: print(e) quit() def exec_status(self): return "Running" def version_cmd(self): return self.version def paramtype_tostring(self, paramnum): if paramnum == self.BOOL: return 'BOOL' elif paramnum == self.FLOAT: return 'FLOAT' elif paramnum == self.STRING: return 'STRING' elif paramnum == self.INT: return 'INT' else: return 'PARAM_ERROR' def commands_cmd(self): rstr = "" for key in self.commands: rstr += key if self.commands[key].paramtype is not self.NO_PARAM: # pdb.set_trace() rstr += ':' + self.paramtype_tostring(self.commands[key].paramtype) rstr += ";" return rstr def status_cmd(self, specific_status=''): str = '' if len(specific_status) > 0: str = self.status[specific_status] else: for st in self.status: str += st + ',' + self.status[st]() + ';' return str[:self.MSGLEN-1] # Some debugging methods def debug_cmds(self): print("Commands: " + str(self.commands)) print("Statuses: " + str(self.status))<|fim▁end|>
li = full.split('?') param = li[-1] cmd = li[0]
<|file_name|>hazc_device.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 from zeroconf import Zeroconf, ServiceInfo import socket import configparser from . import hazc_cmd # import pdb class hazc_device: #Forward constants NO_PARAM = hazc_cmd.NO_PARAM BOOL = hazc_cmd.BOOL FLOAT = hazc_cmd.FLOAT STRING = hazc_cmd.STRING INT = hazc_cmd.INT global running running = False def __init__(self, ipaddr): self.version = "0.1" self.config = configparser.ConfigParser() self.config.read('config.ini') self.MSGLEN = 1024 self.END_OF_MSG = '*' self.ip = ipaddr self.buffer = 20 # self.commands = {'version?':self.version_cmd,'commands?':self.commands_cmd,'status?':self.status_cmd} hcvc = hazc_cmd.hazc_cmd('version?', self.version_cmd, self.NO_PARAM) hccc = hazc_cmd.hazc_cmd('commands?', self.commands_cmd, self.NO_PARAM) hcsc = hazc_cmd.hazc_cmd('status?', self.status_cmd, self.STRING) self.commands = {'version': hcvc, 'commands': hccc, 'status': hcsc} # probably want to add a debug log status self.status = {'exec_status': self.exec_status} #Adds a function - not as preferred as addControl #Does NOT auto add status def addFunction(self, name, handler, paramtype): # pdb.settrace() #log("This is not the preferred way to add controls, see addControl") if not('?' in name or '!' in name): # log("Function name requires a '?' or '!', assuming '!'") name += '!' self.commands[name] = hazc_cmd.hazc_cmd(name, handler, paramtype) #Adds a control vector #controlname should just be a name like 'temp' or 'position' - it'll be the same for the status def addControl(self, controlname, handler, statushandler, paramtype=NO_PARAM): cmd_name = 'set-'+controlname self.commands[cmd_name] = hazc_cmd.hazc_cmd(cmd_name+'?', handler, paramtype) self.addStatus(controlname, statushandler) #adds a unique status not already included in control vector. name is just the name, as in 'temp' def addStatus(self, name, handler): self.status[name] = handler def advertise(self): postfix = self.config['global']['service_prefix'] self.port = int(self.config['global']['port']) #print(self.config['device']['hostname']+postfix) info = ServiceInfo(postfix, self.config['device']['hostname']+"."+postfix, socket.inet_aton(self.ip), self.port, 0, 0, {'info': self.config['device']['description']}, "hazc.local.") self.bindConnection() zeroconf = Zeroconf() zeroconf.register_service(info) try: while True: # try: print("Ready") self.conn, self.addr = self.webcontrol.accept() self.listen() self.conn.close() except KeyboardInterrupt: pass finally: print() print("Unregistering...") zeroconf.unregister_service(info) zeroconf.close() try: print("Shutting down socket") self.webcontrol.shutdown(socket.SHUT_RDWR) except Exception as e: print(e) def listen(self): data = bytes() rbytes = 0 while rbytes < self.MSGLEN: d = self.conn.recv(self.buffer) if not d: break data += d rbytes += len(d) # print data.decode('utf-8') self.handledata(data) def handledata(self, data): command, param = self.cleanandstringdata(data) print('->' + command + ';' + param) # replystr = "ERROR" try: replystr = self.commands[command].execute(param) except KeyError: if(command==''): command = "(empty string)" print("ERROR! Unknown command: " + command) replystr = "" # replystr = self.commands['version'].execute('') if(replystr == None): print("WARNING! " + command + " should return a string to send to the master. Sending 'NO_REPLY'") replystr = 'NO_REPLY' print(replystr) self.reply(replystr) def reply(self, msg): longmsg = msg while len(longmsg) < self.MSGLEN: longmsg += self.END_OF_MSG # print(longmsg) self.conn.send(longmsg.encode('utf-8')) def cleanandstringdata(self, data): dstr = data.decode('utf-8') full = dstr.strip(self.END_OF_MSG) if '?' in full: li = full.split('?') param = li[-1] cmd = li[0] elif '!' in full: <|fim_middle|> else: param = '' cmd = full return (cmd, param) def bindConnection(self): try: self.webcontrol = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.webcontrol.bind((self.ip, self.port)) self.webcontrol.listen(1) except OSError as e: print(e) quit() def exec_status(self): return "Running" def version_cmd(self): return self.version def paramtype_tostring(self, paramnum): if paramnum == self.BOOL: return 'BOOL' elif paramnum == self.FLOAT: return 'FLOAT' elif paramnum == self.STRING: return 'STRING' elif paramnum == self.INT: return 'INT' else: return 'PARAM_ERROR' def commands_cmd(self): rstr = "" for key in self.commands: rstr += key if self.commands[key].paramtype is not self.NO_PARAM: # pdb.set_trace() rstr += ':' + self.paramtype_tostring(self.commands[key].paramtype) rstr += ";" return rstr def status_cmd(self, specific_status=''): str = '' if len(specific_status) > 0: str = self.status[specific_status] else: for st in self.status: str += st + ',' + self.status[st]() + ';' return str[:self.MSGLEN-1] # Some debugging methods def debug_cmds(self): print("Commands: " + str(self.commands)) print("Statuses: " + str(self.status))<|fim▁end|>
li = full.split('!') param = li[-1] cmd = li[0]
<|file_name|>hazc_device.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 from zeroconf import Zeroconf, ServiceInfo import socket import configparser from . import hazc_cmd # import pdb class hazc_device: #Forward constants NO_PARAM = hazc_cmd.NO_PARAM BOOL = hazc_cmd.BOOL FLOAT = hazc_cmd.FLOAT STRING = hazc_cmd.STRING INT = hazc_cmd.INT global running running = False def __init__(self, ipaddr): self.version = "0.1" self.config = configparser.ConfigParser() self.config.read('config.ini') self.MSGLEN = 1024 self.END_OF_MSG = '*' self.ip = ipaddr self.buffer = 20 # self.commands = {'version?':self.version_cmd,'commands?':self.commands_cmd,'status?':self.status_cmd} hcvc = hazc_cmd.hazc_cmd('version?', self.version_cmd, self.NO_PARAM) hccc = hazc_cmd.hazc_cmd('commands?', self.commands_cmd, self.NO_PARAM) hcsc = hazc_cmd.hazc_cmd('status?', self.status_cmd, self.STRING) self.commands = {'version': hcvc, 'commands': hccc, 'status': hcsc} # probably want to add a debug log status self.status = {'exec_status': self.exec_status} #Adds a function - not as preferred as addControl #Does NOT auto add status def addFunction(self, name, handler, paramtype): # pdb.settrace() #log("This is not the preferred way to add controls, see addControl") if not('?' in name or '!' in name): # log("Function name requires a '?' or '!', assuming '!'") name += '!' self.commands[name] = hazc_cmd.hazc_cmd(name, handler, paramtype) #Adds a control vector #controlname should just be a name like 'temp' or 'position' - it'll be the same for the status def addControl(self, controlname, handler, statushandler, paramtype=NO_PARAM): cmd_name = 'set-'+controlname self.commands[cmd_name] = hazc_cmd.hazc_cmd(cmd_name+'?', handler, paramtype) self.addStatus(controlname, statushandler) #adds a unique status not already included in control vector. name is just the name, as in 'temp' def addStatus(self, name, handler): self.status[name] = handler def advertise(self): postfix = self.config['global']['service_prefix'] self.port = int(self.config['global']['port']) #print(self.config['device']['hostname']+postfix) info = ServiceInfo(postfix, self.config['device']['hostname']+"."+postfix, socket.inet_aton(self.ip), self.port, 0, 0, {'info': self.config['device']['description']}, "hazc.local.") self.bindConnection() zeroconf = Zeroconf() zeroconf.register_service(info) try: while True: # try: print("Ready") self.conn, self.addr = self.webcontrol.accept() self.listen() self.conn.close() except KeyboardInterrupt: pass finally: print() print("Unregistering...") zeroconf.unregister_service(info) zeroconf.close() try: print("Shutting down socket") self.webcontrol.shutdown(socket.SHUT_RDWR) except Exception as e: print(e) def listen(self): data = bytes() rbytes = 0 while rbytes < self.MSGLEN: d = self.conn.recv(self.buffer) if not d: break data += d rbytes += len(d) # print data.decode('utf-8') self.handledata(data) def handledata(self, data): command, param = self.cleanandstringdata(data) print('->' + command + ';' + param) # replystr = "ERROR" try: replystr = self.commands[command].execute(param) except KeyError: if(command==''): command = "(empty string)" print("ERROR! Unknown command: " + command) replystr = "" # replystr = self.commands['version'].execute('') if(replystr == None): print("WARNING! " + command + " should return a string to send to the master. Sending 'NO_REPLY'") replystr = 'NO_REPLY' print(replystr) self.reply(replystr) def reply(self, msg): longmsg = msg while len(longmsg) < self.MSGLEN: longmsg += self.END_OF_MSG # print(longmsg) self.conn.send(longmsg.encode('utf-8')) def cleanandstringdata(self, data): dstr = data.decode('utf-8') full = dstr.strip(self.END_OF_MSG) if '?' in full: li = full.split('?') param = li[-1] cmd = li[0] elif '!' in full: li = full.split('!') param = li[-1] cmd = li[0] else: <|fim_middle|> return (cmd, param) def bindConnection(self): try: self.webcontrol = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.webcontrol.bind((self.ip, self.port)) self.webcontrol.listen(1) except OSError as e: print(e) quit() def exec_status(self): return "Running" def version_cmd(self): return self.version def paramtype_tostring(self, paramnum): if paramnum == self.BOOL: return 'BOOL' elif paramnum == self.FLOAT: return 'FLOAT' elif paramnum == self.STRING: return 'STRING' elif paramnum == self.INT: return 'INT' else: return 'PARAM_ERROR' def commands_cmd(self): rstr = "" for key in self.commands: rstr += key if self.commands[key].paramtype is not self.NO_PARAM: # pdb.set_trace() rstr += ':' + self.paramtype_tostring(self.commands[key].paramtype) rstr += ";" return rstr def status_cmd(self, specific_status=''): str = '' if len(specific_status) > 0: str = self.status[specific_status] else: for st in self.status: str += st + ',' + self.status[st]() + ';' return str[:self.MSGLEN-1] # Some debugging methods def debug_cmds(self): print("Commands: " + str(self.commands)) print("Statuses: " + str(self.status))<|fim▁end|>
param = '' cmd = full
<|file_name|>hazc_device.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 from zeroconf import Zeroconf, ServiceInfo import socket import configparser from . import hazc_cmd # import pdb class hazc_device: #Forward constants NO_PARAM = hazc_cmd.NO_PARAM BOOL = hazc_cmd.BOOL FLOAT = hazc_cmd.FLOAT STRING = hazc_cmd.STRING INT = hazc_cmd.INT global running running = False def __init__(self, ipaddr): self.version = "0.1" self.config = configparser.ConfigParser() self.config.read('config.ini') self.MSGLEN = 1024 self.END_OF_MSG = '*' self.ip = ipaddr self.buffer = 20 # self.commands = {'version?':self.version_cmd,'commands?':self.commands_cmd,'status?':self.status_cmd} hcvc = hazc_cmd.hazc_cmd('version?', self.version_cmd, self.NO_PARAM) hccc = hazc_cmd.hazc_cmd('commands?', self.commands_cmd, self.NO_PARAM) hcsc = hazc_cmd.hazc_cmd('status?', self.status_cmd, self.STRING) self.commands = {'version': hcvc, 'commands': hccc, 'status': hcsc} # probably want to add a debug log status self.status = {'exec_status': self.exec_status} #Adds a function - not as preferred as addControl #Does NOT auto add status def addFunction(self, name, handler, paramtype): # pdb.settrace() #log("This is not the preferred way to add controls, see addControl") if not('?' in name or '!' in name): # log("Function name requires a '?' or '!', assuming '!'") name += '!' self.commands[name] = hazc_cmd.hazc_cmd(name, handler, paramtype) #Adds a control vector #controlname should just be a name like 'temp' or 'position' - it'll be the same for the status def addControl(self, controlname, handler, statushandler, paramtype=NO_PARAM): cmd_name = 'set-'+controlname self.commands[cmd_name] = hazc_cmd.hazc_cmd(cmd_name+'?', handler, paramtype) self.addStatus(controlname, statushandler) #adds a unique status not already included in control vector. name is just the name, as in 'temp' def addStatus(self, name, handler): self.status[name] = handler def advertise(self): postfix = self.config['global']['service_prefix'] self.port = int(self.config['global']['port']) #print(self.config['device']['hostname']+postfix) info = ServiceInfo(postfix, self.config['device']['hostname']+"."+postfix, socket.inet_aton(self.ip), self.port, 0, 0, {'info': self.config['device']['description']}, "hazc.local.") self.bindConnection() zeroconf = Zeroconf() zeroconf.register_service(info) try: while True: # try: print("Ready") self.conn, self.addr = self.webcontrol.accept() self.listen() self.conn.close() except KeyboardInterrupt: pass finally: print() print("Unregistering...") zeroconf.unregister_service(info) zeroconf.close() try: print("Shutting down socket") self.webcontrol.shutdown(socket.SHUT_RDWR) except Exception as e: print(e) def listen(self): data = bytes() rbytes = 0 while rbytes < self.MSGLEN: d = self.conn.recv(self.buffer) if not d: break data += d rbytes += len(d) # print data.decode('utf-8') self.handledata(data) def handledata(self, data): command, param = self.cleanandstringdata(data) print('->' + command + ';' + param) # replystr = "ERROR" try: replystr = self.commands[command].execute(param) except KeyError: if(command==''): command = "(empty string)" print("ERROR! Unknown command: " + command) replystr = "" # replystr = self.commands['version'].execute('') if(replystr == None): print("WARNING! " + command + " should return a string to send to the master. Sending 'NO_REPLY'") replystr = 'NO_REPLY' print(replystr) self.reply(replystr) def reply(self, msg): longmsg = msg while len(longmsg) < self.MSGLEN: longmsg += self.END_OF_MSG # print(longmsg) self.conn.send(longmsg.encode('utf-8')) def cleanandstringdata(self, data): dstr = data.decode('utf-8') full = dstr.strip(self.END_OF_MSG) if '?' in full: li = full.split('?') param = li[-1] cmd = li[0] elif '!' in full: li = full.split('!') param = li[-1] cmd = li[0] else: param = '' cmd = full return (cmd, param) def bindConnection(self): try: self.webcontrol = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.webcontrol.bind((self.ip, self.port)) self.webcontrol.listen(1) except OSError as e: print(e) quit() def exec_status(self): return "Running" def version_cmd(self): return self.version def paramtype_tostring(self, paramnum): if paramnum == self.BOOL: <|fim_middle|> elif paramnum == self.FLOAT: return 'FLOAT' elif paramnum == self.STRING: return 'STRING' elif paramnum == self.INT: return 'INT' else: return 'PARAM_ERROR' def commands_cmd(self): rstr = "" for key in self.commands: rstr += key if self.commands[key].paramtype is not self.NO_PARAM: # pdb.set_trace() rstr += ':' + self.paramtype_tostring(self.commands[key].paramtype) rstr += ";" return rstr def status_cmd(self, specific_status=''): str = '' if len(specific_status) > 0: str = self.status[specific_status] else: for st in self.status: str += st + ',' + self.status[st]() + ';' return str[:self.MSGLEN-1] # Some debugging methods def debug_cmds(self): print("Commands: " + str(self.commands)) print("Statuses: " + str(self.status))<|fim▁end|>
return 'BOOL'
<|file_name|>hazc_device.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 from zeroconf import Zeroconf, ServiceInfo import socket import configparser from . import hazc_cmd # import pdb class hazc_device: #Forward constants NO_PARAM = hazc_cmd.NO_PARAM BOOL = hazc_cmd.BOOL FLOAT = hazc_cmd.FLOAT STRING = hazc_cmd.STRING INT = hazc_cmd.INT global running running = False def __init__(self, ipaddr): self.version = "0.1" self.config = configparser.ConfigParser() self.config.read('config.ini') self.MSGLEN = 1024 self.END_OF_MSG = '*' self.ip = ipaddr self.buffer = 20 # self.commands = {'version?':self.version_cmd,'commands?':self.commands_cmd,'status?':self.status_cmd} hcvc = hazc_cmd.hazc_cmd('version?', self.version_cmd, self.NO_PARAM) hccc = hazc_cmd.hazc_cmd('commands?', self.commands_cmd, self.NO_PARAM) hcsc = hazc_cmd.hazc_cmd('status?', self.status_cmd, self.STRING) self.commands = {'version': hcvc, 'commands': hccc, 'status': hcsc} # probably want to add a debug log status self.status = {'exec_status': self.exec_status} #Adds a function - not as preferred as addControl #Does NOT auto add status def addFunction(self, name, handler, paramtype): # pdb.settrace() #log("This is not the preferred way to add controls, see addControl") if not('?' in name or '!' in name): # log("Function name requires a '?' or '!', assuming '!'") name += '!' self.commands[name] = hazc_cmd.hazc_cmd(name, handler, paramtype) #Adds a control vector #controlname should just be a name like 'temp' or 'position' - it'll be the same for the status def addControl(self, controlname, handler, statushandler, paramtype=NO_PARAM): cmd_name = 'set-'+controlname self.commands[cmd_name] = hazc_cmd.hazc_cmd(cmd_name+'?', handler, paramtype) self.addStatus(controlname, statushandler) #adds a unique status not already included in control vector. name is just the name, as in 'temp' def addStatus(self, name, handler): self.status[name] = handler def advertise(self): postfix = self.config['global']['service_prefix'] self.port = int(self.config['global']['port']) #print(self.config['device']['hostname']+postfix) info = ServiceInfo(postfix, self.config['device']['hostname']+"."+postfix, socket.inet_aton(self.ip), self.port, 0, 0, {'info': self.config['device']['description']}, "hazc.local.") self.bindConnection() zeroconf = Zeroconf() zeroconf.register_service(info) try: while True: # try: print("Ready") self.conn, self.addr = self.webcontrol.accept() self.listen() self.conn.close() except KeyboardInterrupt: pass finally: print() print("Unregistering...") zeroconf.unregister_service(info) zeroconf.close() try: print("Shutting down socket") self.webcontrol.shutdown(socket.SHUT_RDWR) except Exception as e: print(e) def listen(self): data = bytes() rbytes = 0 while rbytes < self.MSGLEN: d = self.conn.recv(self.buffer) if not d: break data += d rbytes += len(d) # print data.decode('utf-8') self.handledata(data) def handledata(self, data): command, param = self.cleanandstringdata(data) print('->' + command + ';' + param) # replystr = "ERROR" try: replystr = self.commands[command].execute(param) except KeyError: if(command==''): command = "(empty string)" print("ERROR! Unknown command: " + command) replystr = "" # replystr = self.commands['version'].execute('') if(replystr == None): print("WARNING! " + command + " should return a string to send to the master. Sending 'NO_REPLY'") replystr = 'NO_REPLY' print(replystr) self.reply(replystr) def reply(self, msg): longmsg = msg while len(longmsg) < self.MSGLEN: longmsg += self.END_OF_MSG # print(longmsg) self.conn.send(longmsg.encode('utf-8')) def cleanandstringdata(self, data): dstr = data.decode('utf-8') full = dstr.strip(self.END_OF_MSG) if '?' in full: li = full.split('?') param = li[-1] cmd = li[0] elif '!' in full: li = full.split('!') param = li[-1] cmd = li[0] else: param = '' cmd = full return (cmd, param) def bindConnection(self): try: self.webcontrol = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.webcontrol.bind((self.ip, self.port)) self.webcontrol.listen(1) except OSError as e: print(e) quit() def exec_status(self): return "Running" def version_cmd(self): return self.version def paramtype_tostring(self, paramnum): if paramnum == self.BOOL: return 'BOOL' elif paramnum == self.FLOAT: <|fim_middle|> elif paramnum == self.STRING: return 'STRING' elif paramnum == self.INT: return 'INT' else: return 'PARAM_ERROR' def commands_cmd(self): rstr = "" for key in self.commands: rstr += key if self.commands[key].paramtype is not self.NO_PARAM: # pdb.set_trace() rstr += ':' + self.paramtype_tostring(self.commands[key].paramtype) rstr += ";" return rstr def status_cmd(self, specific_status=''): str = '' if len(specific_status) > 0: str = self.status[specific_status] else: for st in self.status: str += st + ',' + self.status[st]() + ';' return str[:self.MSGLEN-1] # Some debugging methods def debug_cmds(self): print("Commands: " + str(self.commands)) print("Statuses: " + str(self.status))<|fim▁end|>
return 'FLOAT'
<|file_name|>hazc_device.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 from zeroconf import Zeroconf, ServiceInfo import socket import configparser from . import hazc_cmd # import pdb class hazc_device: #Forward constants NO_PARAM = hazc_cmd.NO_PARAM BOOL = hazc_cmd.BOOL FLOAT = hazc_cmd.FLOAT STRING = hazc_cmd.STRING INT = hazc_cmd.INT global running running = False def __init__(self, ipaddr): self.version = "0.1" self.config = configparser.ConfigParser() self.config.read('config.ini') self.MSGLEN = 1024 self.END_OF_MSG = '*' self.ip = ipaddr self.buffer = 20 # self.commands = {'version?':self.version_cmd,'commands?':self.commands_cmd,'status?':self.status_cmd} hcvc = hazc_cmd.hazc_cmd('version?', self.version_cmd, self.NO_PARAM) hccc = hazc_cmd.hazc_cmd('commands?', self.commands_cmd, self.NO_PARAM) hcsc = hazc_cmd.hazc_cmd('status?', self.status_cmd, self.STRING) self.commands = {'version': hcvc, 'commands': hccc, 'status': hcsc} # probably want to add a debug log status self.status = {'exec_status': self.exec_status} #Adds a function - not as preferred as addControl #Does NOT auto add status def addFunction(self, name, handler, paramtype): # pdb.settrace() #log("This is not the preferred way to add controls, see addControl") if not('?' in name or '!' in name): # log("Function name requires a '?' or '!', assuming '!'") name += '!' self.commands[name] = hazc_cmd.hazc_cmd(name, handler, paramtype) #Adds a control vector #controlname should just be a name like 'temp' or 'position' - it'll be the same for the status def addControl(self, controlname, handler, statushandler, paramtype=NO_PARAM): cmd_name = 'set-'+controlname self.commands[cmd_name] = hazc_cmd.hazc_cmd(cmd_name+'?', handler, paramtype) self.addStatus(controlname, statushandler) #adds a unique status not already included in control vector. name is just the name, as in 'temp' def addStatus(self, name, handler): self.status[name] = handler def advertise(self): postfix = self.config['global']['service_prefix'] self.port = int(self.config['global']['port']) #print(self.config['device']['hostname']+postfix) info = ServiceInfo(postfix, self.config['device']['hostname']+"."+postfix, socket.inet_aton(self.ip), self.port, 0, 0, {'info': self.config['device']['description']}, "hazc.local.") self.bindConnection() zeroconf = Zeroconf() zeroconf.register_service(info) try: while True: # try: print("Ready") self.conn, self.addr = self.webcontrol.accept() self.listen() self.conn.close() except KeyboardInterrupt: pass finally: print() print("Unregistering...") zeroconf.unregister_service(info) zeroconf.close() try: print("Shutting down socket") self.webcontrol.shutdown(socket.SHUT_RDWR) except Exception as e: print(e) def listen(self): data = bytes() rbytes = 0 while rbytes < self.MSGLEN: d = self.conn.recv(self.buffer) if not d: break data += d rbytes += len(d) # print data.decode('utf-8') self.handledata(data) def handledata(self, data): command, param = self.cleanandstringdata(data) print('->' + command + ';' + param) # replystr = "ERROR" try: replystr = self.commands[command].execute(param) except KeyError: if(command==''): command = "(empty string)" print("ERROR! Unknown command: " + command) replystr = "" # replystr = self.commands['version'].execute('') if(replystr == None): print("WARNING! " + command + " should return a string to send to the master. Sending 'NO_REPLY'") replystr = 'NO_REPLY' print(replystr) self.reply(replystr) def reply(self, msg): longmsg = msg while len(longmsg) < self.MSGLEN: longmsg += self.END_OF_MSG # print(longmsg) self.conn.send(longmsg.encode('utf-8')) def cleanandstringdata(self, data): dstr = data.decode('utf-8') full = dstr.strip(self.END_OF_MSG) if '?' in full: li = full.split('?') param = li[-1] cmd = li[0] elif '!' in full: li = full.split('!') param = li[-1] cmd = li[0] else: param = '' cmd = full return (cmd, param) def bindConnection(self): try: self.webcontrol = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.webcontrol.bind((self.ip, self.port)) self.webcontrol.listen(1) except OSError as e: print(e) quit() def exec_status(self): return "Running" def version_cmd(self): return self.version def paramtype_tostring(self, paramnum): if paramnum == self.BOOL: return 'BOOL' elif paramnum == self.FLOAT: return 'FLOAT' elif paramnum == self.STRING: <|fim_middle|> elif paramnum == self.INT: return 'INT' else: return 'PARAM_ERROR' def commands_cmd(self): rstr = "" for key in self.commands: rstr += key if self.commands[key].paramtype is not self.NO_PARAM: # pdb.set_trace() rstr += ':' + self.paramtype_tostring(self.commands[key].paramtype) rstr += ";" return rstr def status_cmd(self, specific_status=''): str = '' if len(specific_status) > 0: str = self.status[specific_status] else: for st in self.status: str += st + ',' + self.status[st]() + ';' return str[:self.MSGLEN-1] # Some debugging methods def debug_cmds(self): print("Commands: " + str(self.commands)) print("Statuses: " + str(self.status))<|fim▁end|>
return 'STRING'
<|file_name|>hazc_device.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 from zeroconf import Zeroconf, ServiceInfo import socket import configparser from . import hazc_cmd # import pdb class hazc_device: #Forward constants NO_PARAM = hazc_cmd.NO_PARAM BOOL = hazc_cmd.BOOL FLOAT = hazc_cmd.FLOAT STRING = hazc_cmd.STRING INT = hazc_cmd.INT global running running = False def __init__(self, ipaddr): self.version = "0.1" self.config = configparser.ConfigParser() self.config.read('config.ini') self.MSGLEN = 1024 self.END_OF_MSG = '*' self.ip = ipaddr self.buffer = 20 # self.commands = {'version?':self.version_cmd,'commands?':self.commands_cmd,'status?':self.status_cmd} hcvc = hazc_cmd.hazc_cmd('version?', self.version_cmd, self.NO_PARAM) hccc = hazc_cmd.hazc_cmd('commands?', self.commands_cmd, self.NO_PARAM) hcsc = hazc_cmd.hazc_cmd('status?', self.status_cmd, self.STRING) self.commands = {'version': hcvc, 'commands': hccc, 'status': hcsc} # probably want to add a debug log status self.status = {'exec_status': self.exec_status} #Adds a function - not as preferred as addControl #Does NOT auto add status def addFunction(self, name, handler, paramtype): # pdb.settrace() #log("This is not the preferred way to add controls, see addControl") if not('?' in name or '!' in name): # log("Function name requires a '?' or '!', assuming '!'") name += '!' self.commands[name] = hazc_cmd.hazc_cmd(name, handler, paramtype) #Adds a control vector #controlname should just be a name like 'temp' or 'position' - it'll be the same for the status def addControl(self, controlname, handler, statushandler, paramtype=NO_PARAM): cmd_name = 'set-'+controlname self.commands[cmd_name] = hazc_cmd.hazc_cmd(cmd_name+'?', handler, paramtype) self.addStatus(controlname, statushandler) #adds a unique status not already included in control vector. name is just the name, as in 'temp' def addStatus(self, name, handler): self.status[name] = handler def advertise(self): postfix = self.config['global']['service_prefix'] self.port = int(self.config['global']['port']) #print(self.config['device']['hostname']+postfix) info = ServiceInfo(postfix, self.config['device']['hostname']+"."+postfix, socket.inet_aton(self.ip), self.port, 0, 0, {'info': self.config['device']['description']}, "hazc.local.") self.bindConnection() zeroconf = Zeroconf() zeroconf.register_service(info) try: while True: # try: print("Ready") self.conn, self.addr = self.webcontrol.accept() self.listen() self.conn.close() except KeyboardInterrupt: pass finally: print() print("Unregistering...") zeroconf.unregister_service(info) zeroconf.close() try: print("Shutting down socket") self.webcontrol.shutdown(socket.SHUT_RDWR) except Exception as e: print(e) def listen(self): data = bytes() rbytes = 0 while rbytes < self.MSGLEN: d = self.conn.recv(self.buffer) if not d: break data += d rbytes += len(d) # print data.decode('utf-8') self.handledata(data) def handledata(self, data): command, param = self.cleanandstringdata(data) print('->' + command + ';' + param) # replystr = "ERROR" try: replystr = self.commands[command].execute(param) except KeyError: if(command==''): command = "(empty string)" print("ERROR! Unknown command: " + command) replystr = "" # replystr = self.commands['version'].execute('') if(replystr == None): print("WARNING! " + command + " should return a string to send to the master. Sending 'NO_REPLY'") replystr = 'NO_REPLY' print(replystr) self.reply(replystr) def reply(self, msg): longmsg = msg while len(longmsg) < self.MSGLEN: longmsg += self.END_OF_MSG # print(longmsg) self.conn.send(longmsg.encode('utf-8')) def cleanandstringdata(self, data): dstr = data.decode('utf-8') full = dstr.strip(self.END_OF_MSG) if '?' in full: li = full.split('?') param = li[-1] cmd = li[0] elif '!' in full: li = full.split('!') param = li[-1] cmd = li[0] else: param = '' cmd = full return (cmd, param) def bindConnection(self): try: self.webcontrol = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.webcontrol.bind((self.ip, self.port)) self.webcontrol.listen(1) except OSError as e: print(e) quit() def exec_status(self): return "Running" def version_cmd(self): return self.version def paramtype_tostring(self, paramnum): if paramnum == self.BOOL: return 'BOOL' elif paramnum == self.FLOAT: return 'FLOAT' elif paramnum == self.STRING: return 'STRING' elif paramnum == self.INT: <|fim_middle|> else: return 'PARAM_ERROR' def commands_cmd(self): rstr = "" for key in self.commands: rstr += key if self.commands[key].paramtype is not self.NO_PARAM: # pdb.set_trace() rstr += ':' + self.paramtype_tostring(self.commands[key].paramtype) rstr += ";" return rstr def status_cmd(self, specific_status=''): str = '' if len(specific_status) > 0: str = self.status[specific_status] else: for st in self.status: str += st + ',' + self.status[st]() + ';' return str[:self.MSGLEN-1] # Some debugging methods def debug_cmds(self): print("Commands: " + str(self.commands)) print("Statuses: " + str(self.status))<|fim▁end|>
return 'INT'
<|file_name|>hazc_device.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 from zeroconf import Zeroconf, ServiceInfo import socket import configparser from . import hazc_cmd # import pdb class hazc_device: #Forward constants NO_PARAM = hazc_cmd.NO_PARAM BOOL = hazc_cmd.BOOL FLOAT = hazc_cmd.FLOAT STRING = hazc_cmd.STRING INT = hazc_cmd.INT global running running = False def __init__(self, ipaddr): self.version = "0.1" self.config = configparser.ConfigParser() self.config.read('config.ini') self.MSGLEN = 1024 self.END_OF_MSG = '*' self.ip = ipaddr self.buffer = 20 # self.commands = {'version?':self.version_cmd,'commands?':self.commands_cmd,'status?':self.status_cmd} hcvc = hazc_cmd.hazc_cmd('version?', self.version_cmd, self.NO_PARAM) hccc = hazc_cmd.hazc_cmd('commands?', self.commands_cmd, self.NO_PARAM) hcsc = hazc_cmd.hazc_cmd('status?', self.status_cmd, self.STRING) self.commands = {'version': hcvc, 'commands': hccc, 'status': hcsc} # probably want to add a debug log status self.status = {'exec_status': self.exec_status} #Adds a function - not as preferred as addControl #Does NOT auto add status def addFunction(self, name, handler, paramtype): # pdb.settrace() #log("This is not the preferred way to add controls, see addControl") if not('?' in name or '!' in name): # log("Function name requires a '?' or '!', assuming '!'") name += '!' self.commands[name] = hazc_cmd.hazc_cmd(name, handler, paramtype) #Adds a control vector #controlname should just be a name like 'temp' or 'position' - it'll be the same for the status def addControl(self, controlname, handler, statushandler, paramtype=NO_PARAM): cmd_name = 'set-'+controlname self.commands[cmd_name] = hazc_cmd.hazc_cmd(cmd_name+'?', handler, paramtype) self.addStatus(controlname, statushandler) #adds a unique status not already included in control vector. name is just the name, as in 'temp' def addStatus(self, name, handler): self.status[name] = handler def advertise(self): postfix = self.config['global']['service_prefix'] self.port = int(self.config['global']['port']) #print(self.config['device']['hostname']+postfix) info = ServiceInfo(postfix, self.config['device']['hostname']+"."+postfix, socket.inet_aton(self.ip), self.port, 0, 0, {'info': self.config['device']['description']}, "hazc.local.") self.bindConnection() zeroconf = Zeroconf() zeroconf.register_service(info) try: while True: # try: print("Ready") self.conn, self.addr = self.webcontrol.accept() self.listen() self.conn.close() except KeyboardInterrupt: pass finally: print() print("Unregistering...") zeroconf.unregister_service(info) zeroconf.close() try: print("Shutting down socket") self.webcontrol.shutdown(socket.SHUT_RDWR) except Exception as e: print(e) def listen(self): data = bytes() rbytes = 0 while rbytes < self.MSGLEN: d = self.conn.recv(self.buffer) if not d: break data += d rbytes += len(d) # print data.decode('utf-8') self.handledata(data) def handledata(self, data): command, param = self.cleanandstringdata(data) print('->' + command + ';' + param) # replystr = "ERROR" try: replystr = self.commands[command].execute(param) except KeyError: if(command==''): command = "(empty string)" print("ERROR! Unknown command: " + command) replystr = "" # replystr = self.commands['version'].execute('') if(replystr == None): print("WARNING! " + command + " should return a string to send to the master. Sending 'NO_REPLY'") replystr = 'NO_REPLY' print(replystr) self.reply(replystr) def reply(self, msg): longmsg = msg while len(longmsg) < self.MSGLEN: longmsg += self.END_OF_MSG # print(longmsg) self.conn.send(longmsg.encode('utf-8')) def cleanandstringdata(self, data): dstr = data.decode('utf-8') full = dstr.strip(self.END_OF_MSG) if '?' in full: li = full.split('?') param = li[-1] cmd = li[0] elif '!' in full: li = full.split('!') param = li[-1] cmd = li[0] else: param = '' cmd = full return (cmd, param) def bindConnection(self): try: self.webcontrol = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.webcontrol.bind((self.ip, self.port)) self.webcontrol.listen(1) except OSError as e: print(e) quit() def exec_status(self): return "Running" def version_cmd(self): return self.version def paramtype_tostring(self, paramnum): if paramnum == self.BOOL: return 'BOOL' elif paramnum == self.FLOAT: return 'FLOAT' elif paramnum == self.STRING: return 'STRING' elif paramnum == self.INT: return 'INT' else: <|fim_middle|> def commands_cmd(self): rstr = "" for key in self.commands: rstr += key if self.commands[key].paramtype is not self.NO_PARAM: # pdb.set_trace() rstr += ':' + self.paramtype_tostring(self.commands[key].paramtype) rstr += ";" return rstr def status_cmd(self, specific_status=''): str = '' if len(specific_status) > 0: str = self.status[specific_status] else: for st in self.status: str += st + ',' + self.status[st]() + ';' return str[:self.MSGLEN-1] # Some debugging methods def debug_cmds(self): print("Commands: " + str(self.commands)) print("Statuses: " + str(self.status))<|fim▁end|>
return 'PARAM_ERROR'
<|file_name|>hazc_device.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 from zeroconf import Zeroconf, ServiceInfo import socket import configparser from . import hazc_cmd # import pdb class hazc_device: #Forward constants NO_PARAM = hazc_cmd.NO_PARAM BOOL = hazc_cmd.BOOL FLOAT = hazc_cmd.FLOAT STRING = hazc_cmd.STRING INT = hazc_cmd.INT global running running = False def __init__(self, ipaddr): self.version = "0.1" self.config = configparser.ConfigParser() self.config.read('config.ini') self.MSGLEN = 1024 self.END_OF_MSG = '*' self.ip = ipaddr self.buffer = 20 # self.commands = {'version?':self.version_cmd,'commands?':self.commands_cmd,'status?':self.status_cmd} hcvc = hazc_cmd.hazc_cmd('version?', self.version_cmd, self.NO_PARAM) hccc = hazc_cmd.hazc_cmd('commands?', self.commands_cmd, self.NO_PARAM) hcsc = hazc_cmd.hazc_cmd('status?', self.status_cmd, self.STRING) self.commands = {'version': hcvc, 'commands': hccc, 'status': hcsc} # probably want to add a debug log status self.status = {'exec_status': self.exec_status} #Adds a function - not as preferred as addControl #Does NOT auto add status def addFunction(self, name, handler, paramtype): # pdb.settrace() #log("This is not the preferred way to add controls, see addControl") if not('?' in name or '!' in name): # log("Function name requires a '?' or '!', assuming '!'") name += '!' self.commands[name] = hazc_cmd.hazc_cmd(name, handler, paramtype) #Adds a control vector #controlname should just be a name like 'temp' or 'position' - it'll be the same for the status def addControl(self, controlname, handler, statushandler, paramtype=NO_PARAM): cmd_name = 'set-'+controlname self.commands[cmd_name] = hazc_cmd.hazc_cmd(cmd_name+'?', handler, paramtype) self.addStatus(controlname, statushandler) #adds a unique status not already included in control vector. name is just the name, as in 'temp' def addStatus(self, name, handler): self.status[name] = handler def advertise(self): postfix = self.config['global']['service_prefix'] self.port = int(self.config['global']['port']) #print(self.config['device']['hostname']+postfix) info = ServiceInfo(postfix, self.config['device']['hostname']+"."+postfix, socket.inet_aton(self.ip), self.port, 0, 0, {'info': self.config['device']['description']}, "hazc.local.") self.bindConnection() zeroconf = Zeroconf() zeroconf.register_service(info) try: while True: # try: print("Ready") self.conn, self.addr = self.webcontrol.accept() self.listen() self.conn.close() except KeyboardInterrupt: pass finally: print() print("Unregistering...") zeroconf.unregister_service(info) zeroconf.close() try: print("Shutting down socket") self.webcontrol.shutdown(socket.SHUT_RDWR) except Exception as e: print(e) def listen(self): data = bytes() rbytes = 0 while rbytes < self.MSGLEN: d = self.conn.recv(self.buffer) if not d: break data += d rbytes += len(d) # print data.decode('utf-8') self.handledata(data) def handledata(self, data): command, param = self.cleanandstringdata(data) print('->' + command + ';' + param) # replystr = "ERROR" try: replystr = self.commands[command].execute(param) except KeyError: if(command==''): command = "(empty string)" print("ERROR! Unknown command: " + command) replystr = "" # replystr = self.commands['version'].execute('') if(replystr == None): print("WARNING! " + command + " should return a string to send to the master. Sending 'NO_REPLY'") replystr = 'NO_REPLY' print(replystr) self.reply(replystr) def reply(self, msg): longmsg = msg while len(longmsg) < self.MSGLEN: longmsg += self.END_OF_MSG # print(longmsg) self.conn.send(longmsg.encode('utf-8')) def cleanandstringdata(self, data): dstr = data.decode('utf-8') full = dstr.strip(self.END_OF_MSG) if '?' in full: li = full.split('?') param = li[-1] cmd = li[0] elif '!' in full: li = full.split('!') param = li[-1] cmd = li[0] else: param = '' cmd = full return (cmd, param) def bindConnection(self): try: self.webcontrol = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.webcontrol.bind((self.ip, self.port)) self.webcontrol.listen(1) except OSError as e: print(e) quit() def exec_status(self): return "Running" def version_cmd(self): return self.version def paramtype_tostring(self, paramnum): if paramnum == self.BOOL: return 'BOOL' elif paramnum == self.FLOAT: return 'FLOAT' elif paramnum == self.STRING: return 'STRING' elif paramnum == self.INT: return 'INT' else: return 'PARAM_ERROR' def commands_cmd(self): rstr = "" for key in self.commands: rstr += key if self.commands[key].paramtype is not self.NO_PARAM: # pdb.set_trace() <|fim_middle|> rstr += ";" return rstr def status_cmd(self, specific_status=''): str = '' if len(specific_status) > 0: str = self.status[specific_status] else: for st in self.status: str += st + ',' + self.status[st]() + ';' return str[:self.MSGLEN-1] # Some debugging methods def debug_cmds(self): print("Commands: " + str(self.commands)) print("Statuses: " + str(self.status))<|fim▁end|>
rstr += ':' + self.paramtype_tostring(self.commands[key].paramtype)
<|file_name|>hazc_device.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 from zeroconf import Zeroconf, ServiceInfo import socket import configparser from . import hazc_cmd # import pdb class hazc_device: #Forward constants NO_PARAM = hazc_cmd.NO_PARAM BOOL = hazc_cmd.BOOL FLOAT = hazc_cmd.FLOAT STRING = hazc_cmd.STRING INT = hazc_cmd.INT global running running = False def __init__(self, ipaddr): self.version = "0.1" self.config = configparser.ConfigParser() self.config.read('config.ini') self.MSGLEN = 1024 self.END_OF_MSG = '*' self.ip = ipaddr self.buffer = 20 # self.commands = {'version?':self.version_cmd,'commands?':self.commands_cmd,'status?':self.status_cmd} hcvc = hazc_cmd.hazc_cmd('version?', self.version_cmd, self.NO_PARAM) hccc = hazc_cmd.hazc_cmd('commands?', self.commands_cmd, self.NO_PARAM) hcsc = hazc_cmd.hazc_cmd('status?', self.status_cmd, self.STRING) self.commands = {'version': hcvc, 'commands': hccc, 'status': hcsc} # probably want to add a debug log status self.status = {'exec_status': self.exec_status} #Adds a function - not as preferred as addControl #Does NOT auto add status def addFunction(self, name, handler, paramtype): # pdb.settrace() #log("This is not the preferred way to add controls, see addControl") if not('?' in name or '!' in name): # log("Function name requires a '?' or '!', assuming '!'") name += '!' self.commands[name] = hazc_cmd.hazc_cmd(name, handler, paramtype) #Adds a control vector #controlname should just be a name like 'temp' or 'position' - it'll be the same for the status def addControl(self, controlname, handler, statushandler, paramtype=NO_PARAM): cmd_name = 'set-'+controlname self.commands[cmd_name] = hazc_cmd.hazc_cmd(cmd_name+'?', handler, paramtype) self.addStatus(controlname, statushandler) #adds a unique status not already included in control vector. name is just the name, as in 'temp' def addStatus(self, name, handler): self.status[name] = handler def advertise(self): postfix = self.config['global']['service_prefix'] self.port = int(self.config['global']['port']) #print(self.config['device']['hostname']+postfix) info = ServiceInfo(postfix, self.config['device']['hostname']+"."+postfix, socket.inet_aton(self.ip), self.port, 0, 0, {'info': self.config['device']['description']}, "hazc.local.") self.bindConnection() zeroconf = Zeroconf() zeroconf.register_service(info) try: while True: # try: print("Ready") self.conn, self.addr = self.webcontrol.accept() self.listen() self.conn.close() except KeyboardInterrupt: pass finally: print() print("Unregistering...") zeroconf.unregister_service(info) zeroconf.close() try: print("Shutting down socket") self.webcontrol.shutdown(socket.SHUT_RDWR) except Exception as e: print(e) def listen(self): data = bytes() rbytes = 0 while rbytes < self.MSGLEN: d = self.conn.recv(self.buffer) if not d: break data += d rbytes += len(d) # print data.decode('utf-8') self.handledata(data) def handledata(self, data): command, param = self.cleanandstringdata(data) print('->' + command + ';' + param) # replystr = "ERROR" try: replystr = self.commands[command].execute(param) except KeyError: if(command==''): command = "(empty string)" print("ERROR! Unknown command: " + command) replystr = "" # replystr = self.commands['version'].execute('') if(replystr == None): print("WARNING! " + command + " should return a string to send to the master. Sending 'NO_REPLY'") replystr = 'NO_REPLY' print(replystr) self.reply(replystr) def reply(self, msg): longmsg = msg while len(longmsg) < self.MSGLEN: longmsg += self.END_OF_MSG # print(longmsg) self.conn.send(longmsg.encode('utf-8')) def cleanandstringdata(self, data): dstr = data.decode('utf-8') full = dstr.strip(self.END_OF_MSG) if '?' in full: li = full.split('?') param = li[-1] cmd = li[0] elif '!' in full: li = full.split('!') param = li[-1] cmd = li[0] else: param = '' cmd = full return (cmd, param) def bindConnection(self): try: self.webcontrol = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.webcontrol.bind((self.ip, self.port)) self.webcontrol.listen(1) except OSError as e: print(e) quit() def exec_status(self): return "Running" def version_cmd(self): return self.version def paramtype_tostring(self, paramnum): if paramnum == self.BOOL: return 'BOOL' elif paramnum == self.FLOAT: return 'FLOAT' elif paramnum == self.STRING: return 'STRING' elif paramnum == self.INT: return 'INT' else: return 'PARAM_ERROR' def commands_cmd(self): rstr = "" for key in self.commands: rstr += key if self.commands[key].paramtype is not self.NO_PARAM: # pdb.set_trace() rstr += ':' + self.paramtype_tostring(self.commands[key].paramtype) rstr += ";" return rstr def status_cmd(self, specific_status=''): str = '' if len(specific_status) > 0: <|fim_middle|> else: for st in self.status: str += st + ',' + self.status[st]() + ';' return str[:self.MSGLEN-1] # Some debugging methods def debug_cmds(self): print("Commands: " + str(self.commands)) print("Statuses: " + str(self.status))<|fim▁end|>
str = self.status[specific_status]
<|file_name|>hazc_device.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 from zeroconf import Zeroconf, ServiceInfo import socket import configparser from . import hazc_cmd # import pdb class hazc_device: #Forward constants NO_PARAM = hazc_cmd.NO_PARAM BOOL = hazc_cmd.BOOL FLOAT = hazc_cmd.FLOAT STRING = hazc_cmd.STRING INT = hazc_cmd.INT global running running = False def __init__(self, ipaddr): self.version = "0.1" self.config = configparser.ConfigParser() self.config.read('config.ini') self.MSGLEN = 1024 self.END_OF_MSG = '*' self.ip = ipaddr self.buffer = 20 # self.commands = {'version?':self.version_cmd,'commands?':self.commands_cmd,'status?':self.status_cmd} hcvc = hazc_cmd.hazc_cmd('version?', self.version_cmd, self.NO_PARAM) hccc = hazc_cmd.hazc_cmd('commands?', self.commands_cmd, self.NO_PARAM) hcsc = hazc_cmd.hazc_cmd('status?', self.status_cmd, self.STRING) self.commands = {'version': hcvc, 'commands': hccc, 'status': hcsc} # probably want to add a debug log status self.status = {'exec_status': self.exec_status} #Adds a function - not as preferred as addControl #Does NOT auto add status def addFunction(self, name, handler, paramtype): # pdb.settrace() #log("This is not the preferred way to add controls, see addControl") if not('?' in name or '!' in name): # log("Function name requires a '?' or '!', assuming '!'") name += '!' self.commands[name] = hazc_cmd.hazc_cmd(name, handler, paramtype) #Adds a control vector #controlname should just be a name like 'temp' or 'position' - it'll be the same for the status def addControl(self, controlname, handler, statushandler, paramtype=NO_PARAM): cmd_name = 'set-'+controlname self.commands[cmd_name] = hazc_cmd.hazc_cmd(cmd_name+'?', handler, paramtype) self.addStatus(controlname, statushandler) #adds a unique status not already included in control vector. name is just the name, as in 'temp' def addStatus(self, name, handler): self.status[name] = handler def advertise(self): postfix = self.config['global']['service_prefix'] self.port = int(self.config['global']['port']) #print(self.config['device']['hostname']+postfix) info = ServiceInfo(postfix, self.config['device']['hostname']+"."+postfix, socket.inet_aton(self.ip), self.port, 0, 0, {'info': self.config['device']['description']}, "hazc.local.") self.bindConnection() zeroconf = Zeroconf() zeroconf.register_service(info) try: while True: # try: print("Ready") self.conn, self.addr = self.webcontrol.accept() self.listen() self.conn.close() except KeyboardInterrupt: pass finally: print() print("Unregistering...") zeroconf.unregister_service(info) zeroconf.close() try: print("Shutting down socket") self.webcontrol.shutdown(socket.SHUT_RDWR) except Exception as e: print(e) def listen(self): data = bytes() rbytes = 0 while rbytes < self.MSGLEN: d = self.conn.recv(self.buffer) if not d: break data += d rbytes += len(d) # print data.decode('utf-8') self.handledata(data) def handledata(self, data): command, param = self.cleanandstringdata(data) print('->' + command + ';' + param) # replystr = "ERROR" try: replystr = self.commands[command].execute(param) except KeyError: if(command==''): command = "(empty string)" print("ERROR! Unknown command: " + command) replystr = "" # replystr = self.commands['version'].execute('') if(replystr == None): print("WARNING! " + command + " should return a string to send to the master. Sending 'NO_REPLY'") replystr = 'NO_REPLY' print(replystr) self.reply(replystr) def reply(self, msg): longmsg = msg while len(longmsg) < self.MSGLEN: longmsg += self.END_OF_MSG # print(longmsg) self.conn.send(longmsg.encode('utf-8')) def cleanandstringdata(self, data): dstr = data.decode('utf-8') full = dstr.strip(self.END_OF_MSG) if '?' in full: li = full.split('?') param = li[-1] cmd = li[0] elif '!' in full: li = full.split('!') param = li[-1] cmd = li[0] else: param = '' cmd = full return (cmd, param) def bindConnection(self): try: self.webcontrol = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.webcontrol.bind((self.ip, self.port)) self.webcontrol.listen(1) except OSError as e: print(e) quit() def exec_status(self): return "Running" def version_cmd(self): return self.version def paramtype_tostring(self, paramnum): if paramnum == self.BOOL: return 'BOOL' elif paramnum == self.FLOAT: return 'FLOAT' elif paramnum == self.STRING: return 'STRING' elif paramnum == self.INT: return 'INT' else: return 'PARAM_ERROR' def commands_cmd(self): rstr = "" for key in self.commands: rstr += key if self.commands[key].paramtype is not self.NO_PARAM: # pdb.set_trace() rstr += ':' + self.paramtype_tostring(self.commands[key].paramtype) rstr += ";" return rstr def status_cmd(self, specific_status=''): str = '' if len(specific_status) > 0: str = self.status[specific_status] else: <|fim_middle|> return str[:self.MSGLEN-1] # Some debugging methods def debug_cmds(self): print("Commands: " + str(self.commands)) print("Statuses: " + str(self.status))<|fim▁end|>
for st in self.status: str += st + ',' + self.status[st]() + ';'
<|file_name|>hazc_device.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 from zeroconf import Zeroconf, ServiceInfo import socket import configparser from . import hazc_cmd # import pdb class hazc_device: #Forward constants NO_PARAM = hazc_cmd.NO_PARAM BOOL = hazc_cmd.BOOL FLOAT = hazc_cmd.FLOAT STRING = hazc_cmd.STRING INT = hazc_cmd.INT global running running = False def <|fim_middle|>(self, ipaddr): self.version = "0.1" self.config = configparser.ConfigParser() self.config.read('config.ini') self.MSGLEN = 1024 self.END_OF_MSG = '*' self.ip = ipaddr self.buffer = 20 # self.commands = {'version?':self.version_cmd,'commands?':self.commands_cmd,'status?':self.status_cmd} hcvc = hazc_cmd.hazc_cmd('version?', self.version_cmd, self.NO_PARAM) hccc = hazc_cmd.hazc_cmd('commands?', self.commands_cmd, self.NO_PARAM) hcsc = hazc_cmd.hazc_cmd('status?', self.status_cmd, self.STRING) self.commands = {'version': hcvc, 'commands': hccc, 'status': hcsc} # probably want to add a debug log status self.status = {'exec_status': self.exec_status} #Adds a function - not as preferred as addControl #Does NOT auto add status def addFunction(self, name, handler, paramtype): # pdb.settrace() #log("This is not the preferred way to add controls, see addControl") if not('?' in name or '!' in name): # log("Function name requires a '?' or '!', assuming '!'") name += '!' self.commands[name] = hazc_cmd.hazc_cmd(name, handler, paramtype) #Adds a control vector #controlname should just be a name like 'temp' or 'position' - it'll be the same for the status def addControl(self, controlname, handler, statushandler, paramtype=NO_PARAM): cmd_name = 'set-'+controlname self.commands[cmd_name] = hazc_cmd.hazc_cmd(cmd_name+'?', handler, paramtype) self.addStatus(controlname, statushandler) #adds a unique status not already included in control vector. name is just the name, as in 'temp' def addStatus(self, name, handler): self.status[name] = handler def advertise(self): postfix = self.config['global']['service_prefix'] self.port = int(self.config['global']['port']) #print(self.config['device']['hostname']+postfix) info = ServiceInfo(postfix, self.config['device']['hostname']+"."+postfix, socket.inet_aton(self.ip), self.port, 0, 0, {'info': self.config['device']['description']}, "hazc.local.") self.bindConnection() zeroconf = Zeroconf() zeroconf.register_service(info) try: while True: # try: print("Ready") self.conn, self.addr = self.webcontrol.accept() self.listen() self.conn.close() except KeyboardInterrupt: pass finally: print() print("Unregistering...") zeroconf.unregister_service(info) zeroconf.close() try: print("Shutting down socket") self.webcontrol.shutdown(socket.SHUT_RDWR) except Exception as e: print(e) def listen(self): data = bytes() rbytes = 0 while rbytes < self.MSGLEN: d = self.conn.recv(self.buffer) if not d: break data += d rbytes += len(d) # print data.decode('utf-8') self.handledata(data) def handledata(self, data): command, param = self.cleanandstringdata(data) print('->' + command + ';' + param) # replystr = "ERROR" try: replystr = self.commands[command].execute(param) except KeyError: if(command==''): command = "(empty string)" print("ERROR! Unknown command: " + command) replystr = "" # replystr = self.commands['version'].execute('') if(replystr == None): print("WARNING! " + command + " should return a string to send to the master. Sending 'NO_REPLY'") replystr = 'NO_REPLY' print(replystr) self.reply(replystr) def reply(self, msg): longmsg = msg while len(longmsg) < self.MSGLEN: longmsg += self.END_OF_MSG # print(longmsg) self.conn.send(longmsg.encode('utf-8')) def cleanandstringdata(self, data): dstr = data.decode('utf-8') full = dstr.strip(self.END_OF_MSG) if '?' in full: li = full.split('?') param = li[-1] cmd = li[0] elif '!' in full: li = full.split('!') param = li[-1] cmd = li[0] else: param = '' cmd = full return (cmd, param) def bindConnection(self): try: self.webcontrol = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.webcontrol.bind((self.ip, self.port)) self.webcontrol.listen(1) except OSError as e: print(e) quit() def exec_status(self): return "Running" def version_cmd(self): return self.version def paramtype_tostring(self, paramnum): if paramnum == self.BOOL: return 'BOOL' elif paramnum == self.FLOAT: return 'FLOAT' elif paramnum == self.STRING: return 'STRING' elif paramnum == self.INT: return 'INT' else: return 'PARAM_ERROR' def commands_cmd(self): rstr = "" for key in self.commands: rstr += key if self.commands[key].paramtype is not self.NO_PARAM: # pdb.set_trace() rstr += ':' + self.paramtype_tostring(self.commands[key].paramtype) rstr += ";" return rstr def status_cmd(self, specific_status=''): str = '' if len(specific_status) > 0: str = self.status[specific_status] else: for st in self.status: str += st + ',' + self.status[st]() + ';' return str[:self.MSGLEN-1] # Some debugging methods def debug_cmds(self): print("Commands: " + str(self.commands)) print("Statuses: " + str(self.status))<|fim▁end|>
__init__
<|file_name|>hazc_device.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 from zeroconf import Zeroconf, ServiceInfo import socket import configparser from . import hazc_cmd # import pdb class hazc_device: #Forward constants NO_PARAM = hazc_cmd.NO_PARAM BOOL = hazc_cmd.BOOL FLOAT = hazc_cmd.FLOAT STRING = hazc_cmd.STRING INT = hazc_cmd.INT global running running = False def __init__(self, ipaddr): self.version = "0.1" self.config = configparser.ConfigParser() self.config.read('config.ini') self.MSGLEN = 1024 self.END_OF_MSG = '*' self.ip = ipaddr self.buffer = 20 # self.commands = {'version?':self.version_cmd,'commands?':self.commands_cmd,'status?':self.status_cmd} hcvc = hazc_cmd.hazc_cmd('version?', self.version_cmd, self.NO_PARAM) hccc = hazc_cmd.hazc_cmd('commands?', self.commands_cmd, self.NO_PARAM) hcsc = hazc_cmd.hazc_cmd('status?', self.status_cmd, self.STRING) self.commands = {'version': hcvc, 'commands': hccc, 'status': hcsc} # probably want to add a debug log status self.status = {'exec_status': self.exec_status} #Adds a function - not as preferred as addControl #Does NOT auto add status def <|fim_middle|>(self, name, handler, paramtype): # pdb.settrace() #log("This is not the preferred way to add controls, see addControl") if not('?' in name or '!' in name): # log("Function name requires a '?' or '!', assuming '!'") name += '!' self.commands[name] = hazc_cmd.hazc_cmd(name, handler, paramtype) #Adds a control vector #controlname should just be a name like 'temp' or 'position' - it'll be the same for the status def addControl(self, controlname, handler, statushandler, paramtype=NO_PARAM): cmd_name = 'set-'+controlname self.commands[cmd_name] = hazc_cmd.hazc_cmd(cmd_name+'?', handler, paramtype) self.addStatus(controlname, statushandler) #adds a unique status not already included in control vector. name is just the name, as in 'temp' def addStatus(self, name, handler): self.status[name] = handler def advertise(self): postfix = self.config['global']['service_prefix'] self.port = int(self.config['global']['port']) #print(self.config['device']['hostname']+postfix) info = ServiceInfo(postfix, self.config['device']['hostname']+"."+postfix, socket.inet_aton(self.ip), self.port, 0, 0, {'info': self.config['device']['description']}, "hazc.local.") self.bindConnection() zeroconf = Zeroconf() zeroconf.register_service(info) try: while True: # try: print("Ready") self.conn, self.addr = self.webcontrol.accept() self.listen() self.conn.close() except KeyboardInterrupt: pass finally: print() print("Unregistering...") zeroconf.unregister_service(info) zeroconf.close() try: print("Shutting down socket") self.webcontrol.shutdown(socket.SHUT_RDWR) except Exception as e: print(e) def listen(self): data = bytes() rbytes = 0 while rbytes < self.MSGLEN: d = self.conn.recv(self.buffer) if not d: break data += d rbytes += len(d) # print data.decode('utf-8') self.handledata(data) def handledata(self, data): command, param = self.cleanandstringdata(data) print('->' + command + ';' + param) # replystr = "ERROR" try: replystr = self.commands[command].execute(param) except KeyError: if(command==''): command = "(empty string)" print("ERROR! Unknown command: " + command) replystr = "" # replystr = self.commands['version'].execute('') if(replystr == None): print("WARNING! " + command + " should return a string to send to the master. Sending 'NO_REPLY'") replystr = 'NO_REPLY' print(replystr) self.reply(replystr) def reply(self, msg): longmsg = msg while len(longmsg) < self.MSGLEN: longmsg += self.END_OF_MSG # print(longmsg) self.conn.send(longmsg.encode('utf-8')) def cleanandstringdata(self, data): dstr = data.decode('utf-8') full = dstr.strip(self.END_OF_MSG) if '?' in full: li = full.split('?') param = li[-1] cmd = li[0] elif '!' in full: li = full.split('!') param = li[-1] cmd = li[0] else: param = '' cmd = full return (cmd, param) def bindConnection(self): try: self.webcontrol = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.webcontrol.bind((self.ip, self.port)) self.webcontrol.listen(1) except OSError as e: print(e) quit() def exec_status(self): return "Running" def version_cmd(self): return self.version def paramtype_tostring(self, paramnum): if paramnum == self.BOOL: return 'BOOL' elif paramnum == self.FLOAT: return 'FLOAT' elif paramnum == self.STRING: return 'STRING' elif paramnum == self.INT: return 'INT' else: return 'PARAM_ERROR' def commands_cmd(self): rstr = "" for key in self.commands: rstr += key if self.commands[key].paramtype is not self.NO_PARAM: # pdb.set_trace() rstr += ':' + self.paramtype_tostring(self.commands[key].paramtype) rstr += ";" return rstr def status_cmd(self, specific_status=''): str = '' if len(specific_status) > 0: str = self.status[specific_status] else: for st in self.status: str += st + ',' + self.status[st]() + ';' return str[:self.MSGLEN-1] # Some debugging methods def debug_cmds(self): print("Commands: " + str(self.commands)) print("Statuses: " + str(self.status))<|fim▁end|>
addFunction
<|file_name|>hazc_device.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 from zeroconf import Zeroconf, ServiceInfo import socket import configparser from . import hazc_cmd # import pdb class hazc_device: #Forward constants NO_PARAM = hazc_cmd.NO_PARAM BOOL = hazc_cmd.BOOL FLOAT = hazc_cmd.FLOAT STRING = hazc_cmd.STRING INT = hazc_cmd.INT global running running = False def __init__(self, ipaddr): self.version = "0.1" self.config = configparser.ConfigParser() self.config.read('config.ini') self.MSGLEN = 1024 self.END_OF_MSG = '*' self.ip = ipaddr self.buffer = 20 # self.commands = {'version?':self.version_cmd,'commands?':self.commands_cmd,'status?':self.status_cmd} hcvc = hazc_cmd.hazc_cmd('version?', self.version_cmd, self.NO_PARAM) hccc = hazc_cmd.hazc_cmd('commands?', self.commands_cmd, self.NO_PARAM) hcsc = hazc_cmd.hazc_cmd('status?', self.status_cmd, self.STRING) self.commands = {'version': hcvc, 'commands': hccc, 'status': hcsc} # probably want to add a debug log status self.status = {'exec_status': self.exec_status} #Adds a function - not as preferred as addControl #Does NOT auto add status def addFunction(self, name, handler, paramtype): # pdb.settrace() #log("This is not the preferred way to add controls, see addControl") if not('?' in name or '!' in name): # log("Function name requires a '?' or '!', assuming '!'") name += '!' self.commands[name] = hazc_cmd.hazc_cmd(name, handler, paramtype) #Adds a control vector #controlname should just be a name like 'temp' or 'position' - it'll be the same for the status def <|fim_middle|>(self, controlname, handler, statushandler, paramtype=NO_PARAM): cmd_name = 'set-'+controlname self.commands[cmd_name] = hazc_cmd.hazc_cmd(cmd_name+'?', handler, paramtype) self.addStatus(controlname, statushandler) #adds a unique status not already included in control vector. name is just the name, as in 'temp' def addStatus(self, name, handler): self.status[name] = handler def advertise(self): postfix = self.config['global']['service_prefix'] self.port = int(self.config['global']['port']) #print(self.config['device']['hostname']+postfix) info = ServiceInfo(postfix, self.config['device']['hostname']+"."+postfix, socket.inet_aton(self.ip), self.port, 0, 0, {'info': self.config['device']['description']}, "hazc.local.") self.bindConnection() zeroconf = Zeroconf() zeroconf.register_service(info) try: while True: # try: print("Ready") self.conn, self.addr = self.webcontrol.accept() self.listen() self.conn.close() except KeyboardInterrupt: pass finally: print() print("Unregistering...") zeroconf.unregister_service(info) zeroconf.close() try: print("Shutting down socket") self.webcontrol.shutdown(socket.SHUT_RDWR) except Exception as e: print(e) def listen(self): data = bytes() rbytes = 0 while rbytes < self.MSGLEN: d = self.conn.recv(self.buffer) if not d: break data += d rbytes += len(d) # print data.decode('utf-8') self.handledata(data) def handledata(self, data): command, param = self.cleanandstringdata(data) print('->' + command + ';' + param) # replystr = "ERROR" try: replystr = self.commands[command].execute(param) except KeyError: if(command==''): command = "(empty string)" print("ERROR! Unknown command: " + command) replystr = "" # replystr = self.commands['version'].execute('') if(replystr == None): print("WARNING! " + command + " should return a string to send to the master. Sending 'NO_REPLY'") replystr = 'NO_REPLY' print(replystr) self.reply(replystr) def reply(self, msg): longmsg = msg while len(longmsg) < self.MSGLEN: longmsg += self.END_OF_MSG # print(longmsg) self.conn.send(longmsg.encode('utf-8')) def cleanandstringdata(self, data): dstr = data.decode('utf-8') full = dstr.strip(self.END_OF_MSG) if '?' in full: li = full.split('?') param = li[-1] cmd = li[0] elif '!' in full: li = full.split('!') param = li[-1] cmd = li[0] else: param = '' cmd = full return (cmd, param) def bindConnection(self): try: self.webcontrol = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.webcontrol.bind((self.ip, self.port)) self.webcontrol.listen(1) except OSError as e: print(e) quit() def exec_status(self): return "Running" def version_cmd(self): return self.version def paramtype_tostring(self, paramnum): if paramnum == self.BOOL: return 'BOOL' elif paramnum == self.FLOAT: return 'FLOAT' elif paramnum == self.STRING: return 'STRING' elif paramnum == self.INT: return 'INT' else: return 'PARAM_ERROR' def commands_cmd(self): rstr = "" for key in self.commands: rstr += key if self.commands[key].paramtype is not self.NO_PARAM: # pdb.set_trace() rstr += ':' + self.paramtype_tostring(self.commands[key].paramtype) rstr += ";" return rstr def status_cmd(self, specific_status=''): str = '' if len(specific_status) > 0: str = self.status[specific_status] else: for st in self.status: str += st + ',' + self.status[st]() + ';' return str[:self.MSGLEN-1] # Some debugging methods def debug_cmds(self): print("Commands: " + str(self.commands)) print("Statuses: " + str(self.status))<|fim▁end|>
addControl
<|file_name|>hazc_device.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 from zeroconf import Zeroconf, ServiceInfo import socket import configparser from . import hazc_cmd # import pdb class hazc_device: #Forward constants NO_PARAM = hazc_cmd.NO_PARAM BOOL = hazc_cmd.BOOL FLOAT = hazc_cmd.FLOAT STRING = hazc_cmd.STRING INT = hazc_cmd.INT global running running = False def __init__(self, ipaddr): self.version = "0.1" self.config = configparser.ConfigParser() self.config.read('config.ini') self.MSGLEN = 1024 self.END_OF_MSG = '*' self.ip = ipaddr self.buffer = 20 # self.commands = {'version?':self.version_cmd,'commands?':self.commands_cmd,'status?':self.status_cmd} hcvc = hazc_cmd.hazc_cmd('version?', self.version_cmd, self.NO_PARAM) hccc = hazc_cmd.hazc_cmd('commands?', self.commands_cmd, self.NO_PARAM) hcsc = hazc_cmd.hazc_cmd('status?', self.status_cmd, self.STRING) self.commands = {'version': hcvc, 'commands': hccc, 'status': hcsc} # probably want to add a debug log status self.status = {'exec_status': self.exec_status} #Adds a function - not as preferred as addControl #Does NOT auto add status def addFunction(self, name, handler, paramtype): # pdb.settrace() #log("This is not the preferred way to add controls, see addControl") if not('?' in name or '!' in name): # log("Function name requires a '?' or '!', assuming '!'") name += '!' self.commands[name] = hazc_cmd.hazc_cmd(name, handler, paramtype) #Adds a control vector #controlname should just be a name like 'temp' or 'position' - it'll be the same for the status def addControl(self, controlname, handler, statushandler, paramtype=NO_PARAM): cmd_name = 'set-'+controlname self.commands[cmd_name] = hazc_cmd.hazc_cmd(cmd_name+'?', handler, paramtype) self.addStatus(controlname, statushandler) #adds a unique status not already included in control vector. name is just the name, as in 'temp' def <|fim_middle|>(self, name, handler): self.status[name] = handler def advertise(self): postfix = self.config['global']['service_prefix'] self.port = int(self.config['global']['port']) #print(self.config['device']['hostname']+postfix) info = ServiceInfo(postfix, self.config['device']['hostname']+"."+postfix, socket.inet_aton(self.ip), self.port, 0, 0, {'info': self.config['device']['description']}, "hazc.local.") self.bindConnection() zeroconf = Zeroconf() zeroconf.register_service(info) try: while True: # try: print("Ready") self.conn, self.addr = self.webcontrol.accept() self.listen() self.conn.close() except KeyboardInterrupt: pass finally: print() print("Unregistering...") zeroconf.unregister_service(info) zeroconf.close() try: print("Shutting down socket") self.webcontrol.shutdown(socket.SHUT_RDWR) except Exception as e: print(e) def listen(self): data = bytes() rbytes = 0 while rbytes < self.MSGLEN: d = self.conn.recv(self.buffer) if not d: break data += d rbytes += len(d) # print data.decode('utf-8') self.handledata(data) def handledata(self, data): command, param = self.cleanandstringdata(data) print('->' + command + ';' + param) # replystr = "ERROR" try: replystr = self.commands[command].execute(param) except KeyError: if(command==''): command = "(empty string)" print("ERROR! Unknown command: " + command) replystr = "" # replystr = self.commands['version'].execute('') if(replystr == None): print("WARNING! " + command + " should return a string to send to the master. Sending 'NO_REPLY'") replystr = 'NO_REPLY' print(replystr) self.reply(replystr) def reply(self, msg): longmsg = msg while len(longmsg) < self.MSGLEN: longmsg += self.END_OF_MSG # print(longmsg) self.conn.send(longmsg.encode('utf-8')) def cleanandstringdata(self, data): dstr = data.decode('utf-8') full = dstr.strip(self.END_OF_MSG) if '?' in full: li = full.split('?') param = li[-1] cmd = li[0] elif '!' in full: li = full.split('!') param = li[-1] cmd = li[0] else: param = '' cmd = full return (cmd, param) def bindConnection(self): try: self.webcontrol = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.webcontrol.bind((self.ip, self.port)) self.webcontrol.listen(1) except OSError as e: print(e) quit() def exec_status(self): return "Running" def version_cmd(self): return self.version def paramtype_tostring(self, paramnum): if paramnum == self.BOOL: return 'BOOL' elif paramnum == self.FLOAT: return 'FLOAT' elif paramnum == self.STRING: return 'STRING' elif paramnum == self.INT: return 'INT' else: return 'PARAM_ERROR' def commands_cmd(self): rstr = "" for key in self.commands: rstr += key if self.commands[key].paramtype is not self.NO_PARAM: # pdb.set_trace() rstr += ':' + self.paramtype_tostring(self.commands[key].paramtype) rstr += ";" return rstr def status_cmd(self, specific_status=''): str = '' if len(specific_status) > 0: str = self.status[specific_status] else: for st in self.status: str += st + ',' + self.status[st]() + ';' return str[:self.MSGLEN-1] # Some debugging methods def debug_cmds(self): print("Commands: " + str(self.commands)) print("Statuses: " + str(self.status))<|fim▁end|>
addStatus
<|file_name|>hazc_device.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 from zeroconf import Zeroconf, ServiceInfo import socket import configparser from . import hazc_cmd # import pdb class hazc_device: #Forward constants NO_PARAM = hazc_cmd.NO_PARAM BOOL = hazc_cmd.BOOL FLOAT = hazc_cmd.FLOAT STRING = hazc_cmd.STRING INT = hazc_cmd.INT global running running = False def __init__(self, ipaddr): self.version = "0.1" self.config = configparser.ConfigParser() self.config.read('config.ini') self.MSGLEN = 1024 self.END_OF_MSG = '*' self.ip = ipaddr self.buffer = 20 # self.commands = {'version?':self.version_cmd,'commands?':self.commands_cmd,'status?':self.status_cmd} hcvc = hazc_cmd.hazc_cmd('version?', self.version_cmd, self.NO_PARAM) hccc = hazc_cmd.hazc_cmd('commands?', self.commands_cmd, self.NO_PARAM) hcsc = hazc_cmd.hazc_cmd('status?', self.status_cmd, self.STRING) self.commands = {'version': hcvc, 'commands': hccc, 'status': hcsc} # probably want to add a debug log status self.status = {'exec_status': self.exec_status} #Adds a function - not as preferred as addControl #Does NOT auto add status def addFunction(self, name, handler, paramtype): # pdb.settrace() #log("This is not the preferred way to add controls, see addControl") if not('?' in name or '!' in name): # log("Function name requires a '?' or '!', assuming '!'") name += '!' self.commands[name] = hazc_cmd.hazc_cmd(name, handler, paramtype) #Adds a control vector #controlname should just be a name like 'temp' or 'position' - it'll be the same for the status def addControl(self, controlname, handler, statushandler, paramtype=NO_PARAM): cmd_name = 'set-'+controlname self.commands[cmd_name] = hazc_cmd.hazc_cmd(cmd_name+'?', handler, paramtype) self.addStatus(controlname, statushandler) #adds a unique status not already included in control vector. name is just the name, as in 'temp' def addStatus(self, name, handler): self.status[name] = handler def <|fim_middle|>(self): postfix = self.config['global']['service_prefix'] self.port = int(self.config['global']['port']) #print(self.config['device']['hostname']+postfix) info = ServiceInfo(postfix, self.config['device']['hostname']+"."+postfix, socket.inet_aton(self.ip), self.port, 0, 0, {'info': self.config['device']['description']}, "hazc.local.") self.bindConnection() zeroconf = Zeroconf() zeroconf.register_service(info) try: while True: # try: print("Ready") self.conn, self.addr = self.webcontrol.accept() self.listen() self.conn.close() except KeyboardInterrupt: pass finally: print() print("Unregistering...") zeroconf.unregister_service(info) zeroconf.close() try: print("Shutting down socket") self.webcontrol.shutdown(socket.SHUT_RDWR) except Exception as e: print(e) def listen(self): data = bytes() rbytes = 0 while rbytes < self.MSGLEN: d = self.conn.recv(self.buffer) if not d: break data += d rbytes += len(d) # print data.decode('utf-8') self.handledata(data) def handledata(self, data): command, param = self.cleanandstringdata(data) print('->' + command + ';' + param) # replystr = "ERROR" try: replystr = self.commands[command].execute(param) except KeyError: if(command==''): command = "(empty string)" print("ERROR! Unknown command: " + command) replystr = "" # replystr = self.commands['version'].execute('') if(replystr == None): print("WARNING! " + command + " should return a string to send to the master. Sending 'NO_REPLY'") replystr = 'NO_REPLY' print(replystr) self.reply(replystr) def reply(self, msg): longmsg = msg while len(longmsg) < self.MSGLEN: longmsg += self.END_OF_MSG # print(longmsg) self.conn.send(longmsg.encode('utf-8')) def cleanandstringdata(self, data): dstr = data.decode('utf-8') full = dstr.strip(self.END_OF_MSG) if '?' in full: li = full.split('?') param = li[-1] cmd = li[0] elif '!' in full: li = full.split('!') param = li[-1] cmd = li[0] else: param = '' cmd = full return (cmd, param) def bindConnection(self): try: self.webcontrol = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.webcontrol.bind((self.ip, self.port)) self.webcontrol.listen(1) except OSError as e: print(e) quit() def exec_status(self): return "Running" def version_cmd(self): return self.version def paramtype_tostring(self, paramnum): if paramnum == self.BOOL: return 'BOOL' elif paramnum == self.FLOAT: return 'FLOAT' elif paramnum == self.STRING: return 'STRING' elif paramnum == self.INT: return 'INT' else: return 'PARAM_ERROR' def commands_cmd(self): rstr = "" for key in self.commands: rstr += key if self.commands[key].paramtype is not self.NO_PARAM: # pdb.set_trace() rstr += ':' + self.paramtype_tostring(self.commands[key].paramtype) rstr += ";" return rstr def status_cmd(self, specific_status=''): str = '' if len(specific_status) > 0: str = self.status[specific_status] else: for st in self.status: str += st + ',' + self.status[st]() + ';' return str[:self.MSGLEN-1] # Some debugging methods def debug_cmds(self): print("Commands: " + str(self.commands)) print("Statuses: " + str(self.status))<|fim▁end|>
advertise
<|file_name|>hazc_device.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 from zeroconf import Zeroconf, ServiceInfo import socket import configparser from . import hazc_cmd # import pdb class hazc_device: #Forward constants NO_PARAM = hazc_cmd.NO_PARAM BOOL = hazc_cmd.BOOL FLOAT = hazc_cmd.FLOAT STRING = hazc_cmd.STRING INT = hazc_cmd.INT global running running = False def __init__(self, ipaddr): self.version = "0.1" self.config = configparser.ConfigParser() self.config.read('config.ini') self.MSGLEN = 1024 self.END_OF_MSG = '*' self.ip = ipaddr self.buffer = 20 # self.commands = {'version?':self.version_cmd,'commands?':self.commands_cmd,'status?':self.status_cmd} hcvc = hazc_cmd.hazc_cmd('version?', self.version_cmd, self.NO_PARAM) hccc = hazc_cmd.hazc_cmd('commands?', self.commands_cmd, self.NO_PARAM) hcsc = hazc_cmd.hazc_cmd('status?', self.status_cmd, self.STRING) self.commands = {'version': hcvc, 'commands': hccc, 'status': hcsc} # probably want to add a debug log status self.status = {'exec_status': self.exec_status} #Adds a function - not as preferred as addControl #Does NOT auto add status def addFunction(self, name, handler, paramtype): # pdb.settrace() #log("This is not the preferred way to add controls, see addControl") if not('?' in name or '!' in name): # log("Function name requires a '?' or '!', assuming '!'") name += '!' self.commands[name] = hazc_cmd.hazc_cmd(name, handler, paramtype) #Adds a control vector #controlname should just be a name like 'temp' or 'position' - it'll be the same for the status def addControl(self, controlname, handler, statushandler, paramtype=NO_PARAM): cmd_name = 'set-'+controlname self.commands[cmd_name] = hazc_cmd.hazc_cmd(cmd_name+'?', handler, paramtype) self.addStatus(controlname, statushandler) #adds a unique status not already included in control vector. name is just the name, as in 'temp' def addStatus(self, name, handler): self.status[name] = handler def advertise(self): postfix = self.config['global']['service_prefix'] self.port = int(self.config['global']['port']) #print(self.config['device']['hostname']+postfix) info = ServiceInfo(postfix, self.config['device']['hostname']+"."+postfix, socket.inet_aton(self.ip), self.port, 0, 0, {'info': self.config['device']['description']}, "hazc.local.") self.bindConnection() zeroconf = Zeroconf() zeroconf.register_service(info) try: while True: # try: print("Ready") self.conn, self.addr = self.webcontrol.accept() self.listen() self.conn.close() except KeyboardInterrupt: pass finally: print() print("Unregistering...") zeroconf.unregister_service(info) zeroconf.close() try: print("Shutting down socket") self.webcontrol.shutdown(socket.SHUT_RDWR) except Exception as e: print(e) def <|fim_middle|>(self): data = bytes() rbytes = 0 while rbytes < self.MSGLEN: d = self.conn.recv(self.buffer) if not d: break data += d rbytes += len(d) # print data.decode('utf-8') self.handledata(data) def handledata(self, data): command, param = self.cleanandstringdata(data) print('->' + command + ';' + param) # replystr = "ERROR" try: replystr = self.commands[command].execute(param) except KeyError: if(command==''): command = "(empty string)" print("ERROR! Unknown command: " + command) replystr = "" # replystr = self.commands['version'].execute('') if(replystr == None): print("WARNING! " + command + " should return a string to send to the master. Sending 'NO_REPLY'") replystr = 'NO_REPLY' print(replystr) self.reply(replystr) def reply(self, msg): longmsg = msg while len(longmsg) < self.MSGLEN: longmsg += self.END_OF_MSG # print(longmsg) self.conn.send(longmsg.encode('utf-8')) def cleanandstringdata(self, data): dstr = data.decode('utf-8') full = dstr.strip(self.END_OF_MSG) if '?' in full: li = full.split('?') param = li[-1] cmd = li[0] elif '!' in full: li = full.split('!') param = li[-1] cmd = li[0] else: param = '' cmd = full return (cmd, param) def bindConnection(self): try: self.webcontrol = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.webcontrol.bind((self.ip, self.port)) self.webcontrol.listen(1) except OSError as e: print(e) quit() def exec_status(self): return "Running" def version_cmd(self): return self.version def paramtype_tostring(self, paramnum): if paramnum == self.BOOL: return 'BOOL' elif paramnum == self.FLOAT: return 'FLOAT' elif paramnum == self.STRING: return 'STRING' elif paramnum == self.INT: return 'INT' else: return 'PARAM_ERROR' def commands_cmd(self): rstr = "" for key in self.commands: rstr += key if self.commands[key].paramtype is not self.NO_PARAM: # pdb.set_trace() rstr += ':' + self.paramtype_tostring(self.commands[key].paramtype) rstr += ";" return rstr def status_cmd(self, specific_status=''): str = '' if len(specific_status) > 0: str = self.status[specific_status] else: for st in self.status: str += st + ',' + self.status[st]() + ';' return str[:self.MSGLEN-1] # Some debugging methods def debug_cmds(self): print("Commands: " + str(self.commands)) print("Statuses: " + str(self.status))<|fim▁end|>
listen
<|file_name|>hazc_device.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 from zeroconf import Zeroconf, ServiceInfo import socket import configparser from . import hazc_cmd # import pdb class hazc_device: #Forward constants NO_PARAM = hazc_cmd.NO_PARAM BOOL = hazc_cmd.BOOL FLOAT = hazc_cmd.FLOAT STRING = hazc_cmd.STRING INT = hazc_cmd.INT global running running = False def __init__(self, ipaddr): self.version = "0.1" self.config = configparser.ConfigParser() self.config.read('config.ini') self.MSGLEN = 1024 self.END_OF_MSG = '*' self.ip = ipaddr self.buffer = 20 # self.commands = {'version?':self.version_cmd,'commands?':self.commands_cmd,'status?':self.status_cmd} hcvc = hazc_cmd.hazc_cmd('version?', self.version_cmd, self.NO_PARAM) hccc = hazc_cmd.hazc_cmd('commands?', self.commands_cmd, self.NO_PARAM) hcsc = hazc_cmd.hazc_cmd('status?', self.status_cmd, self.STRING) self.commands = {'version': hcvc, 'commands': hccc, 'status': hcsc} # probably want to add a debug log status self.status = {'exec_status': self.exec_status} #Adds a function - not as preferred as addControl #Does NOT auto add status def addFunction(self, name, handler, paramtype): # pdb.settrace() #log("This is not the preferred way to add controls, see addControl") if not('?' in name or '!' in name): # log("Function name requires a '?' or '!', assuming '!'") name += '!' self.commands[name] = hazc_cmd.hazc_cmd(name, handler, paramtype) #Adds a control vector #controlname should just be a name like 'temp' or 'position' - it'll be the same for the status def addControl(self, controlname, handler, statushandler, paramtype=NO_PARAM): cmd_name = 'set-'+controlname self.commands[cmd_name] = hazc_cmd.hazc_cmd(cmd_name+'?', handler, paramtype) self.addStatus(controlname, statushandler) #adds a unique status not already included in control vector. name is just the name, as in 'temp' def addStatus(self, name, handler): self.status[name] = handler def advertise(self): postfix = self.config['global']['service_prefix'] self.port = int(self.config['global']['port']) #print(self.config['device']['hostname']+postfix) info = ServiceInfo(postfix, self.config['device']['hostname']+"."+postfix, socket.inet_aton(self.ip), self.port, 0, 0, {'info': self.config['device']['description']}, "hazc.local.") self.bindConnection() zeroconf = Zeroconf() zeroconf.register_service(info) try: while True: # try: print("Ready") self.conn, self.addr = self.webcontrol.accept() self.listen() self.conn.close() except KeyboardInterrupt: pass finally: print() print("Unregistering...") zeroconf.unregister_service(info) zeroconf.close() try: print("Shutting down socket") self.webcontrol.shutdown(socket.SHUT_RDWR) except Exception as e: print(e) def listen(self): data = bytes() rbytes = 0 while rbytes < self.MSGLEN: d = self.conn.recv(self.buffer) if not d: break data += d rbytes += len(d) # print data.decode('utf-8') self.handledata(data) def <|fim_middle|>(self, data): command, param = self.cleanandstringdata(data) print('->' + command + ';' + param) # replystr = "ERROR" try: replystr = self.commands[command].execute(param) except KeyError: if(command==''): command = "(empty string)" print("ERROR! Unknown command: " + command) replystr = "" # replystr = self.commands['version'].execute('') if(replystr == None): print("WARNING! " + command + " should return a string to send to the master. Sending 'NO_REPLY'") replystr = 'NO_REPLY' print(replystr) self.reply(replystr) def reply(self, msg): longmsg = msg while len(longmsg) < self.MSGLEN: longmsg += self.END_OF_MSG # print(longmsg) self.conn.send(longmsg.encode('utf-8')) def cleanandstringdata(self, data): dstr = data.decode('utf-8') full = dstr.strip(self.END_OF_MSG) if '?' in full: li = full.split('?') param = li[-1] cmd = li[0] elif '!' in full: li = full.split('!') param = li[-1] cmd = li[0] else: param = '' cmd = full return (cmd, param) def bindConnection(self): try: self.webcontrol = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.webcontrol.bind((self.ip, self.port)) self.webcontrol.listen(1) except OSError as e: print(e) quit() def exec_status(self): return "Running" def version_cmd(self): return self.version def paramtype_tostring(self, paramnum): if paramnum == self.BOOL: return 'BOOL' elif paramnum == self.FLOAT: return 'FLOAT' elif paramnum == self.STRING: return 'STRING' elif paramnum == self.INT: return 'INT' else: return 'PARAM_ERROR' def commands_cmd(self): rstr = "" for key in self.commands: rstr += key if self.commands[key].paramtype is not self.NO_PARAM: # pdb.set_trace() rstr += ':' + self.paramtype_tostring(self.commands[key].paramtype) rstr += ";" return rstr def status_cmd(self, specific_status=''): str = '' if len(specific_status) > 0: str = self.status[specific_status] else: for st in self.status: str += st + ',' + self.status[st]() + ';' return str[:self.MSGLEN-1] # Some debugging methods def debug_cmds(self): print("Commands: " + str(self.commands)) print("Statuses: " + str(self.status))<|fim▁end|>
handledata
<|file_name|>hazc_device.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 from zeroconf import Zeroconf, ServiceInfo import socket import configparser from . import hazc_cmd # import pdb class hazc_device: #Forward constants NO_PARAM = hazc_cmd.NO_PARAM BOOL = hazc_cmd.BOOL FLOAT = hazc_cmd.FLOAT STRING = hazc_cmd.STRING INT = hazc_cmd.INT global running running = False def __init__(self, ipaddr): self.version = "0.1" self.config = configparser.ConfigParser() self.config.read('config.ini') self.MSGLEN = 1024 self.END_OF_MSG = '*' self.ip = ipaddr self.buffer = 20 # self.commands = {'version?':self.version_cmd,'commands?':self.commands_cmd,'status?':self.status_cmd} hcvc = hazc_cmd.hazc_cmd('version?', self.version_cmd, self.NO_PARAM) hccc = hazc_cmd.hazc_cmd('commands?', self.commands_cmd, self.NO_PARAM) hcsc = hazc_cmd.hazc_cmd('status?', self.status_cmd, self.STRING) self.commands = {'version': hcvc, 'commands': hccc, 'status': hcsc} # probably want to add a debug log status self.status = {'exec_status': self.exec_status} #Adds a function - not as preferred as addControl #Does NOT auto add status def addFunction(self, name, handler, paramtype): # pdb.settrace() #log("This is not the preferred way to add controls, see addControl") if not('?' in name or '!' in name): # log("Function name requires a '?' or '!', assuming '!'") name += '!' self.commands[name] = hazc_cmd.hazc_cmd(name, handler, paramtype) #Adds a control vector #controlname should just be a name like 'temp' or 'position' - it'll be the same for the status def addControl(self, controlname, handler, statushandler, paramtype=NO_PARAM): cmd_name = 'set-'+controlname self.commands[cmd_name] = hazc_cmd.hazc_cmd(cmd_name+'?', handler, paramtype) self.addStatus(controlname, statushandler) #adds a unique status not already included in control vector. name is just the name, as in 'temp' def addStatus(self, name, handler): self.status[name] = handler def advertise(self): postfix = self.config['global']['service_prefix'] self.port = int(self.config['global']['port']) #print(self.config['device']['hostname']+postfix) info = ServiceInfo(postfix, self.config['device']['hostname']+"."+postfix, socket.inet_aton(self.ip), self.port, 0, 0, {'info': self.config['device']['description']}, "hazc.local.") self.bindConnection() zeroconf = Zeroconf() zeroconf.register_service(info) try: while True: # try: print("Ready") self.conn, self.addr = self.webcontrol.accept() self.listen() self.conn.close() except KeyboardInterrupt: pass finally: print() print("Unregistering...") zeroconf.unregister_service(info) zeroconf.close() try: print("Shutting down socket") self.webcontrol.shutdown(socket.SHUT_RDWR) except Exception as e: print(e) def listen(self): data = bytes() rbytes = 0 while rbytes < self.MSGLEN: d = self.conn.recv(self.buffer) if not d: break data += d rbytes += len(d) # print data.decode('utf-8') self.handledata(data) def handledata(self, data): command, param = self.cleanandstringdata(data) print('->' + command + ';' + param) # replystr = "ERROR" try: replystr = self.commands[command].execute(param) except KeyError: if(command==''): command = "(empty string)" print("ERROR! Unknown command: " + command) replystr = "" # replystr = self.commands['version'].execute('') if(replystr == None): print("WARNING! " + command + " should return a string to send to the master. Sending 'NO_REPLY'") replystr = 'NO_REPLY' print(replystr) self.reply(replystr) def <|fim_middle|>(self, msg): longmsg = msg while len(longmsg) < self.MSGLEN: longmsg += self.END_OF_MSG # print(longmsg) self.conn.send(longmsg.encode('utf-8')) def cleanandstringdata(self, data): dstr = data.decode('utf-8') full = dstr.strip(self.END_OF_MSG) if '?' in full: li = full.split('?') param = li[-1] cmd = li[0] elif '!' in full: li = full.split('!') param = li[-1] cmd = li[0] else: param = '' cmd = full return (cmd, param) def bindConnection(self): try: self.webcontrol = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.webcontrol.bind((self.ip, self.port)) self.webcontrol.listen(1) except OSError as e: print(e) quit() def exec_status(self): return "Running" def version_cmd(self): return self.version def paramtype_tostring(self, paramnum): if paramnum == self.BOOL: return 'BOOL' elif paramnum == self.FLOAT: return 'FLOAT' elif paramnum == self.STRING: return 'STRING' elif paramnum == self.INT: return 'INT' else: return 'PARAM_ERROR' def commands_cmd(self): rstr = "" for key in self.commands: rstr += key if self.commands[key].paramtype is not self.NO_PARAM: # pdb.set_trace() rstr += ':' + self.paramtype_tostring(self.commands[key].paramtype) rstr += ";" return rstr def status_cmd(self, specific_status=''): str = '' if len(specific_status) > 0: str = self.status[specific_status] else: for st in self.status: str += st + ',' + self.status[st]() + ';' return str[:self.MSGLEN-1] # Some debugging methods def debug_cmds(self): print("Commands: " + str(self.commands)) print("Statuses: " + str(self.status))<|fim▁end|>
reply
<|file_name|>hazc_device.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 from zeroconf import Zeroconf, ServiceInfo import socket import configparser from . import hazc_cmd # import pdb class hazc_device: #Forward constants NO_PARAM = hazc_cmd.NO_PARAM BOOL = hazc_cmd.BOOL FLOAT = hazc_cmd.FLOAT STRING = hazc_cmd.STRING INT = hazc_cmd.INT global running running = False def __init__(self, ipaddr): self.version = "0.1" self.config = configparser.ConfigParser() self.config.read('config.ini') self.MSGLEN = 1024 self.END_OF_MSG = '*' self.ip = ipaddr self.buffer = 20 # self.commands = {'version?':self.version_cmd,'commands?':self.commands_cmd,'status?':self.status_cmd} hcvc = hazc_cmd.hazc_cmd('version?', self.version_cmd, self.NO_PARAM) hccc = hazc_cmd.hazc_cmd('commands?', self.commands_cmd, self.NO_PARAM) hcsc = hazc_cmd.hazc_cmd('status?', self.status_cmd, self.STRING) self.commands = {'version': hcvc, 'commands': hccc, 'status': hcsc} # probably want to add a debug log status self.status = {'exec_status': self.exec_status} #Adds a function - not as preferred as addControl #Does NOT auto add status def addFunction(self, name, handler, paramtype): # pdb.settrace() #log("This is not the preferred way to add controls, see addControl") if not('?' in name or '!' in name): # log("Function name requires a '?' or '!', assuming '!'") name += '!' self.commands[name] = hazc_cmd.hazc_cmd(name, handler, paramtype) #Adds a control vector #controlname should just be a name like 'temp' or 'position' - it'll be the same for the status def addControl(self, controlname, handler, statushandler, paramtype=NO_PARAM): cmd_name = 'set-'+controlname self.commands[cmd_name] = hazc_cmd.hazc_cmd(cmd_name+'?', handler, paramtype) self.addStatus(controlname, statushandler) #adds a unique status not already included in control vector. name is just the name, as in 'temp' def addStatus(self, name, handler): self.status[name] = handler def advertise(self): postfix = self.config['global']['service_prefix'] self.port = int(self.config['global']['port']) #print(self.config['device']['hostname']+postfix) info = ServiceInfo(postfix, self.config['device']['hostname']+"."+postfix, socket.inet_aton(self.ip), self.port, 0, 0, {'info': self.config['device']['description']}, "hazc.local.") self.bindConnection() zeroconf = Zeroconf() zeroconf.register_service(info) try: while True: # try: print("Ready") self.conn, self.addr = self.webcontrol.accept() self.listen() self.conn.close() except KeyboardInterrupt: pass finally: print() print("Unregistering...") zeroconf.unregister_service(info) zeroconf.close() try: print("Shutting down socket") self.webcontrol.shutdown(socket.SHUT_RDWR) except Exception as e: print(e) def listen(self): data = bytes() rbytes = 0 while rbytes < self.MSGLEN: d = self.conn.recv(self.buffer) if not d: break data += d rbytes += len(d) # print data.decode('utf-8') self.handledata(data) def handledata(self, data): command, param = self.cleanandstringdata(data) print('->' + command + ';' + param) # replystr = "ERROR" try: replystr = self.commands[command].execute(param) except KeyError: if(command==''): command = "(empty string)" print("ERROR! Unknown command: " + command) replystr = "" # replystr = self.commands['version'].execute('') if(replystr == None): print("WARNING! " + command + " should return a string to send to the master. Sending 'NO_REPLY'") replystr = 'NO_REPLY' print(replystr) self.reply(replystr) def reply(self, msg): longmsg = msg while len(longmsg) < self.MSGLEN: longmsg += self.END_OF_MSG # print(longmsg) self.conn.send(longmsg.encode('utf-8')) def <|fim_middle|>(self, data): dstr = data.decode('utf-8') full = dstr.strip(self.END_OF_MSG) if '?' in full: li = full.split('?') param = li[-1] cmd = li[0] elif '!' in full: li = full.split('!') param = li[-1] cmd = li[0] else: param = '' cmd = full return (cmd, param) def bindConnection(self): try: self.webcontrol = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.webcontrol.bind((self.ip, self.port)) self.webcontrol.listen(1) except OSError as e: print(e) quit() def exec_status(self): return "Running" def version_cmd(self): return self.version def paramtype_tostring(self, paramnum): if paramnum == self.BOOL: return 'BOOL' elif paramnum == self.FLOAT: return 'FLOAT' elif paramnum == self.STRING: return 'STRING' elif paramnum == self.INT: return 'INT' else: return 'PARAM_ERROR' def commands_cmd(self): rstr = "" for key in self.commands: rstr += key if self.commands[key].paramtype is not self.NO_PARAM: # pdb.set_trace() rstr += ':' + self.paramtype_tostring(self.commands[key].paramtype) rstr += ";" return rstr def status_cmd(self, specific_status=''): str = '' if len(specific_status) > 0: str = self.status[specific_status] else: for st in self.status: str += st + ',' + self.status[st]() + ';' return str[:self.MSGLEN-1] # Some debugging methods def debug_cmds(self): print("Commands: " + str(self.commands)) print("Statuses: " + str(self.status))<|fim▁end|>
cleanandstringdata
<|file_name|>hazc_device.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 from zeroconf import Zeroconf, ServiceInfo import socket import configparser from . import hazc_cmd # import pdb class hazc_device: #Forward constants NO_PARAM = hazc_cmd.NO_PARAM BOOL = hazc_cmd.BOOL FLOAT = hazc_cmd.FLOAT STRING = hazc_cmd.STRING INT = hazc_cmd.INT global running running = False def __init__(self, ipaddr): self.version = "0.1" self.config = configparser.ConfigParser() self.config.read('config.ini') self.MSGLEN = 1024 self.END_OF_MSG = '*' self.ip = ipaddr self.buffer = 20 # self.commands = {'version?':self.version_cmd,'commands?':self.commands_cmd,'status?':self.status_cmd} hcvc = hazc_cmd.hazc_cmd('version?', self.version_cmd, self.NO_PARAM) hccc = hazc_cmd.hazc_cmd('commands?', self.commands_cmd, self.NO_PARAM) hcsc = hazc_cmd.hazc_cmd('status?', self.status_cmd, self.STRING) self.commands = {'version': hcvc, 'commands': hccc, 'status': hcsc} # probably want to add a debug log status self.status = {'exec_status': self.exec_status} #Adds a function - not as preferred as addControl #Does NOT auto add status def addFunction(self, name, handler, paramtype): # pdb.settrace() #log("This is not the preferred way to add controls, see addControl") if not('?' in name or '!' in name): # log("Function name requires a '?' or '!', assuming '!'") name += '!' self.commands[name] = hazc_cmd.hazc_cmd(name, handler, paramtype) #Adds a control vector #controlname should just be a name like 'temp' or 'position' - it'll be the same for the status def addControl(self, controlname, handler, statushandler, paramtype=NO_PARAM): cmd_name = 'set-'+controlname self.commands[cmd_name] = hazc_cmd.hazc_cmd(cmd_name+'?', handler, paramtype) self.addStatus(controlname, statushandler) #adds a unique status not already included in control vector. name is just the name, as in 'temp' def addStatus(self, name, handler): self.status[name] = handler def advertise(self): postfix = self.config['global']['service_prefix'] self.port = int(self.config['global']['port']) #print(self.config['device']['hostname']+postfix) info = ServiceInfo(postfix, self.config['device']['hostname']+"."+postfix, socket.inet_aton(self.ip), self.port, 0, 0, {'info': self.config['device']['description']}, "hazc.local.") self.bindConnection() zeroconf = Zeroconf() zeroconf.register_service(info) try: while True: # try: print("Ready") self.conn, self.addr = self.webcontrol.accept() self.listen() self.conn.close() except KeyboardInterrupt: pass finally: print() print("Unregistering...") zeroconf.unregister_service(info) zeroconf.close() try: print("Shutting down socket") self.webcontrol.shutdown(socket.SHUT_RDWR) except Exception as e: print(e) def listen(self): data = bytes() rbytes = 0 while rbytes < self.MSGLEN: d = self.conn.recv(self.buffer) if not d: break data += d rbytes += len(d) # print data.decode('utf-8') self.handledata(data) def handledata(self, data): command, param = self.cleanandstringdata(data) print('->' + command + ';' + param) # replystr = "ERROR" try: replystr = self.commands[command].execute(param) except KeyError: if(command==''): command = "(empty string)" print("ERROR! Unknown command: " + command) replystr = "" # replystr = self.commands['version'].execute('') if(replystr == None): print("WARNING! " + command + " should return a string to send to the master. Sending 'NO_REPLY'") replystr = 'NO_REPLY' print(replystr) self.reply(replystr) def reply(self, msg): longmsg = msg while len(longmsg) < self.MSGLEN: longmsg += self.END_OF_MSG # print(longmsg) self.conn.send(longmsg.encode('utf-8')) def cleanandstringdata(self, data): dstr = data.decode('utf-8') full = dstr.strip(self.END_OF_MSG) if '?' in full: li = full.split('?') param = li[-1] cmd = li[0] elif '!' in full: li = full.split('!') param = li[-1] cmd = li[0] else: param = '' cmd = full return (cmd, param) def <|fim_middle|>(self): try: self.webcontrol = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.webcontrol.bind((self.ip, self.port)) self.webcontrol.listen(1) except OSError as e: print(e) quit() def exec_status(self): return "Running" def version_cmd(self): return self.version def paramtype_tostring(self, paramnum): if paramnum == self.BOOL: return 'BOOL' elif paramnum == self.FLOAT: return 'FLOAT' elif paramnum == self.STRING: return 'STRING' elif paramnum == self.INT: return 'INT' else: return 'PARAM_ERROR' def commands_cmd(self): rstr = "" for key in self.commands: rstr += key if self.commands[key].paramtype is not self.NO_PARAM: # pdb.set_trace() rstr += ':' + self.paramtype_tostring(self.commands[key].paramtype) rstr += ";" return rstr def status_cmd(self, specific_status=''): str = '' if len(specific_status) > 0: str = self.status[specific_status] else: for st in self.status: str += st + ',' + self.status[st]() + ';' return str[:self.MSGLEN-1] # Some debugging methods def debug_cmds(self): print("Commands: " + str(self.commands)) print("Statuses: " + str(self.status))<|fim▁end|>
bindConnection
<|file_name|>hazc_device.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 from zeroconf import Zeroconf, ServiceInfo import socket import configparser from . import hazc_cmd # import pdb class hazc_device: #Forward constants NO_PARAM = hazc_cmd.NO_PARAM BOOL = hazc_cmd.BOOL FLOAT = hazc_cmd.FLOAT STRING = hazc_cmd.STRING INT = hazc_cmd.INT global running running = False def __init__(self, ipaddr): self.version = "0.1" self.config = configparser.ConfigParser() self.config.read('config.ini') self.MSGLEN = 1024 self.END_OF_MSG = '*' self.ip = ipaddr self.buffer = 20 # self.commands = {'version?':self.version_cmd,'commands?':self.commands_cmd,'status?':self.status_cmd} hcvc = hazc_cmd.hazc_cmd('version?', self.version_cmd, self.NO_PARAM) hccc = hazc_cmd.hazc_cmd('commands?', self.commands_cmd, self.NO_PARAM) hcsc = hazc_cmd.hazc_cmd('status?', self.status_cmd, self.STRING) self.commands = {'version': hcvc, 'commands': hccc, 'status': hcsc} # probably want to add a debug log status self.status = {'exec_status': self.exec_status} #Adds a function - not as preferred as addControl #Does NOT auto add status def addFunction(self, name, handler, paramtype): # pdb.settrace() #log("This is not the preferred way to add controls, see addControl") if not('?' in name or '!' in name): # log("Function name requires a '?' or '!', assuming '!'") name += '!' self.commands[name] = hazc_cmd.hazc_cmd(name, handler, paramtype) #Adds a control vector #controlname should just be a name like 'temp' or 'position' - it'll be the same for the status def addControl(self, controlname, handler, statushandler, paramtype=NO_PARAM): cmd_name = 'set-'+controlname self.commands[cmd_name] = hazc_cmd.hazc_cmd(cmd_name+'?', handler, paramtype) self.addStatus(controlname, statushandler) #adds a unique status not already included in control vector. name is just the name, as in 'temp' def addStatus(self, name, handler): self.status[name] = handler def advertise(self): postfix = self.config['global']['service_prefix'] self.port = int(self.config['global']['port']) #print(self.config['device']['hostname']+postfix) info = ServiceInfo(postfix, self.config['device']['hostname']+"."+postfix, socket.inet_aton(self.ip), self.port, 0, 0, {'info': self.config['device']['description']}, "hazc.local.") self.bindConnection() zeroconf = Zeroconf() zeroconf.register_service(info) try: while True: # try: print("Ready") self.conn, self.addr = self.webcontrol.accept() self.listen() self.conn.close() except KeyboardInterrupt: pass finally: print() print("Unregistering...") zeroconf.unregister_service(info) zeroconf.close() try: print("Shutting down socket") self.webcontrol.shutdown(socket.SHUT_RDWR) except Exception as e: print(e) def listen(self): data = bytes() rbytes = 0 while rbytes < self.MSGLEN: d = self.conn.recv(self.buffer) if not d: break data += d rbytes += len(d) # print data.decode('utf-8') self.handledata(data) def handledata(self, data): command, param = self.cleanandstringdata(data) print('->' + command + ';' + param) # replystr = "ERROR" try: replystr = self.commands[command].execute(param) except KeyError: if(command==''): command = "(empty string)" print("ERROR! Unknown command: " + command) replystr = "" # replystr = self.commands['version'].execute('') if(replystr == None): print("WARNING! " + command + " should return a string to send to the master. Sending 'NO_REPLY'") replystr = 'NO_REPLY' print(replystr) self.reply(replystr) def reply(self, msg): longmsg = msg while len(longmsg) < self.MSGLEN: longmsg += self.END_OF_MSG # print(longmsg) self.conn.send(longmsg.encode('utf-8')) def cleanandstringdata(self, data): dstr = data.decode('utf-8') full = dstr.strip(self.END_OF_MSG) if '?' in full: li = full.split('?') param = li[-1] cmd = li[0] elif '!' in full: li = full.split('!') param = li[-1] cmd = li[0] else: param = '' cmd = full return (cmd, param) def bindConnection(self): try: self.webcontrol = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.webcontrol.bind((self.ip, self.port)) self.webcontrol.listen(1) except OSError as e: print(e) quit() def <|fim_middle|>(self): return "Running" def version_cmd(self): return self.version def paramtype_tostring(self, paramnum): if paramnum == self.BOOL: return 'BOOL' elif paramnum == self.FLOAT: return 'FLOAT' elif paramnum == self.STRING: return 'STRING' elif paramnum == self.INT: return 'INT' else: return 'PARAM_ERROR' def commands_cmd(self): rstr = "" for key in self.commands: rstr += key if self.commands[key].paramtype is not self.NO_PARAM: # pdb.set_trace() rstr += ':' + self.paramtype_tostring(self.commands[key].paramtype) rstr += ";" return rstr def status_cmd(self, specific_status=''): str = '' if len(specific_status) > 0: str = self.status[specific_status] else: for st in self.status: str += st + ',' + self.status[st]() + ';' return str[:self.MSGLEN-1] # Some debugging methods def debug_cmds(self): print("Commands: " + str(self.commands)) print("Statuses: " + str(self.status))<|fim▁end|>
exec_status
<|file_name|>hazc_device.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 from zeroconf import Zeroconf, ServiceInfo import socket import configparser from . import hazc_cmd # import pdb class hazc_device: #Forward constants NO_PARAM = hazc_cmd.NO_PARAM BOOL = hazc_cmd.BOOL FLOAT = hazc_cmd.FLOAT STRING = hazc_cmd.STRING INT = hazc_cmd.INT global running running = False def __init__(self, ipaddr): self.version = "0.1" self.config = configparser.ConfigParser() self.config.read('config.ini') self.MSGLEN = 1024 self.END_OF_MSG = '*' self.ip = ipaddr self.buffer = 20 # self.commands = {'version?':self.version_cmd,'commands?':self.commands_cmd,'status?':self.status_cmd} hcvc = hazc_cmd.hazc_cmd('version?', self.version_cmd, self.NO_PARAM) hccc = hazc_cmd.hazc_cmd('commands?', self.commands_cmd, self.NO_PARAM) hcsc = hazc_cmd.hazc_cmd('status?', self.status_cmd, self.STRING) self.commands = {'version': hcvc, 'commands': hccc, 'status': hcsc} # probably want to add a debug log status self.status = {'exec_status': self.exec_status} #Adds a function - not as preferred as addControl #Does NOT auto add status def addFunction(self, name, handler, paramtype): # pdb.settrace() #log("This is not the preferred way to add controls, see addControl") if not('?' in name or '!' in name): # log("Function name requires a '?' or '!', assuming '!'") name += '!' self.commands[name] = hazc_cmd.hazc_cmd(name, handler, paramtype) #Adds a control vector #controlname should just be a name like 'temp' or 'position' - it'll be the same for the status def addControl(self, controlname, handler, statushandler, paramtype=NO_PARAM): cmd_name = 'set-'+controlname self.commands[cmd_name] = hazc_cmd.hazc_cmd(cmd_name+'?', handler, paramtype) self.addStatus(controlname, statushandler) #adds a unique status not already included in control vector. name is just the name, as in 'temp' def addStatus(self, name, handler): self.status[name] = handler def advertise(self): postfix = self.config['global']['service_prefix'] self.port = int(self.config['global']['port']) #print(self.config['device']['hostname']+postfix) info = ServiceInfo(postfix, self.config['device']['hostname']+"."+postfix, socket.inet_aton(self.ip), self.port, 0, 0, {'info': self.config['device']['description']}, "hazc.local.") self.bindConnection() zeroconf = Zeroconf() zeroconf.register_service(info) try: while True: # try: print("Ready") self.conn, self.addr = self.webcontrol.accept() self.listen() self.conn.close() except KeyboardInterrupt: pass finally: print() print("Unregistering...") zeroconf.unregister_service(info) zeroconf.close() try: print("Shutting down socket") self.webcontrol.shutdown(socket.SHUT_RDWR) except Exception as e: print(e) def listen(self): data = bytes() rbytes = 0 while rbytes < self.MSGLEN: d = self.conn.recv(self.buffer) if not d: break data += d rbytes += len(d) # print data.decode('utf-8') self.handledata(data) def handledata(self, data): command, param = self.cleanandstringdata(data) print('->' + command + ';' + param) # replystr = "ERROR" try: replystr = self.commands[command].execute(param) except KeyError: if(command==''): command = "(empty string)" print("ERROR! Unknown command: " + command) replystr = "" # replystr = self.commands['version'].execute('') if(replystr == None): print("WARNING! " + command + " should return a string to send to the master. Sending 'NO_REPLY'") replystr = 'NO_REPLY' print(replystr) self.reply(replystr) def reply(self, msg): longmsg = msg while len(longmsg) < self.MSGLEN: longmsg += self.END_OF_MSG # print(longmsg) self.conn.send(longmsg.encode('utf-8')) def cleanandstringdata(self, data): dstr = data.decode('utf-8') full = dstr.strip(self.END_OF_MSG) if '?' in full: li = full.split('?') param = li[-1] cmd = li[0] elif '!' in full: li = full.split('!') param = li[-1] cmd = li[0] else: param = '' cmd = full return (cmd, param) def bindConnection(self): try: self.webcontrol = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.webcontrol.bind((self.ip, self.port)) self.webcontrol.listen(1) except OSError as e: print(e) quit() def exec_status(self): return "Running" def <|fim_middle|>(self): return self.version def paramtype_tostring(self, paramnum): if paramnum == self.BOOL: return 'BOOL' elif paramnum == self.FLOAT: return 'FLOAT' elif paramnum == self.STRING: return 'STRING' elif paramnum == self.INT: return 'INT' else: return 'PARAM_ERROR' def commands_cmd(self): rstr = "" for key in self.commands: rstr += key if self.commands[key].paramtype is not self.NO_PARAM: # pdb.set_trace() rstr += ':' + self.paramtype_tostring(self.commands[key].paramtype) rstr += ";" return rstr def status_cmd(self, specific_status=''): str = '' if len(specific_status) > 0: str = self.status[specific_status] else: for st in self.status: str += st + ',' + self.status[st]() + ';' return str[:self.MSGLEN-1] # Some debugging methods def debug_cmds(self): print("Commands: " + str(self.commands)) print("Statuses: " + str(self.status))<|fim▁end|>
version_cmd
<|file_name|>hazc_device.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 from zeroconf import Zeroconf, ServiceInfo import socket import configparser from . import hazc_cmd # import pdb class hazc_device: #Forward constants NO_PARAM = hazc_cmd.NO_PARAM BOOL = hazc_cmd.BOOL FLOAT = hazc_cmd.FLOAT STRING = hazc_cmd.STRING INT = hazc_cmd.INT global running running = False def __init__(self, ipaddr): self.version = "0.1" self.config = configparser.ConfigParser() self.config.read('config.ini') self.MSGLEN = 1024 self.END_OF_MSG = '*' self.ip = ipaddr self.buffer = 20 # self.commands = {'version?':self.version_cmd,'commands?':self.commands_cmd,'status?':self.status_cmd} hcvc = hazc_cmd.hazc_cmd('version?', self.version_cmd, self.NO_PARAM) hccc = hazc_cmd.hazc_cmd('commands?', self.commands_cmd, self.NO_PARAM) hcsc = hazc_cmd.hazc_cmd('status?', self.status_cmd, self.STRING) self.commands = {'version': hcvc, 'commands': hccc, 'status': hcsc} # probably want to add a debug log status self.status = {'exec_status': self.exec_status} #Adds a function - not as preferred as addControl #Does NOT auto add status def addFunction(self, name, handler, paramtype): # pdb.settrace() #log("This is not the preferred way to add controls, see addControl") if not('?' in name or '!' in name): # log("Function name requires a '?' or '!', assuming '!'") name += '!' self.commands[name] = hazc_cmd.hazc_cmd(name, handler, paramtype) #Adds a control vector #controlname should just be a name like 'temp' or 'position' - it'll be the same for the status def addControl(self, controlname, handler, statushandler, paramtype=NO_PARAM): cmd_name = 'set-'+controlname self.commands[cmd_name] = hazc_cmd.hazc_cmd(cmd_name+'?', handler, paramtype) self.addStatus(controlname, statushandler) #adds a unique status not already included in control vector. name is just the name, as in 'temp' def addStatus(self, name, handler): self.status[name] = handler def advertise(self): postfix = self.config['global']['service_prefix'] self.port = int(self.config['global']['port']) #print(self.config['device']['hostname']+postfix) info = ServiceInfo(postfix, self.config['device']['hostname']+"."+postfix, socket.inet_aton(self.ip), self.port, 0, 0, {'info': self.config['device']['description']}, "hazc.local.") self.bindConnection() zeroconf = Zeroconf() zeroconf.register_service(info) try: while True: # try: print("Ready") self.conn, self.addr = self.webcontrol.accept() self.listen() self.conn.close() except KeyboardInterrupt: pass finally: print() print("Unregistering...") zeroconf.unregister_service(info) zeroconf.close() try: print("Shutting down socket") self.webcontrol.shutdown(socket.SHUT_RDWR) except Exception as e: print(e) def listen(self): data = bytes() rbytes = 0 while rbytes < self.MSGLEN: d = self.conn.recv(self.buffer) if not d: break data += d rbytes += len(d) # print data.decode('utf-8') self.handledata(data) def handledata(self, data): command, param = self.cleanandstringdata(data) print('->' + command + ';' + param) # replystr = "ERROR" try: replystr = self.commands[command].execute(param) except KeyError: if(command==''): command = "(empty string)" print("ERROR! Unknown command: " + command) replystr = "" # replystr = self.commands['version'].execute('') if(replystr == None): print("WARNING! " + command + " should return a string to send to the master. Sending 'NO_REPLY'") replystr = 'NO_REPLY' print(replystr) self.reply(replystr) def reply(self, msg): longmsg = msg while len(longmsg) < self.MSGLEN: longmsg += self.END_OF_MSG # print(longmsg) self.conn.send(longmsg.encode('utf-8')) def cleanandstringdata(self, data): dstr = data.decode('utf-8') full = dstr.strip(self.END_OF_MSG) if '?' in full: li = full.split('?') param = li[-1] cmd = li[0] elif '!' in full: li = full.split('!') param = li[-1] cmd = li[0] else: param = '' cmd = full return (cmd, param) def bindConnection(self): try: self.webcontrol = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.webcontrol.bind((self.ip, self.port)) self.webcontrol.listen(1) except OSError as e: print(e) quit() def exec_status(self): return "Running" def version_cmd(self): return self.version def <|fim_middle|>(self, paramnum): if paramnum == self.BOOL: return 'BOOL' elif paramnum == self.FLOAT: return 'FLOAT' elif paramnum == self.STRING: return 'STRING' elif paramnum == self.INT: return 'INT' else: return 'PARAM_ERROR' def commands_cmd(self): rstr = "" for key in self.commands: rstr += key if self.commands[key].paramtype is not self.NO_PARAM: # pdb.set_trace() rstr += ':' + self.paramtype_tostring(self.commands[key].paramtype) rstr += ";" return rstr def status_cmd(self, specific_status=''): str = '' if len(specific_status) > 0: str = self.status[specific_status] else: for st in self.status: str += st + ',' + self.status[st]() + ';' return str[:self.MSGLEN-1] # Some debugging methods def debug_cmds(self): print("Commands: " + str(self.commands)) print("Statuses: " + str(self.status))<|fim▁end|>
paramtype_tostring
<|file_name|>hazc_device.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 from zeroconf import Zeroconf, ServiceInfo import socket import configparser from . import hazc_cmd # import pdb class hazc_device: #Forward constants NO_PARAM = hazc_cmd.NO_PARAM BOOL = hazc_cmd.BOOL FLOAT = hazc_cmd.FLOAT STRING = hazc_cmd.STRING INT = hazc_cmd.INT global running running = False def __init__(self, ipaddr): self.version = "0.1" self.config = configparser.ConfigParser() self.config.read('config.ini') self.MSGLEN = 1024 self.END_OF_MSG = '*' self.ip = ipaddr self.buffer = 20 # self.commands = {'version?':self.version_cmd,'commands?':self.commands_cmd,'status?':self.status_cmd} hcvc = hazc_cmd.hazc_cmd('version?', self.version_cmd, self.NO_PARAM) hccc = hazc_cmd.hazc_cmd('commands?', self.commands_cmd, self.NO_PARAM) hcsc = hazc_cmd.hazc_cmd('status?', self.status_cmd, self.STRING) self.commands = {'version': hcvc, 'commands': hccc, 'status': hcsc} # probably want to add a debug log status self.status = {'exec_status': self.exec_status} #Adds a function - not as preferred as addControl #Does NOT auto add status def addFunction(self, name, handler, paramtype): # pdb.settrace() #log("This is not the preferred way to add controls, see addControl") if not('?' in name or '!' in name): # log("Function name requires a '?' or '!', assuming '!'") name += '!' self.commands[name] = hazc_cmd.hazc_cmd(name, handler, paramtype) #Adds a control vector #controlname should just be a name like 'temp' or 'position' - it'll be the same for the status def addControl(self, controlname, handler, statushandler, paramtype=NO_PARAM): cmd_name = 'set-'+controlname self.commands[cmd_name] = hazc_cmd.hazc_cmd(cmd_name+'?', handler, paramtype) self.addStatus(controlname, statushandler) #adds a unique status not already included in control vector. name is just the name, as in 'temp' def addStatus(self, name, handler): self.status[name] = handler def advertise(self): postfix = self.config['global']['service_prefix'] self.port = int(self.config['global']['port']) #print(self.config['device']['hostname']+postfix) info = ServiceInfo(postfix, self.config['device']['hostname']+"."+postfix, socket.inet_aton(self.ip), self.port, 0, 0, {'info': self.config['device']['description']}, "hazc.local.") self.bindConnection() zeroconf = Zeroconf() zeroconf.register_service(info) try: while True: # try: print("Ready") self.conn, self.addr = self.webcontrol.accept() self.listen() self.conn.close() except KeyboardInterrupt: pass finally: print() print("Unregistering...") zeroconf.unregister_service(info) zeroconf.close() try: print("Shutting down socket") self.webcontrol.shutdown(socket.SHUT_RDWR) except Exception as e: print(e) def listen(self): data = bytes() rbytes = 0 while rbytes < self.MSGLEN: d = self.conn.recv(self.buffer) if not d: break data += d rbytes += len(d) # print data.decode('utf-8') self.handledata(data) def handledata(self, data): command, param = self.cleanandstringdata(data) print('->' + command + ';' + param) # replystr = "ERROR" try: replystr = self.commands[command].execute(param) except KeyError: if(command==''): command = "(empty string)" print("ERROR! Unknown command: " + command) replystr = "" # replystr = self.commands['version'].execute('') if(replystr == None): print("WARNING! " + command + " should return a string to send to the master. Sending 'NO_REPLY'") replystr = 'NO_REPLY' print(replystr) self.reply(replystr) def reply(self, msg): longmsg = msg while len(longmsg) < self.MSGLEN: longmsg += self.END_OF_MSG # print(longmsg) self.conn.send(longmsg.encode('utf-8')) def cleanandstringdata(self, data): dstr = data.decode('utf-8') full = dstr.strip(self.END_OF_MSG) if '?' in full: li = full.split('?') param = li[-1] cmd = li[0] elif '!' in full: li = full.split('!') param = li[-1] cmd = li[0] else: param = '' cmd = full return (cmd, param) def bindConnection(self): try: self.webcontrol = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.webcontrol.bind((self.ip, self.port)) self.webcontrol.listen(1) except OSError as e: print(e) quit() def exec_status(self): return "Running" def version_cmd(self): return self.version def paramtype_tostring(self, paramnum): if paramnum == self.BOOL: return 'BOOL' elif paramnum == self.FLOAT: return 'FLOAT' elif paramnum == self.STRING: return 'STRING' elif paramnum == self.INT: return 'INT' else: return 'PARAM_ERROR' def <|fim_middle|>(self): rstr = "" for key in self.commands: rstr += key if self.commands[key].paramtype is not self.NO_PARAM: # pdb.set_trace() rstr += ':' + self.paramtype_tostring(self.commands[key].paramtype) rstr += ";" return rstr def status_cmd(self, specific_status=''): str = '' if len(specific_status) > 0: str = self.status[specific_status] else: for st in self.status: str += st + ',' + self.status[st]() + ';' return str[:self.MSGLEN-1] # Some debugging methods def debug_cmds(self): print("Commands: " + str(self.commands)) print("Statuses: " + str(self.status))<|fim▁end|>
commands_cmd
<|file_name|>hazc_device.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 from zeroconf import Zeroconf, ServiceInfo import socket import configparser from . import hazc_cmd # import pdb class hazc_device: #Forward constants NO_PARAM = hazc_cmd.NO_PARAM BOOL = hazc_cmd.BOOL FLOAT = hazc_cmd.FLOAT STRING = hazc_cmd.STRING INT = hazc_cmd.INT global running running = False def __init__(self, ipaddr): self.version = "0.1" self.config = configparser.ConfigParser() self.config.read('config.ini') self.MSGLEN = 1024 self.END_OF_MSG = '*' self.ip = ipaddr self.buffer = 20 # self.commands = {'version?':self.version_cmd,'commands?':self.commands_cmd,'status?':self.status_cmd} hcvc = hazc_cmd.hazc_cmd('version?', self.version_cmd, self.NO_PARAM) hccc = hazc_cmd.hazc_cmd('commands?', self.commands_cmd, self.NO_PARAM) hcsc = hazc_cmd.hazc_cmd('status?', self.status_cmd, self.STRING) self.commands = {'version': hcvc, 'commands': hccc, 'status': hcsc} # probably want to add a debug log status self.status = {'exec_status': self.exec_status} #Adds a function - not as preferred as addControl #Does NOT auto add status def addFunction(self, name, handler, paramtype): # pdb.settrace() #log("This is not the preferred way to add controls, see addControl") if not('?' in name or '!' in name): # log("Function name requires a '?' or '!', assuming '!'") name += '!' self.commands[name] = hazc_cmd.hazc_cmd(name, handler, paramtype) #Adds a control vector #controlname should just be a name like 'temp' or 'position' - it'll be the same for the status def addControl(self, controlname, handler, statushandler, paramtype=NO_PARAM): cmd_name = 'set-'+controlname self.commands[cmd_name] = hazc_cmd.hazc_cmd(cmd_name+'?', handler, paramtype) self.addStatus(controlname, statushandler) #adds a unique status not already included in control vector. name is just the name, as in 'temp' def addStatus(self, name, handler): self.status[name] = handler def advertise(self): postfix = self.config['global']['service_prefix'] self.port = int(self.config['global']['port']) #print(self.config['device']['hostname']+postfix) info = ServiceInfo(postfix, self.config['device']['hostname']+"."+postfix, socket.inet_aton(self.ip), self.port, 0, 0, {'info': self.config['device']['description']}, "hazc.local.") self.bindConnection() zeroconf = Zeroconf() zeroconf.register_service(info) try: while True: # try: print("Ready") self.conn, self.addr = self.webcontrol.accept() self.listen() self.conn.close() except KeyboardInterrupt: pass finally: print() print("Unregistering...") zeroconf.unregister_service(info) zeroconf.close() try: print("Shutting down socket") self.webcontrol.shutdown(socket.SHUT_RDWR) except Exception as e: print(e) def listen(self): data = bytes() rbytes = 0 while rbytes < self.MSGLEN: d = self.conn.recv(self.buffer) if not d: break data += d rbytes += len(d) # print data.decode('utf-8') self.handledata(data) def handledata(self, data): command, param = self.cleanandstringdata(data) print('->' + command + ';' + param) # replystr = "ERROR" try: replystr = self.commands[command].execute(param) except KeyError: if(command==''): command = "(empty string)" print("ERROR! Unknown command: " + command) replystr = "" # replystr = self.commands['version'].execute('') if(replystr == None): print("WARNING! " + command + " should return a string to send to the master. Sending 'NO_REPLY'") replystr = 'NO_REPLY' print(replystr) self.reply(replystr) def reply(self, msg): longmsg = msg while len(longmsg) < self.MSGLEN: longmsg += self.END_OF_MSG # print(longmsg) self.conn.send(longmsg.encode('utf-8')) def cleanandstringdata(self, data): dstr = data.decode('utf-8') full = dstr.strip(self.END_OF_MSG) if '?' in full: li = full.split('?') param = li[-1] cmd = li[0] elif '!' in full: li = full.split('!') param = li[-1] cmd = li[0] else: param = '' cmd = full return (cmd, param) def bindConnection(self): try: self.webcontrol = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.webcontrol.bind((self.ip, self.port)) self.webcontrol.listen(1) except OSError as e: print(e) quit() def exec_status(self): return "Running" def version_cmd(self): return self.version def paramtype_tostring(self, paramnum): if paramnum == self.BOOL: return 'BOOL' elif paramnum == self.FLOAT: return 'FLOAT' elif paramnum == self.STRING: return 'STRING' elif paramnum == self.INT: return 'INT' else: return 'PARAM_ERROR' def commands_cmd(self): rstr = "" for key in self.commands: rstr += key if self.commands[key].paramtype is not self.NO_PARAM: # pdb.set_trace() rstr += ':' + self.paramtype_tostring(self.commands[key].paramtype) rstr += ";" return rstr def <|fim_middle|>(self, specific_status=''): str = '' if len(specific_status) > 0: str = self.status[specific_status] else: for st in self.status: str += st + ',' + self.status[st]() + ';' return str[:self.MSGLEN-1] # Some debugging methods def debug_cmds(self): print("Commands: " + str(self.commands)) print("Statuses: " + str(self.status))<|fim▁end|>
status_cmd
<|file_name|>hazc_device.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3 from zeroconf import Zeroconf, ServiceInfo import socket import configparser from . import hazc_cmd # import pdb class hazc_device: #Forward constants NO_PARAM = hazc_cmd.NO_PARAM BOOL = hazc_cmd.BOOL FLOAT = hazc_cmd.FLOAT STRING = hazc_cmd.STRING INT = hazc_cmd.INT global running running = False def __init__(self, ipaddr): self.version = "0.1" self.config = configparser.ConfigParser() self.config.read('config.ini') self.MSGLEN = 1024 self.END_OF_MSG = '*' self.ip = ipaddr self.buffer = 20 # self.commands = {'version?':self.version_cmd,'commands?':self.commands_cmd,'status?':self.status_cmd} hcvc = hazc_cmd.hazc_cmd('version?', self.version_cmd, self.NO_PARAM) hccc = hazc_cmd.hazc_cmd('commands?', self.commands_cmd, self.NO_PARAM) hcsc = hazc_cmd.hazc_cmd('status?', self.status_cmd, self.STRING) self.commands = {'version': hcvc, 'commands': hccc, 'status': hcsc} # probably want to add a debug log status self.status = {'exec_status': self.exec_status} #Adds a function - not as preferred as addControl #Does NOT auto add status def addFunction(self, name, handler, paramtype): # pdb.settrace() #log("This is not the preferred way to add controls, see addControl") if not('?' in name or '!' in name): # log("Function name requires a '?' or '!', assuming '!'") name += '!' self.commands[name] = hazc_cmd.hazc_cmd(name, handler, paramtype) #Adds a control vector #controlname should just be a name like 'temp' or 'position' - it'll be the same for the status def addControl(self, controlname, handler, statushandler, paramtype=NO_PARAM): cmd_name = 'set-'+controlname self.commands[cmd_name] = hazc_cmd.hazc_cmd(cmd_name+'?', handler, paramtype) self.addStatus(controlname, statushandler) #adds a unique status not already included in control vector. name is just the name, as in 'temp' def addStatus(self, name, handler): self.status[name] = handler def advertise(self): postfix = self.config['global']['service_prefix'] self.port = int(self.config['global']['port']) #print(self.config['device']['hostname']+postfix) info = ServiceInfo(postfix, self.config['device']['hostname']+"."+postfix, socket.inet_aton(self.ip), self.port, 0, 0, {'info': self.config['device']['description']}, "hazc.local.") self.bindConnection() zeroconf = Zeroconf() zeroconf.register_service(info) try: while True: # try: print("Ready") self.conn, self.addr = self.webcontrol.accept() self.listen() self.conn.close() except KeyboardInterrupt: pass finally: print() print("Unregistering...") zeroconf.unregister_service(info) zeroconf.close() try: print("Shutting down socket") self.webcontrol.shutdown(socket.SHUT_RDWR) except Exception as e: print(e) def listen(self): data = bytes() rbytes = 0 while rbytes < self.MSGLEN: d = self.conn.recv(self.buffer) if not d: break data += d rbytes += len(d) # print data.decode('utf-8') self.handledata(data) def handledata(self, data): command, param = self.cleanandstringdata(data) print('->' + command + ';' + param) # replystr = "ERROR" try: replystr = self.commands[command].execute(param) except KeyError: if(command==''): command = "(empty string)" print("ERROR! Unknown command: " + command) replystr = "" # replystr = self.commands['version'].execute('') if(replystr == None): print("WARNING! " + command + " should return a string to send to the master. Sending 'NO_REPLY'") replystr = 'NO_REPLY' print(replystr) self.reply(replystr) def reply(self, msg): longmsg = msg while len(longmsg) < self.MSGLEN: longmsg += self.END_OF_MSG # print(longmsg) self.conn.send(longmsg.encode('utf-8')) def cleanandstringdata(self, data): dstr = data.decode('utf-8') full = dstr.strip(self.END_OF_MSG) if '?' in full: li = full.split('?') param = li[-1] cmd = li[0] elif '!' in full: li = full.split('!') param = li[-1] cmd = li[0] else: param = '' cmd = full return (cmd, param) def bindConnection(self): try: self.webcontrol = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.webcontrol.bind((self.ip, self.port)) self.webcontrol.listen(1) except OSError as e: print(e) quit() def exec_status(self): return "Running" def version_cmd(self): return self.version def paramtype_tostring(self, paramnum): if paramnum == self.BOOL: return 'BOOL' elif paramnum == self.FLOAT: return 'FLOAT' elif paramnum == self.STRING: return 'STRING' elif paramnum == self.INT: return 'INT' else: return 'PARAM_ERROR' def commands_cmd(self): rstr = "" for key in self.commands: rstr += key if self.commands[key].paramtype is not self.NO_PARAM: # pdb.set_trace() rstr += ':' + self.paramtype_tostring(self.commands[key].paramtype) rstr += ";" return rstr def status_cmd(self, specific_status=''): str = '' if len(specific_status) > 0: str = self.status[specific_status] else: for st in self.status: str += st + ',' + self.status[st]() + ';' return str[:self.MSGLEN-1] # Some debugging methods def <|fim_middle|>(self): print("Commands: " + str(self.commands)) print("Statuses: " + str(self.status))<|fim▁end|>
debug_cmds
<|file_name|>npx.py<|end_file_name|><|fim▁begin|><|fim▁hole|> if __name__ == "__main__": setup(skip_dependencies=True) nodeenv_delegate("npx")<|fim▁end|>
#!/usr/bin/env python from util import nodeenv_delegate from setup import setup
<|file_name|>npx.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python from util import nodeenv_delegate from setup import setup if __name__ == "__main__": <|fim_middle|> <|fim▁end|>
setup(skip_dependencies=True) nodeenv_delegate("npx")
<|file_name|>asignaturas_actuales.py<|end_file_name|><|fim▁begin|>import time t1=.3 t2=.1 path="~/Dropbox/Ingenieria/asignaturas_actuales" time.sleep(t2) keyboard.send_key("<f6>") time.sleep(t2) keyboard.send_keys(path) time.sleep(t1)<|fim▁hole|><|fim▁end|>
keyboard.send_key("<enter>")
<|file_name|>wsgi.py<|end_file_name|><|fim▁begin|>""" WSGI config for brp project. It exposes the WSGI callable as a module-level variable named ``application``.<|fim▁hole|>https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ """ import os from dj_static import Cling from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "brp.settings") os.environ.setdefault('DJANGO_CONFIGURATION', 'Dev') application = Cling(get_wsgi_application())<|fim▁end|>
For more information on this file, see
<|file_name|>ndvi_difference.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2 """Example of server-side computations used in global forest change analysis. In this example we will focus on server side computation using NDVI and EVI data. This both metrics are computed bands created by third party companies or directly taken by the satellites. NDVI and EVI are two metrics used in global forest change analysis. They represent the forest concentration in a specific area. We will use the MOD13A1 vegetation indice provided by the NASA [1]. The goal is to generate an RGB image, where reds stands for deforestation, gree for reforestation and blue for masked data (e.g. rivers, oceans...). [1] https://code.earthengine.google.com/dataset/MODIS/MOD13A1 """ import ee # Initialize the Earth Engine ee.Initialize() # Small rectangle used to generate the image, over the Amazonian forest. # The location is above the Rondonia (West of Bresil). rectangle = ee.Geometry.Rectangle(-68, -7, -65, -8) # Get the MODIS dataset. collection = ee.ImageCollection('MODIS/MOD13A1') # Select the EVI, since it is more accurate on this dataset. You can also<|fim▁hole|># Get two dataset, one over the year 2000 and the other one over 2015 ndvi2000 = collection.filterDate('2000-01-01', '2000-12-31').median() ndvi2015 = collection.filterDate('2015-01-01', '2015-12-31').median() # Substract the two datasets to see the evolution between both of them. difference = ndvi2015.subtract(ndvi2000) # Use a mask to avoid showing data on rivers. # TODO(funkysayu) move this mask to blue color. classifiedImage = ee.Image('MODIS/051/MCD12Q1/2001_01_01') mask = classifiedImage.select(['Land_Cover_Type_1']) maskedDifference = difference.updateMask(mask) # Convert it to RGB image. visualized = maskedDifference.visualize( min=-2000, max=2000, palette='FF0000, 000000, 00FF00', ) # Finally generate the PNG. print visualized.getDownloadUrl({ 'region': rectangle.toGeoJSONString(), 'scale': 500, 'format': 'png', })<|fim▁end|>
# use the NDVI band here. collection = collection.select(['EVI'])
<|file_name|>TarThread.py<|end_file_name|><|fim▁begin|>import os import logging from mongodb_consistent_backup.Common import LocalCommand<|fim▁hole|> def __init__(self, backup_dir, output_file, compression='none', verbose=False, binary="tar"): super(TarThread, self).__init__(self.__class__.__name__, compression) self.compression_method = compression self.backup_dir = backup_dir self.output_file = output_file self.verbose = verbose self.binary = binary self._command = None def close(self, exit_code=None, frame=None): if self._command and not self.stopped: logging.debug("Stopping running tar command: %s" % self._command.command) del exit_code del frame self._command.close() self.stopped = True def run(self): if os.path.isdir(self.backup_dir): if not os.path.isfile(self.output_file): try: backup_base_dir = os.path.dirname(self.backup_dir) backup_base_name = os.path.basename(self.backup_dir) log_msg = "Archiving directory: %s" % self.backup_dir cmd_flags = ["-C", backup_base_dir, "-c", "-f", self.output_file, "--remove-files"] if self.do_gzip(): log_msg = "Archiving and compressing directory: %s" % self.backup_dir cmd_flags.append("-z") cmd_flags.append(backup_base_name) logging.info(log_msg) self.running = True self._command = LocalCommand(self.binary, cmd_flags, self.verbose) self.exit_code = self._command.run() except Exception, e: return self.result(False, "Failed archiving file: %s!" % self.output_file, e) finally: self.running = False self.stopped = True self.completed = True else: return self.result(False, "Output file: %s already exists!" % self.output_file, None) return self.result(True, "Archiving successful.", None) def result(self, success, message, error): return { "success": success, "message": message, "error": error, "directory": self.backup_dir, "exit_code": self.exit_code }<|fim▁end|>
from mongodb_consistent_backup.Pipeline import PoolThread class TarThread(PoolThread):
<|file_name|>TarThread.py<|end_file_name|><|fim▁begin|>import os import logging from mongodb_consistent_backup.Common import LocalCommand from mongodb_consistent_backup.Pipeline import PoolThread class TarThread(PoolThread): <|fim_middle|> <|fim▁end|>
def __init__(self, backup_dir, output_file, compression='none', verbose=False, binary="tar"): super(TarThread, self).__init__(self.__class__.__name__, compression) self.compression_method = compression self.backup_dir = backup_dir self.output_file = output_file self.verbose = verbose self.binary = binary self._command = None def close(self, exit_code=None, frame=None): if self._command and not self.stopped: logging.debug("Stopping running tar command: %s" % self._command.command) del exit_code del frame self._command.close() self.stopped = True def run(self): if os.path.isdir(self.backup_dir): if not os.path.isfile(self.output_file): try: backup_base_dir = os.path.dirname(self.backup_dir) backup_base_name = os.path.basename(self.backup_dir) log_msg = "Archiving directory: %s" % self.backup_dir cmd_flags = ["-C", backup_base_dir, "-c", "-f", self.output_file, "--remove-files"] if self.do_gzip(): log_msg = "Archiving and compressing directory: %s" % self.backup_dir cmd_flags.append("-z") cmd_flags.append(backup_base_name) logging.info(log_msg) self.running = True self._command = LocalCommand(self.binary, cmd_flags, self.verbose) self.exit_code = self._command.run() except Exception, e: return self.result(False, "Failed archiving file: %s!" % self.output_file, e) finally: self.running = False self.stopped = True self.completed = True else: return self.result(False, "Output file: %s already exists!" % self.output_file, None) return self.result(True, "Archiving successful.", None) def result(self, success, message, error): return { "success": success, "message": message, "error": error, "directory": self.backup_dir, "exit_code": self.exit_code }
<|file_name|>TarThread.py<|end_file_name|><|fim▁begin|>import os import logging from mongodb_consistent_backup.Common import LocalCommand from mongodb_consistent_backup.Pipeline import PoolThread class TarThread(PoolThread): def __init__(self, backup_dir, output_file, compression='none', verbose=False, binary="tar"): <|fim_middle|> def close(self, exit_code=None, frame=None): if self._command and not self.stopped: logging.debug("Stopping running tar command: %s" % self._command.command) del exit_code del frame self._command.close() self.stopped = True def run(self): if os.path.isdir(self.backup_dir): if not os.path.isfile(self.output_file): try: backup_base_dir = os.path.dirname(self.backup_dir) backup_base_name = os.path.basename(self.backup_dir) log_msg = "Archiving directory: %s" % self.backup_dir cmd_flags = ["-C", backup_base_dir, "-c", "-f", self.output_file, "--remove-files"] if self.do_gzip(): log_msg = "Archiving and compressing directory: %s" % self.backup_dir cmd_flags.append("-z") cmd_flags.append(backup_base_name) logging.info(log_msg) self.running = True self._command = LocalCommand(self.binary, cmd_flags, self.verbose) self.exit_code = self._command.run() except Exception, e: return self.result(False, "Failed archiving file: %s!" % self.output_file, e) finally: self.running = False self.stopped = True self.completed = True else: return self.result(False, "Output file: %s already exists!" % self.output_file, None) return self.result(True, "Archiving successful.", None) def result(self, success, message, error): return { "success": success, "message": message, "error": error, "directory": self.backup_dir, "exit_code": self.exit_code } <|fim▁end|>
super(TarThread, self).__init__(self.__class__.__name__, compression) self.compression_method = compression self.backup_dir = backup_dir self.output_file = output_file self.verbose = verbose self.binary = binary self._command = None
<|file_name|>TarThread.py<|end_file_name|><|fim▁begin|>import os import logging from mongodb_consistent_backup.Common import LocalCommand from mongodb_consistent_backup.Pipeline import PoolThread class TarThread(PoolThread): def __init__(self, backup_dir, output_file, compression='none', verbose=False, binary="tar"): super(TarThread, self).__init__(self.__class__.__name__, compression) self.compression_method = compression self.backup_dir = backup_dir self.output_file = output_file self.verbose = verbose self.binary = binary self._command = None def close(self, exit_code=None, frame=None): <|fim_middle|> def run(self): if os.path.isdir(self.backup_dir): if not os.path.isfile(self.output_file): try: backup_base_dir = os.path.dirname(self.backup_dir) backup_base_name = os.path.basename(self.backup_dir) log_msg = "Archiving directory: %s" % self.backup_dir cmd_flags = ["-C", backup_base_dir, "-c", "-f", self.output_file, "--remove-files"] if self.do_gzip(): log_msg = "Archiving and compressing directory: %s" % self.backup_dir cmd_flags.append("-z") cmd_flags.append(backup_base_name) logging.info(log_msg) self.running = True self._command = LocalCommand(self.binary, cmd_flags, self.verbose) self.exit_code = self._command.run() except Exception, e: return self.result(False, "Failed archiving file: %s!" % self.output_file, e) finally: self.running = False self.stopped = True self.completed = True else: return self.result(False, "Output file: %s already exists!" % self.output_file, None) return self.result(True, "Archiving successful.", None) def result(self, success, message, error): return { "success": success, "message": message, "error": error, "directory": self.backup_dir, "exit_code": self.exit_code } <|fim▁end|>
if self._command and not self.stopped: logging.debug("Stopping running tar command: %s" % self._command.command) del exit_code del frame self._command.close() self.stopped = True
<|file_name|>TarThread.py<|end_file_name|><|fim▁begin|>import os import logging from mongodb_consistent_backup.Common import LocalCommand from mongodb_consistent_backup.Pipeline import PoolThread class TarThread(PoolThread): def __init__(self, backup_dir, output_file, compression='none', verbose=False, binary="tar"): super(TarThread, self).__init__(self.__class__.__name__, compression) self.compression_method = compression self.backup_dir = backup_dir self.output_file = output_file self.verbose = verbose self.binary = binary self._command = None def close(self, exit_code=None, frame=None): if self._command and not self.stopped: logging.debug("Stopping running tar command: %s" % self._command.command) del exit_code del frame self._command.close() self.stopped = True def run(self): <|fim_middle|> def result(self, success, message, error): return { "success": success, "message": message, "error": error, "directory": self.backup_dir, "exit_code": self.exit_code } <|fim▁end|>
if os.path.isdir(self.backup_dir): if not os.path.isfile(self.output_file): try: backup_base_dir = os.path.dirname(self.backup_dir) backup_base_name = os.path.basename(self.backup_dir) log_msg = "Archiving directory: %s" % self.backup_dir cmd_flags = ["-C", backup_base_dir, "-c", "-f", self.output_file, "--remove-files"] if self.do_gzip(): log_msg = "Archiving and compressing directory: %s" % self.backup_dir cmd_flags.append("-z") cmd_flags.append(backup_base_name) logging.info(log_msg) self.running = True self._command = LocalCommand(self.binary, cmd_flags, self.verbose) self.exit_code = self._command.run() except Exception, e: return self.result(False, "Failed archiving file: %s!" % self.output_file, e) finally: self.running = False self.stopped = True self.completed = True else: return self.result(False, "Output file: %s already exists!" % self.output_file, None) return self.result(True, "Archiving successful.", None)
<|file_name|>TarThread.py<|end_file_name|><|fim▁begin|>import os import logging from mongodb_consistent_backup.Common import LocalCommand from mongodb_consistent_backup.Pipeline import PoolThread class TarThread(PoolThread): def __init__(self, backup_dir, output_file, compression='none', verbose=False, binary="tar"): super(TarThread, self).__init__(self.__class__.__name__, compression) self.compression_method = compression self.backup_dir = backup_dir self.output_file = output_file self.verbose = verbose self.binary = binary self._command = None def close(self, exit_code=None, frame=None): if self._command and not self.stopped: logging.debug("Stopping running tar command: %s" % self._command.command) del exit_code del frame self._command.close() self.stopped = True def run(self): if os.path.isdir(self.backup_dir): if not os.path.isfile(self.output_file): try: backup_base_dir = os.path.dirname(self.backup_dir) backup_base_name = os.path.basename(self.backup_dir) log_msg = "Archiving directory: %s" % self.backup_dir cmd_flags = ["-C", backup_base_dir, "-c", "-f", self.output_file, "--remove-files"] if self.do_gzip(): log_msg = "Archiving and compressing directory: %s" % self.backup_dir cmd_flags.append("-z") cmd_flags.append(backup_base_name) logging.info(log_msg) self.running = True self._command = LocalCommand(self.binary, cmd_flags, self.verbose) self.exit_code = self._command.run() except Exception, e: return self.result(False, "Failed archiving file: %s!" % self.output_file, e) finally: self.running = False self.stopped = True self.completed = True else: return self.result(False, "Output file: %s already exists!" % self.output_file, None) return self.result(True, "Archiving successful.", None) def result(self, success, message, error): <|fim_middle|> <|fim▁end|>
return { "success": success, "message": message, "error": error, "directory": self.backup_dir, "exit_code": self.exit_code }
<|file_name|>TarThread.py<|end_file_name|><|fim▁begin|>import os import logging from mongodb_consistent_backup.Common import LocalCommand from mongodb_consistent_backup.Pipeline import PoolThread class TarThread(PoolThread): def __init__(self, backup_dir, output_file, compression='none', verbose=False, binary="tar"): super(TarThread, self).__init__(self.__class__.__name__, compression) self.compression_method = compression self.backup_dir = backup_dir self.output_file = output_file self.verbose = verbose self.binary = binary self._command = None def close(self, exit_code=None, frame=None): if self._command and not self.stopped: <|fim_middle|> def run(self): if os.path.isdir(self.backup_dir): if not os.path.isfile(self.output_file): try: backup_base_dir = os.path.dirname(self.backup_dir) backup_base_name = os.path.basename(self.backup_dir) log_msg = "Archiving directory: %s" % self.backup_dir cmd_flags = ["-C", backup_base_dir, "-c", "-f", self.output_file, "--remove-files"] if self.do_gzip(): log_msg = "Archiving and compressing directory: %s" % self.backup_dir cmd_flags.append("-z") cmd_flags.append(backup_base_name) logging.info(log_msg) self.running = True self._command = LocalCommand(self.binary, cmd_flags, self.verbose) self.exit_code = self._command.run() except Exception, e: return self.result(False, "Failed archiving file: %s!" % self.output_file, e) finally: self.running = False self.stopped = True self.completed = True else: return self.result(False, "Output file: %s already exists!" % self.output_file, None) return self.result(True, "Archiving successful.", None) def result(self, success, message, error): return { "success": success, "message": message, "error": error, "directory": self.backup_dir, "exit_code": self.exit_code } <|fim▁end|>
logging.debug("Stopping running tar command: %s" % self._command.command) del exit_code del frame self._command.close() self.stopped = True
<|file_name|>TarThread.py<|end_file_name|><|fim▁begin|>import os import logging from mongodb_consistent_backup.Common import LocalCommand from mongodb_consistent_backup.Pipeline import PoolThread class TarThread(PoolThread): def __init__(self, backup_dir, output_file, compression='none', verbose=False, binary="tar"): super(TarThread, self).__init__(self.__class__.__name__, compression) self.compression_method = compression self.backup_dir = backup_dir self.output_file = output_file self.verbose = verbose self.binary = binary self._command = None def close(self, exit_code=None, frame=None): if self._command and not self.stopped: logging.debug("Stopping running tar command: %s" % self._command.command) del exit_code del frame self._command.close() self.stopped = True def run(self): if os.path.isdir(self.backup_dir): <|fim_middle|> def result(self, success, message, error): return { "success": success, "message": message, "error": error, "directory": self.backup_dir, "exit_code": self.exit_code } <|fim▁end|>
if not os.path.isfile(self.output_file): try: backup_base_dir = os.path.dirname(self.backup_dir) backup_base_name = os.path.basename(self.backup_dir) log_msg = "Archiving directory: %s" % self.backup_dir cmd_flags = ["-C", backup_base_dir, "-c", "-f", self.output_file, "--remove-files"] if self.do_gzip(): log_msg = "Archiving and compressing directory: %s" % self.backup_dir cmd_flags.append("-z") cmd_flags.append(backup_base_name) logging.info(log_msg) self.running = True self._command = LocalCommand(self.binary, cmd_flags, self.verbose) self.exit_code = self._command.run() except Exception, e: return self.result(False, "Failed archiving file: %s!" % self.output_file, e) finally: self.running = False self.stopped = True self.completed = True else: return self.result(False, "Output file: %s already exists!" % self.output_file, None) return self.result(True, "Archiving successful.", None)
<|file_name|>TarThread.py<|end_file_name|><|fim▁begin|>import os import logging from mongodb_consistent_backup.Common import LocalCommand from mongodb_consistent_backup.Pipeline import PoolThread class TarThread(PoolThread): def __init__(self, backup_dir, output_file, compression='none', verbose=False, binary="tar"): super(TarThread, self).__init__(self.__class__.__name__, compression) self.compression_method = compression self.backup_dir = backup_dir self.output_file = output_file self.verbose = verbose self.binary = binary self._command = None def close(self, exit_code=None, frame=None): if self._command and not self.stopped: logging.debug("Stopping running tar command: %s" % self._command.command) del exit_code del frame self._command.close() self.stopped = True def run(self): if os.path.isdir(self.backup_dir): if not os.path.isfile(self.output_file): <|fim_middle|> else: return self.result(False, "Output file: %s already exists!" % self.output_file, None) return self.result(True, "Archiving successful.", None) def result(self, success, message, error): return { "success": success, "message": message, "error": error, "directory": self.backup_dir, "exit_code": self.exit_code } <|fim▁end|>
try: backup_base_dir = os.path.dirname(self.backup_dir) backup_base_name = os.path.basename(self.backup_dir) log_msg = "Archiving directory: %s" % self.backup_dir cmd_flags = ["-C", backup_base_dir, "-c", "-f", self.output_file, "--remove-files"] if self.do_gzip(): log_msg = "Archiving and compressing directory: %s" % self.backup_dir cmd_flags.append("-z") cmd_flags.append(backup_base_name) logging.info(log_msg) self.running = True self._command = LocalCommand(self.binary, cmd_flags, self.verbose) self.exit_code = self._command.run() except Exception, e: return self.result(False, "Failed archiving file: %s!" % self.output_file, e) finally: self.running = False self.stopped = True self.completed = True
<|file_name|>TarThread.py<|end_file_name|><|fim▁begin|>import os import logging from mongodb_consistent_backup.Common import LocalCommand from mongodb_consistent_backup.Pipeline import PoolThread class TarThread(PoolThread): def __init__(self, backup_dir, output_file, compression='none', verbose=False, binary="tar"): super(TarThread, self).__init__(self.__class__.__name__, compression) self.compression_method = compression self.backup_dir = backup_dir self.output_file = output_file self.verbose = verbose self.binary = binary self._command = None def close(self, exit_code=None, frame=None): if self._command and not self.stopped: logging.debug("Stopping running tar command: %s" % self._command.command) del exit_code del frame self._command.close() self.stopped = True def run(self): if os.path.isdir(self.backup_dir): if not os.path.isfile(self.output_file): try: backup_base_dir = os.path.dirname(self.backup_dir) backup_base_name = os.path.basename(self.backup_dir) log_msg = "Archiving directory: %s" % self.backup_dir cmd_flags = ["-C", backup_base_dir, "-c", "-f", self.output_file, "--remove-files"] if self.do_gzip(): <|fim_middle|> cmd_flags.append(backup_base_name) logging.info(log_msg) self.running = True self._command = LocalCommand(self.binary, cmd_flags, self.verbose) self.exit_code = self._command.run() except Exception, e: return self.result(False, "Failed archiving file: %s!" % self.output_file, e) finally: self.running = False self.stopped = True self.completed = True else: return self.result(False, "Output file: %s already exists!" % self.output_file, None) return self.result(True, "Archiving successful.", None) def result(self, success, message, error): return { "success": success, "message": message, "error": error, "directory": self.backup_dir, "exit_code": self.exit_code } <|fim▁end|>
log_msg = "Archiving and compressing directory: %s" % self.backup_dir cmd_flags.append("-z")
<|file_name|>TarThread.py<|end_file_name|><|fim▁begin|>import os import logging from mongodb_consistent_backup.Common import LocalCommand from mongodb_consistent_backup.Pipeline import PoolThread class TarThread(PoolThread): def __init__(self, backup_dir, output_file, compression='none', verbose=False, binary="tar"): super(TarThread, self).__init__(self.__class__.__name__, compression) self.compression_method = compression self.backup_dir = backup_dir self.output_file = output_file self.verbose = verbose self.binary = binary self._command = None def close(self, exit_code=None, frame=None): if self._command and not self.stopped: logging.debug("Stopping running tar command: %s" % self._command.command) del exit_code del frame self._command.close() self.stopped = True def run(self): if os.path.isdir(self.backup_dir): if not os.path.isfile(self.output_file): try: backup_base_dir = os.path.dirname(self.backup_dir) backup_base_name = os.path.basename(self.backup_dir) log_msg = "Archiving directory: %s" % self.backup_dir cmd_flags = ["-C", backup_base_dir, "-c", "-f", self.output_file, "--remove-files"] if self.do_gzip(): log_msg = "Archiving and compressing directory: %s" % self.backup_dir cmd_flags.append("-z") cmd_flags.append(backup_base_name) logging.info(log_msg) self.running = True self._command = LocalCommand(self.binary, cmd_flags, self.verbose) self.exit_code = self._command.run() except Exception, e: return self.result(False, "Failed archiving file: %s!" % self.output_file, e) finally: self.running = False self.stopped = True self.completed = True else: <|fim_middle|> return self.result(True, "Archiving successful.", None) def result(self, success, message, error): return { "success": success, "message": message, "error": error, "directory": self.backup_dir, "exit_code": self.exit_code } <|fim▁end|>
return self.result(False, "Output file: %s already exists!" % self.output_file, None)
<|file_name|>TarThread.py<|end_file_name|><|fim▁begin|>import os import logging from mongodb_consistent_backup.Common import LocalCommand from mongodb_consistent_backup.Pipeline import PoolThread class TarThread(PoolThread): def <|fim_middle|>(self, backup_dir, output_file, compression='none', verbose=False, binary="tar"): super(TarThread, self).__init__(self.__class__.__name__, compression) self.compression_method = compression self.backup_dir = backup_dir self.output_file = output_file self.verbose = verbose self.binary = binary self._command = None def close(self, exit_code=None, frame=None): if self._command and not self.stopped: logging.debug("Stopping running tar command: %s" % self._command.command) del exit_code del frame self._command.close() self.stopped = True def run(self): if os.path.isdir(self.backup_dir): if not os.path.isfile(self.output_file): try: backup_base_dir = os.path.dirname(self.backup_dir) backup_base_name = os.path.basename(self.backup_dir) log_msg = "Archiving directory: %s" % self.backup_dir cmd_flags = ["-C", backup_base_dir, "-c", "-f", self.output_file, "--remove-files"] if self.do_gzip(): log_msg = "Archiving and compressing directory: %s" % self.backup_dir cmd_flags.append("-z") cmd_flags.append(backup_base_name) logging.info(log_msg) self.running = True self._command = LocalCommand(self.binary, cmd_flags, self.verbose) self.exit_code = self._command.run() except Exception, e: return self.result(False, "Failed archiving file: %s!" % self.output_file, e) finally: self.running = False self.stopped = True self.completed = True else: return self.result(False, "Output file: %s already exists!" % self.output_file, None) return self.result(True, "Archiving successful.", None) def result(self, success, message, error): return { "success": success, "message": message, "error": error, "directory": self.backup_dir, "exit_code": self.exit_code } <|fim▁end|>
__init__
<|file_name|>TarThread.py<|end_file_name|><|fim▁begin|>import os import logging from mongodb_consistent_backup.Common import LocalCommand from mongodb_consistent_backup.Pipeline import PoolThread class TarThread(PoolThread): def __init__(self, backup_dir, output_file, compression='none', verbose=False, binary="tar"): super(TarThread, self).__init__(self.__class__.__name__, compression) self.compression_method = compression self.backup_dir = backup_dir self.output_file = output_file self.verbose = verbose self.binary = binary self._command = None def <|fim_middle|>(self, exit_code=None, frame=None): if self._command and not self.stopped: logging.debug("Stopping running tar command: %s" % self._command.command) del exit_code del frame self._command.close() self.stopped = True def run(self): if os.path.isdir(self.backup_dir): if not os.path.isfile(self.output_file): try: backup_base_dir = os.path.dirname(self.backup_dir) backup_base_name = os.path.basename(self.backup_dir) log_msg = "Archiving directory: %s" % self.backup_dir cmd_flags = ["-C", backup_base_dir, "-c", "-f", self.output_file, "--remove-files"] if self.do_gzip(): log_msg = "Archiving and compressing directory: %s" % self.backup_dir cmd_flags.append("-z") cmd_flags.append(backup_base_name) logging.info(log_msg) self.running = True self._command = LocalCommand(self.binary, cmd_flags, self.verbose) self.exit_code = self._command.run() except Exception, e: return self.result(False, "Failed archiving file: %s!" % self.output_file, e) finally: self.running = False self.stopped = True self.completed = True else: return self.result(False, "Output file: %s already exists!" % self.output_file, None) return self.result(True, "Archiving successful.", None) def result(self, success, message, error): return { "success": success, "message": message, "error": error, "directory": self.backup_dir, "exit_code": self.exit_code } <|fim▁end|>
close
<|file_name|>TarThread.py<|end_file_name|><|fim▁begin|>import os import logging from mongodb_consistent_backup.Common import LocalCommand from mongodb_consistent_backup.Pipeline import PoolThread class TarThread(PoolThread): def __init__(self, backup_dir, output_file, compression='none', verbose=False, binary="tar"): super(TarThread, self).__init__(self.__class__.__name__, compression) self.compression_method = compression self.backup_dir = backup_dir self.output_file = output_file self.verbose = verbose self.binary = binary self._command = None def close(self, exit_code=None, frame=None): if self._command and not self.stopped: logging.debug("Stopping running tar command: %s" % self._command.command) del exit_code del frame self._command.close() self.stopped = True def <|fim_middle|>(self): if os.path.isdir(self.backup_dir): if not os.path.isfile(self.output_file): try: backup_base_dir = os.path.dirname(self.backup_dir) backup_base_name = os.path.basename(self.backup_dir) log_msg = "Archiving directory: %s" % self.backup_dir cmd_flags = ["-C", backup_base_dir, "-c", "-f", self.output_file, "--remove-files"] if self.do_gzip(): log_msg = "Archiving and compressing directory: %s" % self.backup_dir cmd_flags.append("-z") cmd_flags.append(backup_base_name) logging.info(log_msg) self.running = True self._command = LocalCommand(self.binary, cmd_flags, self.verbose) self.exit_code = self._command.run() except Exception, e: return self.result(False, "Failed archiving file: %s!" % self.output_file, e) finally: self.running = False self.stopped = True self.completed = True else: return self.result(False, "Output file: %s already exists!" % self.output_file, None) return self.result(True, "Archiving successful.", None) def result(self, success, message, error): return { "success": success, "message": message, "error": error, "directory": self.backup_dir, "exit_code": self.exit_code } <|fim▁end|>
run
<|file_name|>TarThread.py<|end_file_name|><|fim▁begin|>import os import logging from mongodb_consistent_backup.Common import LocalCommand from mongodb_consistent_backup.Pipeline import PoolThread class TarThread(PoolThread): def __init__(self, backup_dir, output_file, compression='none', verbose=False, binary="tar"): super(TarThread, self).__init__(self.__class__.__name__, compression) self.compression_method = compression self.backup_dir = backup_dir self.output_file = output_file self.verbose = verbose self.binary = binary self._command = None def close(self, exit_code=None, frame=None): if self._command and not self.stopped: logging.debug("Stopping running tar command: %s" % self._command.command) del exit_code del frame self._command.close() self.stopped = True def run(self): if os.path.isdir(self.backup_dir): if not os.path.isfile(self.output_file): try: backup_base_dir = os.path.dirname(self.backup_dir) backup_base_name = os.path.basename(self.backup_dir) log_msg = "Archiving directory: %s" % self.backup_dir cmd_flags = ["-C", backup_base_dir, "-c", "-f", self.output_file, "--remove-files"] if self.do_gzip(): log_msg = "Archiving and compressing directory: %s" % self.backup_dir cmd_flags.append("-z") cmd_flags.append(backup_base_name) logging.info(log_msg) self.running = True self._command = LocalCommand(self.binary, cmd_flags, self.verbose) self.exit_code = self._command.run() except Exception, e: return self.result(False, "Failed archiving file: %s!" % self.output_file, e) finally: self.running = False self.stopped = True self.completed = True else: return self.result(False, "Output file: %s already exists!" % self.output_file, None) return self.result(True, "Archiving successful.", None) def <|fim_middle|>(self, success, message, error): return { "success": success, "message": message, "error": error, "directory": self.backup_dir, "exit_code": self.exit_code } <|fim▁end|>
result
<|file_name|>feature_extraction.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- ''' Description: Extract the feature from the text in English. Version: python3<|fim▁hole|>VECTORIZER = CountVectorizer(min_df=1) # 以下代码设置了特征提取方法的参数(以1-2个单词作为滑动窗口大小,以空格作为单词的分割点,最小词频为1) # 详细参考API介绍: # http://scikit-learn.org/stable/modules/feature_extraction.html#text-feature-extraction # VECTORIZER = CountVectorizer(ngram_range=(1,2), token_pattern=r'\b\w+\b', min_df=1) CORPUS = [ 'This is the first document.', 'This is the second second document.', 'And the third one.', 'Is this the first document?' ] X = VECTORIZER.fit_transform(CORPUS) FEATURE_NAMES = VECTORIZER.get_feature_names() print(FEATURE_NAMES)<|fim▁end|>
''' from sklearn.feature_extraction.text import CountVectorizer
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- encoding: utf-8 -*- #<|fim▁hole|># GNU GPLv3 <https://www.gnu.org/licenses/gpl-3.0.en.html> from ._common import * from .rethinkdb import RethinkDBPipe from .mongodb import MongoDBPipe<|fim▁end|>
# Copyright (c) 2017 Stephen Bunn ([email protected])
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>from django.conf import settings from django.conf.urls import static from django.urls import include, path, re_path from django.contrib import admin urlpatterns = [ path(r"admin/", admin.site.urls), path(r"flickr/", include("ditto.flickr.urls")), path(r"lastfm/", include("ditto.lastfm.urls")),<|fim▁hole|> path(r"twitter/", include("ditto.twitter.urls")), path(r"", include("ditto.core.urls")), ] if settings.DEBUG: import debug_toolbar urlpatterns += [ re_path(r"^__debug__/", include(debug_toolbar.urls)), ] urlpatterns += static.static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static.static( settings.STATIC_URL, document_root=settings.STATIC_ROOT )<|fim▁end|>
path(r"pinboard/", include("ditto.pinboard.urls")),
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>from django.conf import settings from django.conf.urls import static from django.urls import include, path, re_path from django.contrib import admin urlpatterns = [ path(r"admin/", admin.site.urls), path(r"flickr/", include("ditto.flickr.urls")), path(r"lastfm/", include("ditto.lastfm.urls")), path(r"pinboard/", include("ditto.pinboard.urls")), path(r"twitter/", include("ditto.twitter.urls")), path(r"", include("ditto.core.urls")), ] if settings.DEBUG: <|fim_middle|> <|fim▁end|>
import debug_toolbar urlpatterns += [ re_path(r"^__debug__/", include(debug_toolbar.urls)), ] urlpatterns += static.static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static.static( settings.STATIC_URL, document_root=settings.STATIC_ROOT )
<|file_name|>Client.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # ********************************************************************** # # Copyright (c) 2003-2011 ZeroC, Inc. All rights reserved. # # This copy of Ice is licensed to you under the terms described in the # ICE_LICENSE file included in this distribution. # # ********************************************************************** import os, sys, traceback import Ice, AllTests def test(b): if not b: raise RuntimeError('test assertion failed') def usage(n): sys.stderr.write("Usage: " + n + " port...\n") def run(args, communicator): ports = [] for arg in args[1:]: if arg[0] == '-': sys.stderr.write(args[0] + ": unknown option `" + arg + "'\n") usage(args[0]) return False ports.append(int(arg)) if len(ports) == 0:<|fim▁hole|> try: AllTests.allTests(communicator, ports) except: traceback.print_exc() test(False) return True try: initData = Ice.InitializationData() initData.properties = Ice.createProperties(sys.argv) # # This test aborts servers, so we don't want warnings. # initData.properties.setProperty('Ice.Warn.Connections', '0') communicator = Ice.initialize(sys.argv, initData) status = run(sys.argv, communicator) except: traceback.print_exc() status = False if communicator: try: communicator.destroy() except: traceback.print_exc() status = False sys.exit(not status)<|fim▁end|>
sys.stderr.write(args[0] + ": no ports specified\n") usage(args[0]) return False
<|file_name|>Client.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # ********************************************************************** # # Copyright (c) 2003-2011 ZeroC, Inc. All rights reserved. # # This copy of Ice is licensed to you under the terms described in the # ICE_LICENSE file included in this distribution. # # ********************************************************************** import os, sys, traceback import Ice, AllTests def test(b): <|fim_middle|> def usage(n): sys.stderr.write("Usage: " + n + " port...\n") def run(args, communicator): ports = [] for arg in args[1:]: if arg[0] == '-': sys.stderr.write(args[0] + ": unknown option `" + arg + "'\n") usage(args[0]) return False ports.append(int(arg)) if len(ports) == 0: sys.stderr.write(args[0] + ": no ports specified\n") usage(args[0]) return False try: AllTests.allTests(communicator, ports) except: traceback.print_exc() test(False) return True try: initData = Ice.InitializationData() initData.properties = Ice.createProperties(sys.argv) # # This test aborts servers, so we don't want warnings. # initData.properties.setProperty('Ice.Warn.Connections', '0') communicator = Ice.initialize(sys.argv, initData) status = run(sys.argv, communicator) except: traceback.print_exc() status = False if communicator: try: communicator.destroy() except: traceback.print_exc() status = False sys.exit(not status) <|fim▁end|>
if not b: raise RuntimeError('test assertion failed')
<|file_name|>Client.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # ********************************************************************** # # Copyright (c) 2003-2011 ZeroC, Inc. All rights reserved. # # This copy of Ice is licensed to you under the terms described in the # ICE_LICENSE file included in this distribution. # # ********************************************************************** import os, sys, traceback import Ice, AllTests def test(b): if not b: raise RuntimeError('test assertion failed') def usage(n): <|fim_middle|> def run(args, communicator): ports = [] for arg in args[1:]: if arg[0] == '-': sys.stderr.write(args[0] + ": unknown option `" + arg + "'\n") usage(args[0]) return False ports.append(int(arg)) if len(ports) == 0: sys.stderr.write(args[0] + ": no ports specified\n") usage(args[0]) return False try: AllTests.allTests(communicator, ports) except: traceback.print_exc() test(False) return True try: initData = Ice.InitializationData() initData.properties = Ice.createProperties(sys.argv) # # This test aborts servers, so we don't want warnings. # initData.properties.setProperty('Ice.Warn.Connections', '0') communicator = Ice.initialize(sys.argv, initData) status = run(sys.argv, communicator) except: traceback.print_exc() status = False if communicator: try: communicator.destroy() except: traceback.print_exc() status = False sys.exit(not status) <|fim▁end|>
sys.stderr.write("Usage: " + n + " port...\n")
<|file_name|>Client.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # ********************************************************************** # # Copyright (c) 2003-2011 ZeroC, Inc. All rights reserved. # # This copy of Ice is licensed to you under the terms described in the # ICE_LICENSE file included in this distribution. # # ********************************************************************** import os, sys, traceback import Ice, AllTests def test(b): if not b: raise RuntimeError('test assertion failed') def usage(n): sys.stderr.write("Usage: " + n + " port...\n") def run(args, communicator): <|fim_middle|> try: initData = Ice.InitializationData() initData.properties = Ice.createProperties(sys.argv) # # This test aborts servers, so we don't want warnings. # initData.properties.setProperty('Ice.Warn.Connections', '0') communicator = Ice.initialize(sys.argv, initData) status = run(sys.argv, communicator) except: traceback.print_exc() status = False if communicator: try: communicator.destroy() except: traceback.print_exc() status = False sys.exit(not status) <|fim▁end|>
ports = [] for arg in args[1:]: if arg[0] == '-': sys.stderr.write(args[0] + ": unknown option `" + arg + "'\n") usage(args[0]) return False ports.append(int(arg)) if len(ports) == 0: sys.stderr.write(args[0] + ": no ports specified\n") usage(args[0]) return False try: AllTests.allTests(communicator, ports) except: traceback.print_exc() test(False) return True
<|file_name|>Client.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # ********************************************************************** # # Copyright (c) 2003-2011 ZeroC, Inc. All rights reserved. # # This copy of Ice is licensed to you under the terms described in the # ICE_LICENSE file included in this distribution. # # ********************************************************************** import os, sys, traceback import Ice, AllTests def test(b): if not b: <|fim_middle|> def usage(n): sys.stderr.write("Usage: " + n + " port...\n") def run(args, communicator): ports = [] for arg in args[1:]: if arg[0] == '-': sys.stderr.write(args[0] + ": unknown option `" + arg + "'\n") usage(args[0]) return False ports.append(int(arg)) if len(ports) == 0: sys.stderr.write(args[0] + ": no ports specified\n") usage(args[0]) return False try: AllTests.allTests(communicator, ports) except: traceback.print_exc() test(False) return True try: initData = Ice.InitializationData() initData.properties = Ice.createProperties(sys.argv) # # This test aborts servers, so we don't want warnings. # initData.properties.setProperty('Ice.Warn.Connections', '0') communicator = Ice.initialize(sys.argv, initData) status = run(sys.argv, communicator) except: traceback.print_exc() status = False if communicator: try: communicator.destroy() except: traceback.print_exc() status = False sys.exit(not status) <|fim▁end|>
raise RuntimeError('test assertion failed')
<|file_name|>Client.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # ********************************************************************** # # Copyright (c) 2003-2011 ZeroC, Inc. All rights reserved. # # This copy of Ice is licensed to you under the terms described in the # ICE_LICENSE file included in this distribution. # # ********************************************************************** import os, sys, traceback import Ice, AllTests def test(b): if not b: raise RuntimeError('test assertion failed') def usage(n): sys.stderr.write("Usage: " + n + " port...\n") def run(args, communicator): ports = [] for arg in args[1:]: if arg[0] == '-': <|fim_middle|> ports.append(int(arg)) if len(ports) == 0: sys.stderr.write(args[0] + ": no ports specified\n") usage(args[0]) return False try: AllTests.allTests(communicator, ports) except: traceback.print_exc() test(False) return True try: initData = Ice.InitializationData() initData.properties = Ice.createProperties(sys.argv) # # This test aborts servers, so we don't want warnings. # initData.properties.setProperty('Ice.Warn.Connections', '0') communicator = Ice.initialize(sys.argv, initData) status = run(sys.argv, communicator) except: traceback.print_exc() status = False if communicator: try: communicator.destroy() except: traceback.print_exc() status = False sys.exit(not status) <|fim▁end|>
sys.stderr.write(args[0] + ": unknown option `" + arg + "'\n") usage(args[0]) return False
<|file_name|>Client.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # ********************************************************************** # # Copyright (c) 2003-2011 ZeroC, Inc. All rights reserved. # # This copy of Ice is licensed to you under the terms described in the # ICE_LICENSE file included in this distribution. # # ********************************************************************** import os, sys, traceback import Ice, AllTests def test(b): if not b: raise RuntimeError('test assertion failed') def usage(n): sys.stderr.write("Usage: " + n + " port...\n") def run(args, communicator): ports = [] for arg in args[1:]: if arg[0] == '-': sys.stderr.write(args[0] + ": unknown option `" + arg + "'\n") usage(args[0]) return False ports.append(int(arg)) if len(ports) == 0: <|fim_middle|> try: AllTests.allTests(communicator, ports) except: traceback.print_exc() test(False) return True try: initData = Ice.InitializationData() initData.properties = Ice.createProperties(sys.argv) # # This test aborts servers, so we don't want warnings. # initData.properties.setProperty('Ice.Warn.Connections', '0') communicator = Ice.initialize(sys.argv, initData) status = run(sys.argv, communicator) except: traceback.print_exc() status = False if communicator: try: communicator.destroy() except: traceback.print_exc() status = False sys.exit(not status) <|fim▁end|>
sys.stderr.write(args[0] + ": no ports specified\n") usage(args[0]) return False
<|file_name|>Client.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # ********************************************************************** # # Copyright (c) 2003-2011 ZeroC, Inc. All rights reserved. # # This copy of Ice is licensed to you under the terms described in the # ICE_LICENSE file included in this distribution. # # ********************************************************************** import os, sys, traceback import Ice, AllTests def test(b): if not b: raise RuntimeError('test assertion failed') def usage(n): sys.stderr.write("Usage: " + n + " port...\n") def run(args, communicator): ports = [] for arg in args[1:]: if arg[0] == '-': sys.stderr.write(args[0] + ": unknown option `" + arg + "'\n") usage(args[0]) return False ports.append(int(arg)) if len(ports) == 0: sys.stderr.write(args[0] + ": no ports specified\n") usage(args[0]) return False try: AllTests.allTests(communicator, ports) except: traceback.print_exc() test(False) return True try: initData = Ice.InitializationData() initData.properties = Ice.createProperties(sys.argv) # # This test aborts servers, so we don't want warnings. # initData.properties.setProperty('Ice.Warn.Connections', '0') communicator = Ice.initialize(sys.argv, initData) status = run(sys.argv, communicator) except: traceback.print_exc() status = False if communicator: <|fim_middle|> sys.exit(not status) <|fim▁end|>
try: communicator.destroy() except: traceback.print_exc() status = False
<|file_name|>Client.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # ********************************************************************** # # Copyright (c) 2003-2011 ZeroC, Inc. All rights reserved. # # This copy of Ice is licensed to you under the terms described in the # ICE_LICENSE file included in this distribution. # # ********************************************************************** import os, sys, traceback import Ice, AllTests def <|fim_middle|>(b): if not b: raise RuntimeError('test assertion failed') def usage(n): sys.stderr.write("Usage: " + n + " port...\n") def run(args, communicator): ports = [] for arg in args[1:]: if arg[0] == '-': sys.stderr.write(args[0] + ": unknown option `" + arg + "'\n") usage(args[0]) return False ports.append(int(arg)) if len(ports) == 0: sys.stderr.write(args[0] + ": no ports specified\n") usage(args[0]) return False try: AllTests.allTests(communicator, ports) except: traceback.print_exc() test(False) return True try: initData = Ice.InitializationData() initData.properties = Ice.createProperties(sys.argv) # # This test aborts servers, so we don't want warnings. # initData.properties.setProperty('Ice.Warn.Connections', '0') communicator = Ice.initialize(sys.argv, initData) status = run(sys.argv, communicator) except: traceback.print_exc() status = False if communicator: try: communicator.destroy() except: traceback.print_exc() status = False sys.exit(not status) <|fim▁end|>
test
<|file_name|>Client.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # ********************************************************************** # # Copyright (c) 2003-2011 ZeroC, Inc. All rights reserved. # # This copy of Ice is licensed to you under the terms described in the # ICE_LICENSE file included in this distribution. # # ********************************************************************** import os, sys, traceback import Ice, AllTests def test(b): if not b: raise RuntimeError('test assertion failed') def <|fim_middle|>(n): sys.stderr.write("Usage: " + n + " port...\n") def run(args, communicator): ports = [] for arg in args[1:]: if arg[0] == '-': sys.stderr.write(args[0] + ": unknown option `" + arg + "'\n") usage(args[0]) return False ports.append(int(arg)) if len(ports) == 0: sys.stderr.write(args[0] + ": no ports specified\n") usage(args[0]) return False try: AllTests.allTests(communicator, ports) except: traceback.print_exc() test(False) return True try: initData = Ice.InitializationData() initData.properties = Ice.createProperties(sys.argv) # # This test aborts servers, so we don't want warnings. # initData.properties.setProperty('Ice.Warn.Connections', '0') communicator = Ice.initialize(sys.argv, initData) status = run(sys.argv, communicator) except: traceback.print_exc() status = False if communicator: try: communicator.destroy() except: traceback.print_exc() status = False sys.exit(not status) <|fim▁end|>
usage
<|file_name|>Client.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # ********************************************************************** # # Copyright (c) 2003-2011 ZeroC, Inc. All rights reserved. # # This copy of Ice is licensed to you under the terms described in the # ICE_LICENSE file included in this distribution. # # ********************************************************************** import os, sys, traceback import Ice, AllTests def test(b): if not b: raise RuntimeError('test assertion failed') def usage(n): sys.stderr.write("Usage: " + n + " port...\n") def <|fim_middle|>(args, communicator): ports = [] for arg in args[1:]: if arg[0] == '-': sys.stderr.write(args[0] + ": unknown option `" + arg + "'\n") usage(args[0]) return False ports.append(int(arg)) if len(ports) == 0: sys.stderr.write(args[0] + ": no ports specified\n") usage(args[0]) return False try: AllTests.allTests(communicator, ports) except: traceback.print_exc() test(False) return True try: initData = Ice.InitializationData() initData.properties = Ice.createProperties(sys.argv) # # This test aborts servers, so we don't want warnings. # initData.properties.setProperty('Ice.Warn.Connections', '0') communicator = Ice.initialize(sys.argv, initData) status = run(sys.argv, communicator) except: traceback.print_exc() status = False if communicator: try: communicator.destroy() except: traceback.print_exc() status = False sys.exit(not status) <|fim▁end|>
run
<|file_name|>test_ae_detector.py<|end_file_name|><|fim▁begin|># # Copyright 2018 Analytics Zoo Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0<|fim▁hole|># distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import pytest import numpy as np from test.zoo.pipeline.utils.test_utils import ZooTestCase from zoo.chronos.detector.anomaly.ae_detector import AEDetector class TestAEDetector(ZooTestCase): def setup_method(self, method): pass def teardown_method(self, method): pass def create_data(self): cycles = 10 time = np.arange(0, cycles * np.pi, 0.01) data = np.sin(time) data[600:800] = 10 return data def test_ae_fit_score_rolled_keras(self): y = self.create_data() ad = AEDetector(roll_len=314) ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_ae_fit_score_rolled_pytorch(self): y = self.create_data() ad = AEDetector(roll_len=314, backend="torch") ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_ae_fit_score_unrolled(self): y = self.create_data() ad = AEDetector(roll_len=0) ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_corner_cases(self): y = self.create_data() ad = AEDetector(roll_len=314, backend="dummy") with pytest.raises(ValueError): ad.fit(y) ad = AEDetector(roll_len=314) with pytest.raises(RuntimeError): ad.score() y = np.array([1]) with pytest.raises(ValueError): ad.fit(y) y = self.create_data() y = y.reshape(2, -1) with pytest.raises(ValueError): ad.fit(y)<|fim▁end|>
# # Unless required by applicable law or agreed to in writing, software
<|file_name|>test_ae_detector.py<|end_file_name|><|fim▁begin|># # Copyright 2018 Analytics Zoo Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import pytest import numpy as np from test.zoo.pipeline.utils.test_utils import ZooTestCase from zoo.chronos.detector.anomaly.ae_detector import AEDetector class TestAEDetector(ZooTestCase): <|fim_middle|> <|fim▁end|>
def setup_method(self, method): pass def teardown_method(self, method): pass def create_data(self): cycles = 10 time = np.arange(0, cycles * np.pi, 0.01) data = np.sin(time) data[600:800] = 10 return data def test_ae_fit_score_rolled_keras(self): y = self.create_data() ad = AEDetector(roll_len=314) ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_ae_fit_score_rolled_pytorch(self): y = self.create_data() ad = AEDetector(roll_len=314, backend="torch") ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_ae_fit_score_unrolled(self): y = self.create_data() ad = AEDetector(roll_len=0) ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_corner_cases(self): y = self.create_data() ad = AEDetector(roll_len=314, backend="dummy") with pytest.raises(ValueError): ad.fit(y) ad = AEDetector(roll_len=314) with pytest.raises(RuntimeError): ad.score() y = np.array([1]) with pytest.raises(ValueError): ad.fit(y) y = self.create_data() y = y.reshape(2, -1) with pytest.raises(ValueError): ad.fit(y)
<|file_name|>test_ae_detector.py<|end_file_name|><|fim▁begin|># # Copyright 2018 Analytics Zoo Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import pytest import numpy as np from test.zoo.pipeline.utils.test_utils import ZooTestCase from zoo.chronos.detector.anomaly.ae_detector import AEDetector class TestAEDetector(ZooTestCase): def setup_method(self, method): <|fim_middle|> def teardown_method(self, method): pass def create_data(self): cycles = 10 time = np.arange(0, cycles * np.pi, 0.01) data = np.sin(time) data[600:800] = 10 return data def test_ae_fit_score_rolled_keras(self): y = self.create_data() ad = AEDetector(roll_len=314) ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_ae_fit_score_rolled_pytorch(self): y = self.create_data() ad = AEDetector(roll_len=314, backend="torch") ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_ae_fit_score_unrolled(self): y = self.create_data() ad = AEDetector(roll_len=0) ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_corner_cases(self): y = self.create_data() ad = AEDetector(roll_len=314, backend="dummy") with pytest.raises(ValueError): ad.fit(y) ad = AEDetector(roll_len=314) with pytest.raises(RuntimeError): ad.score() y = np.array([1]) with pytest.raises(ValueError): ad.fit(y) y = self.create_data() y = y.reshape(2, -1) with pytest.raises(ValueError): ad.fit(y) <|fim▁end|>
pass
<|file_name|>test_ae_detector.py<|end_file_name|><|fim▁begin|># # Copyright 2018 Analytics Zoo Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import pytest import numpy as np from test.zoo.pipeline.utils.test_utils import ZooTestCase from zoo.chronos.detector.anomaly.ae_detector import AEDetector class TestAEDetector(ZooTestCase): def setup_method(self, method): pass def teardown_method(self, method): <|fim_middle|> def create_data(self): cycles = 10 time = np.arange(0, cycles * np.pi, 0.01) data = np.sin(time) data[600:800] = 10 return data def test_ae_fit_score_rolled_keras(self): y = self.create_data() ad = AEDetector(roll_len=314) ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_ae_fit_score_rolled_pytorch(self): y = self.create_data() ad = AEDetector(roll_len=314, backend="torch") ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_ae_fit_score_unrolled(self): y = self.create_data() ad = AEDetector(roll_len=0) ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_corner_cases(self): y = self.create_data() ad = AEDetector(roll_len=314, backend="dummy") with pytest.raises(ValueError): ad.fit(y) ad = AEDetector(roll_len=314) with pytest.raises(RuntimeError): ad.score() y = np.array([1]) with pytest.raises(ValueError): ad.fit(y) y = self.create_data() y = y.reshape(2, -1) with pytest.raises(ValueError): ad.fit(y) <|fim▁end|>
pass
<|file_name|>test_ae_detector.py<|end_file_name|><|fim▁begin|># # Copyright 2018 Analytics Zoo Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import pytest import numpy as np from test.zoo.pipeline.utils.test_utils import ZooTestCase from zoo.chronos.detector.anomaly.ae_detector import AEDetector class TestAEDetector(ZooTestCase): def setup_method(self, method): pass def teardown_method(self, method): pass def create_data(self): <|fim_middle|> def test_ae_fit_score_rolled_keras(self): y = self.create_data() ad = AEDetector(roll_len=314) ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_ae_fit_score_rolled_pytorch(self): y = self.create_data() ad = AEDetector(roll_len=314, backend="torch") ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_ae_fit_score_unrolled(self): y = self.create_data() ad = AEDetector(roll_len=0) ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_corner_cases(self): y = self.create_data() ad = AEDetector(roll_len=314, backend="dummy") with pytest.raises(ValueError): ad.fit(y) ad = AEDetector(roll_len=314) with pytest.raises(RuntimeError): ad.score() y = np.array([1]) with pytest.raises(ValueError): ad.fit(y) y = self.create_data() y = y.reshape(2, -1) with pytest.raises(ValueError): ad.fit(y) <|fim▁end|>
cycles = 10 time = np.arange(0, cycles * np.pi, 0.01) data = np.sin(time) data[600:800] = 10 return data
<|file_name|>test_ae_detector.py<|end_file_name|><|fim▁begin|># # Copyright 2018 Analytics Zoo Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import pytest import numpy as np from test.zoo.pipeline.utils.test_utils import ZooTestCase from zoo.chronos.detector.anomaly.ae_detector import AEDetector class TestAEDetector(ZooTestCase): def setup_method(self, method): pass def teardown_method(self, method): pass def create_data(self): cycles = 10 time = np.arange(0, cycles * np.pi, 0.01) data = np.sin(time) data[600:800] = 10 return data def test_ae_fit_score_rolled_keras(self): <|fim_middle|> def test_ae_fit_score_rolled_pytorch(self): y = self.create_data() ad = AEDetector(roll_len=314, backend="torch") ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_ae_fit_score_unrolled(self): y = self.create_data() ad = AEDetector(roll_len=0) ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_corner_cases(self): y = self.create_data() ad = AEDetector(roll_len=314, backend="dummy") with pytest.raises(ValueError): ad.fit(y) ad = AEDetector(roll_len=314) with pytest.raises(RuntimeError): ad.score() y = np.array([1]) with pytest.raises(ValueError): ad.fit(y) y = self.create_data() y = y.reshape(2, -1) with pytest.raises(ValueError): ad.fit(y) <|fim▁end|>
y = self.create_data() ad = AEDetector(roll_len=314) ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y))
<|file_name|>test_ae_detector.py<|end_file_name|><|fim▁begin|># # Copyright 2018 Analytics Zoo Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import pytest import numpy as np from test.zoo.pipeline.utils.test_utils import ZooTestCase from zoo.chronos.detector.anomaly.ae_detector import AEDetector class TestAEDetector(ZooTestCase): def setup_method(self, method): pass def teardown_method(self, method): pass def create_data(self): cycles = 10 time = np.arange(0, cycles * np.pi, 0.01) data = np.sin(time) data[600:800] = 10 return data def test_ae_fit_score_rolled_keras(self): y = self.create_data() ad = AEDetector(roll_len=314) ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_ae_fit_score_rolled_pytorch(self): <|fim_middle|> def test_ae_fit_score_unrolled(self): y = self.create_data() ad = AEDetector(roll_len=0) ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_corner_cases(self): y = self.create_data() ad = AEDetector(roll_len=314, backend="dummy") with pytest.raises(ValueError): ad.fit(y) ad = AEDetector(roll_len=314) with pytest.raises(RuntimeError): ad.score() y = np.array([1]) with pytest.raises(ValueError): ad.fit(y) y = self.create_data() y = y.reshape(2, -1) with pytest.raises(ValueError): ad.fit(y) <|fim▁end|>
y = self.create_data() ad = AEDetector(roll_len=314, backend="torch") ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y))
<|file_name|>test_ae_detector.py<|end_file_name|><|fim▁begin|># # Copyright 2018 Analytics Zoo Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import pytest import numpy as np from test.zoo.pipeline.utils.test_utils import ZooTestCase from zoo.chronos.detector.anomaly.ae_detector import AEDetector class TestAEDetector(ZooTestCase): def setup_method(self, method): pass def teardown_method(self, method): pass def create_data(self): cycles = 10 time = np.arange(0, cycles * np.pi, 0.01) data = np.sin(time) data[600:800] = 10 return data def test_ae_fit_score_rolled_keras(self): y = self.create_data() ad = AEDetector(roll_len=314) ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_ae_fit_score_rolled_pytorch(self): y = self.create_data() ad = AEDetector(roll_len=314, backend="torch") ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_ae_fit_score_unrolled(self): <|fim_middle|> def test_corner_cases(self): y = self.create_data() ad = AEDetector(roll_len=314, backend="dummy") with pytest.raises(ValueError): ad.fit(y) ad = AEDetector(roll_len=314) with pytest.raises(RuntimeError): ad.score() y = np.array([1]) with pytest.raises(ValueError): ad.fit(y) y = self.create_data() y = y.reshape(2, -1) with pytest.raises(ValueError): ad.fit(y) <|fim▁end|>
y = self.create_data() ad = AEDetector(roll_len=0) ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y))
<|file_name|>test_ae_detector.py<|end_file_name|><|fim▁begin|># # Copyright 2018 Analytics Zoo Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import pytest import numpy as np from test.zoo.pipeline.utils.test_utils import ZooTestCase from zoo.chronos.detector.anomaly.ae_detector import AEDetector class TestAEDetector(ZooTestCase): def setup_method(self, method): pass def teardown_method(self, method): pass def create_data(self): cycles = 10 time = np.arange(0, cycles * np.pi, 0.01) data = np.sin(time) data[600:800] = 10 return data def test_ae_fit_score_rolled_keras(self): y = self.create_data() ad = AEDetector(roll_len=314) ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_ae_fit_score_rolled_pytorch(self): y = self.create_data() ad = AEDetector(roll_len=314, backend="torch") ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_ae_fit_score_unrolled(self): y = self.create_data() ad = AEDetector(roll_len=0) ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_corner_cases(self): <|fim_middle|> <|fim▁end|>
y = self.create_data() ad = AEDetector(roll_len=314, backend="dummy") with pytest.raises(ValueError): ad.fit(y) ad = AEDetector(roll_len=314) with pytest.raises(RuntimeError): ad.score() y = np.array([1]) with pytest.raises(ValueError): ad.fit(y) y = self.create_data() y = y.reshape(2, -1) with pytest.raises(ValueError): ad.fit(y)
<|file_name|>test_ae_detector.py<|end_file_name|><|fim▁begin|># # Copyright 2018 Analytics Zoo Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import pytest import numpy as np from test.zoo.pipeline.utils.test_utils import ZooTestCase from zoo.chronos.detector.anomaly.ae_detector import AEDetector class TestAEDetector(ZooTestCase): def <|fim_middle|>(self, method): pass def teardown_method(self, method): pass def create_data(self): cycles = 10 time = np.arange(0, cycles * np.pi, 0.01) data = np.sin(time) data[600:800] = 10 return data def test_ae_fit_score_rolled_keras(self): y = self.create_data() ad = AEDetector(roll_len=314) ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_ae_fit_score_rolled_pytorch(self): y = self.create_data() ad = AEDetector(roll_len=314, backend="torch") ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_ae_fit_score_unrolled(self): y = self.create_data() ad = AEDetector(roll_len=0) ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_corner_cases(self): y = self.create_data() ad = AEDetector(roll_len=314, backend="dummy") with pytest.raises(ValueError): ad.fit(y) ad = AEDetector(roll_len=314) with pytest.raises(RuntimeError): ad.score() y = np.array([1]) with pytest.raises(ValueError): ad.fit(y) y = self.create_data() y = y.reshape(2, -1) with pytest.raises(ValueError): ad.fit(y) <|fim▁end|>
setup_method
<|file_name|>test_ae_detector.py<|end_file_name|><|fim▁begin|># # Copyright 2018 Analytics Zoo Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import pytest import numpy as np from test.zoo.pipeline.utils.test_utils import ZooTestCase from zoo.chronos.detector.anomaly.ae_detector import AEDetector class TestAEDetector(ZooTestCase): def setup_method(self, method): pass def <|fim_middle|>(self, method): pass def create_data(self): cycles = 10 time = np.arange(0, cycles * np.pi, 0.01) data = np.sin(time) data[600:800] = 10 return data def test_ae_fit_score_rolled_keras(self): y = self.create_data() ad = AEDetector(roll_len=314) ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_ae_fit_score_rolled_pytorch(self): y = self.create_data() ad = AEDetector(roll_len=314, backend="torch") ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_ae_fit_score_unrolled(self): y = self.create_data() ad = AEDetector(roll_len=0) ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_corner_cases(self): y = self.create_data() ad = AEDetector(roll_len=314, backend="dummy") with pytest.raises(ValueError): ad.fit(y) ad = AEDetector(roll_len=314) with pytest.raises(RuntimeError): ad.score() y = np.array([1]) with pytest.raises(ValueError): ad.fit(y) y = self.create_data() y = y.reshape(2, -1) with pytest.raises(ValueError): ad.fit(y) <|fim▁end|>
teardown_method
<|file_name|>test_ae_detector.py<|end_file_name|><|fim▁begin|># # Copyright 2018 Analytics Zoo Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import pytest import numpy as np from test.zoo.pipeline.utils.test_utils import ZooTestCase from zoo.chronos.detector.anomaly.ae_detector import AEDetector class TestAEDetector(ZooTestCase): def setup_method(self, method): pass def teardown_method(self, method): pass def <|fim_middle|>(self): cycles = 10 time = np.arange(0, cycles * np.pi, 0.01) data = np.sin(time) data[600:800] = 10 return data def test_ae_fit_score_rolled_keras(self): y = self.create_data() ad = AEDetector(roll_len=314) ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_ae_fit_score_rolled_pytorch(self): y = self.create_data() ad = AEDetector(roll_len=314, backend="torch") ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_ae_fit_score_unrolled(self): y = self.create_data() ad = AEDetector(roll_len=0) ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_corner_cases(self): y = self.create_data() ad = AEDetector(roll_len=314, backend="dummy") with pytest.raises(ValueError): ad.fit(y) ad = AEDetector(roll_len=314) with pytest.raises(RuntimeError): ad.score() y = np.array([1]) with pytest.raises(ValueError): ad.fit(y) y = self.create_data() y = y.reshape(2, -1) with pytest.raises(ValueError): ad.fit(y) <|fim▁end|>
create_data
<|file_name|>test_ae_detector.py<|end_file_name|><|fim▁begin|># # Copyright 2018 Analytics Zoo Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import pytest import numpy as np from test.zoo.pipeline.utils.test_utils import ZooTestCase from zoo.chronos.detector.anomaly.ae_detector import AEDetector class TestAEDetector(ZooTestCase): def setup_method(self, method): pass def teardown_method(self, method): pass def create_data(self): cycles = 10 time = np.arange(0, cycles * np.pi, 0.01) data = np.sin(time) data[600:800] = 10 return data def <|fim_middle|>(self): y = self.create_data() ad = AEDetector(roll_len=314) ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_ae_fit_score_rolled_pytorch(self): y = self.create_data() ad = AEDetector(roll_len=314, backend="torch") ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_ae_fit_score_unrolled(self): y = self.create_data() ad = AEDetector(roll_len=0) ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_corner_cases(self): y = self.create_data() ad = AEDetector(roll_len=314, backend="dummy") with pytest.raises(ValueError): ad.fit(y) ad = AEDetector(roll_len=314) with pytest.raises(RuntimeError): ad.score() y = np.array([1]) with pytest.raises(ValueError): ad.fit(y) y = self.create_data() y = y.reshape(2, -1) with pytest.raises(ValueError): ad.fit(y) <|fim▁end|>
test_ae_fit_score_rolled_keras
<|file_name|>test_ae_detector.py<|end_file_name|><|fim▁begin|># # Copyright 2018 Analytics Zoo Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import pytest import numpy as np from test.zoo.pipeline.utils.test_utils import ZooTestCase from zoo.chronos.detector.anomaly.ae_detector import AEDetector class TestAEDetector(ZooTestCase): def setup_method(self, method): pass def teardown_method(self, method): pass def create_data(self): cycles = 10 time = np.arange(0, cycles * np.pi, 0.01) data = np.sin(time) data[600:800] = 10 return data def test_ae_fit_score_rolled_keras(self): y = self.create_data() ad = AEDetector(roll_len=314) ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def <|fim_middle|>(self): y = self.create_data() ad = AEDetector(roll_len=314, backend="torch") ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_ae_fit_score_unrolled(self): y = self.create_data() ad = AEDetector(roll_len=0) ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_corner_cases(self): y = self.create_data() ad = AEDetector(roll_len=314, backend="dummy") with pytest.raises(ValueError): ad.fit(y) ad = AEDetector(roll_len=314) with pytest.raises(RuntimeError): ad.score() y = np.array([1]) with pytest.raises(ValueError): ad.fit(y) y = self.create_data() y = y.reshape(2, -1) with pytest.raises(ValueError): ad.fit(y) <|fim▁end|>
test_ae_fit_score_rolled_pytorch
<|file_name|>test_ae_detector.py<|end_file_name|><|fim▁begin|># # Copyright 2018 Analytics Zoo Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import pytest import numpy as np from test.zoo.pipeline.utils.test_utils import ZooTestCase from zoo.chronos.detector.anomaly.ae_detector import AEDetector class TestAEDetector(ZooTestCase): def setup_method(self, method): pass def teardown_method(self, method): pass def create_data(self): cycles = 10 time = np.arange(0, cycles * np.pi, 0.01) data = np.sin(time) data[600:800] = 10 return data def test_ae_fit_score_rolled_keras(self): y = self.create_data() ad = AEDetector(roll_len=314) ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_ae_fit_score_rolled_pytorch(self): y = self.create_data() ad = AEDetector(roll_len=314, backend="torch") ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def <|fim_middle|>(self): y = self.create_data() ad = AEDetector(roll_len=0) ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_corner_cases(self): y = self.create_data() ad = AEDetector(roll_len=314, backend="dummy") with pytest.raises(ValueError): ad.fit(y) ad = AEDetector(roll_len=314) with pytest.raises(RuntimeError): ad.score() y = np.array([1]) with pytest.raises(ValueError): ad.fit(y) y = self.create_data() y = y.reshape(2, -1) with pytest.raises(ValueError): ad.fit(y) <|fim▁end|>
test_ae_fit_score_unrolled
<|file_name|>test_ae_detector.py<|end_file_name|><|fim▁begin|># # Copyright 2018 Analytics Zoo Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import pytest import numpy as np from test.zoo.pipeline.utils.test_utils import ZooTestCase from zoo.chronos.detector.anomaly.ae_detector import AEDetector class TestAEDetector(ZooTestCase): def setup_method(self, method): pass def teardown_method(self, method): pass def create_data(self): cycles = 10 time = np.arange(0, cycles * np.pi, 0.01) data = np.sin(time) data[600:800] = 10 return data def test_ae_fit_score_rolled_keras(self): y = self.create_data() ad = AEDetector(roll_len=314) ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_ae_fit_score_rolled_pytorch(self): y = self.create_data() ad = AEDetector(roll_len=314, backend="torch") ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_ae_fit_score_unrolled(self): y = self.create_data() ad = AEDetector(roll_len=0) ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def <|fim_middle|>(self): y = self.create_data() ad = AEDetector(roll_len=314, backend="dummy") with pytest.raises(ValueError): ad.fit(y) ad = AEDetector(roll_len=314) with pytest.raises(RuntimeError): ad.score() y = np.array([1]) with pytest.raises(ValueError): ad.fit(y) y = self.create_data() y = y.reshape(2, -1) with pytest.raises(ValueError): ad.fit(y) <|fim▁end|>
test_corner_cases
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>from distutils.core import setup setup( # Application name: name="streaker", # Version number (initial): version="0.0.1", # Application author details: author="Aldi Alimucaj",<|fim▁hole|> # Packages packages=["streaker"], scripts=['bin/streaker'], # Include additional files into the package include_package_data=True, # Details url="http://pypi.python.org/pypi/Streaker_v001/", # license="MIT", description="GitHub streak manipulator", # long_description=open("README.txt").read(), # Dependent packages (distributions) install_requires=[ # "", ], )<|fim▁end|>
author_email="[email protected]",
<|file_name|>wire.py<|end_file_name|><|fim▁begin|># Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """Implement standard (and unused) TCP protocols. These protocols are either provided by inetd, or are not provided at all. """ from __future__ import absolute_import, division import time import struct from zope.interface import implementer from twisted.internet import protocol, interfaces from twisted.python.compat import _PY3 class Echo(protocol.Protocol): """As soon as any data is received, write it back (RFC 862)""" def dataReceived(self, data): self.transport.write(data) class Discard(protocol.Protocol): """Discard any received data (RFC 863)""" def dataReceived(self, data): # I'm ignoring you, nyah-nyah pass @implementer(interfaces.IProducer) class Chargen(protocol.Protocol): """Generate repeating noise (RFC 864)""" noise = r'@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ !"#$%&?' def connectionMade(self): self.transport.registerProducer(self, 0) def resumeProducing(self): self.transport.write(self.noise) def pauseProducing(self): pass def stopProducing(self): pass class QOTD(protocol.Protocol): """Return a quote of the day (RFC 865)""" def connectionMade(self): self.transport.write(self.getQuote()) self.transport.loseConnection() def getQuote(self): """Return a quote. May be overrriden in subclasses.""" return "An apple a day keeps the doctor away.\r\n" class Who(protocol.Protocol): """Return list of active users (RFC 866)""" def connectionMade(self): self.transport.write(self.getUsers()) self.transport.loseConnection() <|fim▁hole|> class Daytime(protocol.Protocol): """Send back the daytime in ASCII form (RFC 867)""" def connectionMade(self): self.transport.write(time.asctime(time.gmtime(time.time())) + '\r\n') self.transport.loseConnection() class Time(protocol.Protocol): """Send back the time in machine readable form (RFC 868)""" def connectionMade(self): # is this correct only for 32-bit machines? result = struct.pack("!i", int(time.time())) self.transport.write(result) self.transport.loseConnection() __all__ = ["Echo", "Discard", "Chargen", "QOTD", "Who", "Daytime", "Time"] if _PY3: __all3__ = ["Echo"] for name in __all__[:]: if name not in __all3__: __all__.remove(name) del globals()[name] del name, __all3__<|fim▁end|>
def getUsers(self): """Return active users. Override in subclasses.""" return "root\r\n"
<|file_name|>wire.py<|end_file_name|><|fim▁begin|># Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """Implement standard (and unused) TCP protocols. These protocols are either provided by inetd, or are not provided at all. """ from __future__ import absolute_import, division import time import struct from zope.interface import implementer from twisted.internet import protocol, interfaces from twisted.python.compat import _PY3 class Echo(protocol.Protocol): <|fim_middle|> class Discard(protocol.Protocol): """Discard any received data (RFC 863)""" def dataReceived(self, data): # I'm ignoring you, nyah-nyah pass @implementer(interfaces.IProducer) class Chargen(protocol.Protocol): """Generate repeating noise (RFC 864)""" noise = r'@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ !"#$%&?' def connectionMade(self): self.transport.registerProducer(self, 0) def resumeProducing(self): self.transport.write(self.noise) def pauseProducing(self): pass def stopProducing(self): pass class QOTD(protocol.Protocol): """Return a quote of the day (RFC 865)""" def connectionMade(self): self.transport.write(self.getQuote()) self.transport.loseConnection() def getQuote(self): """Return a quote. May be overrriden in subclasses.""" return "An apple a day keeps the doctor away.\r\n" class Who(protocol.Protocol): """Return list of active users (RFC 866)""" def connectionMade(self): self.transport.write(self.getUsers()) self.transport.loseConnection() def getUsers(self): """Return active users. Override in subclasses.""" return "root\r\n" class Daytime(protocol.Protocol): """Send back the daytime in ASCII form (RFC 867)""" def connectionMade(self): self.transport.write(time.asctime(time.gmtime(time.time())) + '\r\n') self.transport.loseConnection() class Time(protocol.Protocol): """Send back the time in machine readable form (RFC 868)""" def connectionMade(self): # is this correct only for 32-bit machines? result = struct.pack("!i", int(time.time())) self.transport.write(result) self.transport.loseConnection() __all__ = ["Echo", "Discard", "Chargen", "QOTD", "Who", "Daytime", "Time"] if _PY3: __all3__ = ["Echo"] for name in __all__[:]: if name not in __all3__: __all__.remove(name) del globals()[name] del name, __all3__ <|fim▁end|>
"""As soon as any data is received, write it back (RFC 862)""" def dataReceived(self, data): self.transport.write(data)
<|file_name|>wire.py<|end_file_name|><|fim▁begin|># Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """Implement standard (and unused) TCP protocols. These protocols are either provided by inetd, or are not provided at all. """ from __future__ import absolute_import, division import time import struct from zope.interface import implementer from twisted.internet import protocol, interfaces from twisted.python.compat import _PY3 class Echo(protocol.Protocol): """As soon as any data is received, write it back (RFC 862)""" def dataReceived(self, data): <|fim_middle|> class Discard(protocol.Protocol): """Discard any received data (RFC 863)""" def dataReceived(self, data): # I'm ignoring you, nyah-nyah pass @implementer(interfaces.IProducer) class Chargen(protocol.Protocol): """Generate repeating noise (RFC 864)""" noise = r'@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ !"#$%&?' def connectionMade(self): self.transport.registerProducer(self, 0) def resumeProducing(self): self.transport.write(self.noise) def pauseProducing(self): pass def stopProducing(self): pass class QOTD(protocol.Protocol): """Return a quote of the day (RFC 865)""" def connectionMade(self): self.transport.write(self.getQuote()) self.transport.loseConnection() def getQuote(self): """Return a quote. May be overrriden in subclasses.""" return "An apple a day keeps the doctor away.\r\n" class Who(protocol.Protocol): """Return list of active users (RFC 866)""" def connectionMade(self): self.transport.write(self.getUsers()) self.transport.loseConnection() def getUsers(self): """Return active users. Override in subclasses.""" return "root\r\n" class Daytime(protocol.Protocol): """Send back the daytime in ASCII form (RFC 867)""" def connectionMade(self): self.transport.write(time.asctime(time.gmtime(time.time())) + '\r\n') self.transport.loseConnection() class Time(protocol.Protocol): """Send back the time in machine readable form (RFC 868)""" def connectionMade(self): # is this correct only for 32-bit machines? result = struct.pack("!i", int(time.time())) self.transport.write(result) self.transport.loseConnection() __all__ = ["Echo", "Discard", "Chargen", "QOTD", "Who", "Daytime", "Time"] if _PY3: __all3__ = ["Echo"] for name in __all__[:]: if name not in __all3__: __all__.remove(name) del globals()[name] del name, __all3__ <|fim▁end|>
self.transport.write(data)
<|file_name|>wire.py<|end_file_name|><|fim▁begin|># Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """Implement standard (and unused) TCP protocols. These protocols are either provided by inetd, or are not provided at all. """ from __future__ import absolute_import, division import time import struct from zope.interface import implementer from twisted.internet import protocol, interfaces from twisted.python.compat import _PY3 class Echo(protocol.Protocol): """As soon as any data is received, write it back (RFC 862)""" def dataReceived(self, data): self.transport.write(data) class Discard(protocol.Protocol): <|fim_middle|> @implementer(interfaces.IProducer) class Chargen(protocol.Protocol): """Generate repeating noise (RFC 864)""" noise = r'@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ !"#$%&?' def connectionMade(self): self.transport.registerProducer(self, 0) def resumeProducing(self): self.transport.write(self.noise) def pauseProducing(self): pass def stopProducing(self): pass class QOTD(protocol.Protocol): """Return a quote of the day (RFC 865)""" def connectionMade(self): self.transport.write(self.getQuote()) self.transport.loseConnection() def getQuote(self): """Return a quote. May be overrriden in subclasses.""" return "An apple a day keeps the doctor away.\r\n" class Who(protocol.Protocol): """Return list of active users (RFC 866)""" def connectionMade(self): self.transport.write(self.getUsers()) self.transport.loseConnection() def getUsers(self): """Return active users. Override in subclasses.""" return "root\r\n" class Daytime(protocol.Protocol): """Send back the daytime in ASCII form (RFC 867)""" def connectionMade(self): self.transport.write(time.asctime(time.gmtime(time.time())) + '\r\n') self.transport.loseConnection() class Time(protocol.Protocol): """Send back the time in machine readable form (RFC 868)""" def connectionMade(self): # is this correct only for 32-bit machines? result = struct.pack("!i", int(time.time())) self.transport.write(result) self.transport.loseConnection() __all__ = ["Echo", "Discard", "Chargen", "QOTD", "Who", "Daytime", "Time"] if _PY3: __all3__ = ["Echo"] for name in __all__[:]: if name not in __all3__: __all__.remove(name) del globals()[name] del name, __all3__ <|fim▁end|>
"""Discard any received data (RFC 863)""" def dataReceived(self, data): # I'm ignoring you, nyah-nyah pass
<|file_name|>wire.py<|end_file_name|><|fim▁begin|># Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """Implement standard (and unused) TCP protocols. These protocols are either provided by inetd, or are not provided at all. """ from __future__ import absolute_import, division import time import struct from zope.interface import implementer from twisted.internet import protocol, interfaces from twisted.python.compat import _PY3 class Echo(protocol.Protocol): """As soon as any data is received, write it back (RFC 862)""" def dataReceived(self, data): self.transport.write(data) class Discard(protocol.Protocol): """Discard any received data (RFC 863)""" def dataReceived(self, data): # I'm ignoring you, nyah-nyah <|fim_middle|> @implementer(interfaces.IProducer) class Chargen(protocol.Protocol): """Generate repeating noise (RFC 864)""" noise = r'@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ !"#$%&?' def connectionMade(self): self.transport.registerProducer(self, 0) def resumeProducing(self): self.transport.write(self.noise) def pauseProducing(self): pass def stopProducing(self): pass class QOTD(protocol.Protocol): """Return a quote of the day (RFC 865)""" def connectionMade(self): self.transport.write(self.getQuote()) self.transport.loseConnection() def getQuote(self): """Return a quote. May be overrriden in subclasses.""" return "An apple a day keeps the doctor away.\r\n" class Who(protocol.Protocol): """Return list of active users (RFC 866)""" def connectionMade(self): self.transport.write(self.getUsers()) self.transport.loseConnection() def getUsers(self): """Return active users. Override in subclasses.""" return "root\r\n" class Daytime(protocol.Protocol): """Send back the daytime in ASCII form (RFC 867)""" def connectionMade(self): self.transport.write(time.asctime(time.gmtime(time.time())) + '\r\n') self.transport.loseConnection() class Time(protocol.Protocol): """Send back the time in machine readable form (RFC 868)""" def connectionMade(self): # is this correct only for 32-bit machines? result = struct.pack("!i", int(time.time())) self.transport.write(result) self.transport.loseConnection() __all__ = ["Echo", "Discard", "Chargen", "QOTD", "Who", "Daytime", "Time"] if _PY3: __all3__ = ["Echo"] for name in __all__[:]: if name not in __all3__: __all__.remove(name) del globals()[name] del name, __all3__ <|fim▁end|>
pass
<|file_name|>wire.py<|end_file_name|><|fim▁begin|># Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """Implement standard (and unused) TCP protocols. These protocols are either provided by inetd, or are not provided at all. """ from __future__ import absolute_import, division import time import struct from zope.interface import implementer from twisted.internet import protocol, interfaces from twisted.python.compat import _PY3 class Echo(protocol.Protocol): """As soon as any data is received, write it back (RFC 862)""" def dataReceived(self, data): self.transport.write(data) class Discard(protocol.Protocol): """Discard any received data (RFC 863)""" def dataReceived(self, data): # I'm ignoring you, nyah-nyah pass @implementer(interfaces.IProducer) class Chargen(protocol.Protocol): <|fim_middle|> class QOTD(protocol.Protocol): """Return a quote of the day (RFC 865)""" def connectionMade(self): self.transport.write(self.getQuote()) self.transport.loseConnection() def getQuote(self): """Return a quote. May be overrriden in subclasses.""" return "An apple a day keeps the doctor away.\r\n" class Who(protocol.Protocol): """Return list of active users (RFC 866)""" def connectionMade(self): self.transport.write(self.getUsers()) self.transport.loseConnection() def getUsers(self): """Return active users. Override in subclasses.""" return "root\r\n" class Daytime(protocol.Protocol): """Send back the daytime in ASCII form (RFC 867)""" def connectionMade(self): self.transport.write(time.asctime(time.gmtime(time.time())) + '\r\n') self.transport.loseConnection() class Time(protocol.Protocol): """Send back the time in machine readable form (RFC 868)""" def connectionMade(self): # is this correct only for 32-bit machines? result = struct.pack("!i", int(time.time())) self.transport.write(result) self.transport.loseConnection() __all__ = ["Echo", "Discard", "Chargen", "QOTD", "Who", "Daytime", "Time"] if _PY3: __all3__ = ["Echo"] for name in __all__[:]: if name not in __all3__: __all__.remove(name) del globals()[name] del name, __all3__ <|fim▁end|>
"""Generate repeating noise (RFC 864)""" noise = r'@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ !"#$%&?' def connectionMade(self): self.transport.registerProducer(self, 0) def resumeProducing(self): self.transport.write(self.noise) def pauseProducing(self): pass def stopProducing(self): pass
<|file_name|>wire.py<|end_file_name|><|fim▁begin|># Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """Implement standard (and unused) TCP protocols. These protocols are either provided by inetd, or are not provided at all. """ from __future__ import absolute_import, division import time import struct from zope.interface import implementer from twisted.internet import protocol, interfaces from twisted.python.compat import _PY3 class Echo(protocol.Protocol): """As soon as any data is received, write it back (RFC 862)""" def dataReceived(self, data): self.transport.write(data) class Discard(protocol.Protocol): """Discard any received data (RFC 863)""" def dataReceived(self, data): # I'm ignoring you, nyah-nyah pass @implementer(interfaces.IProducer) class Chargen(protocol.Protocol): """Generate repeating noise (RFC 864)""" noise = r'@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ !"#$%&?' def connectionMade(self): <|fim_middle|> def resumeProducing(self): self.transport.write(self.noise) def pauseProducing(self): pass def stopProducing(self): pass class QOTD(protocol.Protocol): """Return a quote of the day (RFC 865)""" def connectionMade(self): self.transport.write(self.getQuote()) self.transport.loseConnection() def getQuote(self): """Return a quote. May be overrriden in subclasses.""" return "An apple a day keeps the doctor away.\r\n" class Who(protocol.Protocol): """Return list of active users (RFC 866)""" def connectionMade(self): self.transport.write(self.getUsers()) self.transport.loseConnection() def getUsers(self): """Return active users. Override in subclasses.""" return "root\r\n" class Daytime(protocol.Protocol): """Send back the daytime in ASCII form (RFC 867)""" def connectionMade(self): self.transport.write(time.asctime(time.gmtime(time.time())) + '\r\n') self.transport.loseConnection() class Time(protocol.Protocol): """Send back the time in machine readable form (RFC 868)""" def connectionMade(self): # is this correct only for 32-bit machines? result = struct.pack("!i", int(time.time())) self.transport.write(result) self.transport.loseConnection() __all__ = ["Echo", "Discard", "Chargen", "QOTD", "Who", "Daytime", "Time"] if _PY3: __all3__ = ["Echo"] for name in __all__[:]: if name not in __all3__: __all__.remove(name) del globals()[name] del name, __all3__ <|fim▁end|>
self.transport.registerProducer(self, 0)
<|file_name|>wire.py<|end_file_name|><|fim▁begin|># Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """Implement standard (and unused) TCP protocols. These protocols are either provided by inetd, or are not provided at all. """ from __future__ import absolute_import, division import time import struct from zope.interface import implementer from twisted.internet import protocol, interfaces from twisted.python.compat import _PY3 class Echo(protocol.Protocol): """As soon as any data is received, write it back (RFC 862)""" def dataReceived(self, data): self.transport.write(data) class Discard(protocol.Protocol): """Discard any received data (RFC 863)""" def dataReceived(self, data): # I'm ignoring you, nyah-nyah pass @implementer(interfaces.IProducer) class Chargen(protocol.Protocol): """Generate repeating noise (RFC 864)""" noise = r'@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ !"#$%&?' def connectionMade(self): self.transport.registerProducer(self, 0) def resumeProducing(self): <|fim_middle|> def pauseProducing(self): pass def stopProducing(self): pass class QOTD(protocol.Protocol): """Return a quote of the day (RFC 865)""" def connectionMade(self): self.transport.write(self.getQuote()) self.transport.loseConnection() def getQuote(self): """Return a quote. May be overrriden in subclasses.""" return "An apple a day keeps the doctor away.\r\n" class Who(protocol.Protocol): """Return list of active users (RFC 866)""" def connectionMade(self): self.transport.write(self.getUsers()) self.transport.loseConnection() def getUsers(self): """Return active users. Override in subclasses.""" return "root\r\n" class Daytime(protocol.Protocol): """Send back the daytime in ASCII form (RFC 867)""" def connectionMade(self): self.transport.write(time.asctime(time.gmtime(time.time())) + '\r\n') self.transport.loseConnection() class Time(protocol.Protocol): """Send back the time in machine readable form (RFC 868)""" def connectionMade(self): # is this correct only for 32-bit machines? result = struct.pack("!i", int(time.time())) self.transport.write(result) self.transport.loseConnection() __all__ = ["Echo", "Discard", "Chargen", "QOTD", "Who", "Daytime", "Time"] if _PY3: __all3__ = ["Echo"] for name in __all__[:]: if name not in __all3__: __all__.remove(name) del globals()[name] del name, __all3__ <|fim▁end|>
self.transport.write(self.noise)
<|file_name|>wire.py<|end_file_name|><|fim▁begin|># Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """Implement standard (and unused) TCP protocols. These protocols are either provided by inetd, or are not provided at all. """ from __future__ import absolute_import, division import time import struct from zope.interface import implementer from twisted.internet import protocol, interfaces from twisted.python.compat import _PY3 class Echo(protocol.Protocol): """As soon as any data is received, write it back (RFC 862)""" def dataReceived(self, data): self.transport.write(data) class Discard(protocol.Protocol): """Discard any received data (RFC 863)""" def dataReceived(self, data): # I'm ignoring you, nyah-nyah pass @implementer(interfaces.IProducer) class Chargen(protocol.Protocol): """Generate repeating noise (RFC 864)""" noise = r'@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ !"#$%&?' def connectionMade(self): self.transport.registerProducer(self, 0) def resumeProducing(self): self.transport.write(self.noise) def pauseProducing(self): <|fim_middle|> def stopProducing(self): pass class QOTD(protocol.Protocol): """Return a quote of the day (RFC 865)""" def connectionMade(self): self.transport.write(self.getQuote()) self.transport.loseConnection() def getQuote(self): """Return a quote. May be overrriden in subclasses.""" return "An apple a day keeps the doctor away.\r\n" class Who(protocol.Protocol): """Return list of active users (RFC 866)""" def connectionMade(self): self.transport.write(self.getUsers()) self.transport.loseConnection() def getUsers(self): """Return active users. Override in subclasses.""" return "root\r\n" class Daytime(protocol.Protocol): """Send back the daytime in ASCII form (RFC 867)""" def connectionMade(self): self.transport.write(time.asctime(time.gmtime(time.time())) + '\r\n') self.transport.loseConnection() class Time(protocol.Protocol): """Send back the time in machine readable form (RFC 868)""" def connectionMade(self): # is this correct only for 32-bit machines? result = struct.pack("!i", int(time.time())) self.transport.write(result) self.transport.loseConnection() __all__ = ["Echo", "Discard", "Chargen", "QOTD", "Who", "Daytime", "Time"] if _PY3: __all3__ = ["Echo"] for name in __all__[:]: if name not in __all3__: __all__.remove(name) del globals()[name] del name, __all3__ <|fim▁end|>
pass
<|file_name|>wire.py<|end_file_name|><|fim▁begin|># Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """Implement standard (and unused) TCP protocols. These protocols are either provided by inetd, or are not provided at all. """ from __future__ import absolute_import, division import time import struct from zope.interface import implementer from twisted.internet import protocol, interfaces from twisted.python.compat import _PY3 class Echo(protocol.Protocol): """As soon as any data is received, write it back (RFC 862)""" def dataReceived(self, data): self.transport.write(data) class Discard(protocol.Protocol): """Discard any received data (RFC 863)""" def dataReceived(self, data): # I'm ignoring you, nyah-nyah pass @implementer(interfaces.IProducer) class Chargen(protocol.Protocol): """Generate repeating noise (RFC 864)""" noise = r'@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ !"#$%&?' def connectionMade(self): self.transport.registerProducer(self, 0) def resumeProducing(self): self.transport.write(self.noise) def pauseProducing(self): pass def stopProducing(self): <|fim_middle|> class QOTD(protocol.Protocol): """Return a quote of the day (RFC 865)""" def connectionMade(self): self.transport.write(self.getQuote()) self.transport.loseConnection() def getQuote(self): """Return a quote. May be overrriden in subclasses.""" return "An apple a day keeps the doctor away.\r\n" class Who(protocol.Protocol): """Return list of active users (RFC 866)""" def connectionMade(self): self.transport.write(self.getUsers()) self.transport.loseConnection() def getUsers(self): """Return active users. Override in subclasses.""" return "root\r\n" class Daytime(protocol.Protocol): """Send back the daytime in ASCII form (RFC 867)""" def connectionMade(self): self.transport.write(time.asctime(time.gmtime(time.time())) + '\r\n') self.transport.loseConnection() class Time(protocol.Protocol): """Send back the time in machine readable form (RFC 868)""" def connectionMade(self): # is this correct only for 32-bit machines? result = struct.pack("!i", int(time.time())) self.transport.write(result) self.transport.loseConnection() __all__ = ["Echo", "Discard", "Chargen", "QOTD", "Who", "Daytime", "Time"] if _PY3: __all3__ = ["Echo"] for name in __all__[:]: if name not in __all3__: __all__.remove(name) del globals()[name] del name, __all3__ <|fim▁end|>
pass
<|file_name|>wire.py<|end_file_name|><|fim▁begin|># Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """Implement standard (and unused) TCP protocols. These protocols are either provided by inetd, or are not provided at all. """ from __future__ import absolute_import, division import time import struct from zope.interface import implementer from twisted.internet import protocol, interfaces from twisted.python.compat import _PY3 class Echo(protocol.Protocol): """As soon as any data is received, write it back (RFC 862)""" def dataReceived(self, data): self.transport.write(data) class Discard(protocol.Protocol): """Discard any received data (RFC 863)""" def dataReceived(self, data): # I'm ignoring you, nyah-nyah pass @implementer(interfaces.IProducer) class Chargen(protocol.Protocol): """Generate repeating noise (RFC 864)""" noise = r'@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ !"#$%&?' def connectionMade(self): self.transport.registerProducer(self, 0) def resumeProducing(self): self.transport.write(self.noise) def pauseProducing(self): pass def stopProducing(self): pass class QOTD(protocol.Protocol): <|fim_middle|> class Who(protocol.Protocol): """Return list of active users (RFC 866)""" def connectionMade(self): self.transport.write(self.getUsers()) self.transport.loseConnection() def getUsers(self): """Return active users. Override in subclasses.""" return "root\r\n" class Daytime(protocol.Protocol): """Send back the daytime in ASCII form (RFC 867)""" def connectionMade(self): self.transport.write(time.asctime(time.gmtime(time.time())) + '\r\n') self.transport.loseConnection() class Time(protocol.Protocol): """Send back the time in machine readable form (RFC 868)""" def connectionMade(self): # is this correct only for 32-bit machines? result = struct.pack("!i", int(time.time())) self.transport.write(result) self.transport.loseConnection() __all__ = ["Echo", "Discard", "Chargen", "QOTD", "Who", "Daytime", "Time"] if _PY3: __all3__ = ["Echo"] for name in __all__[:]: if name not in __all3__: __all__.remove(name) del globals()[name] del name, __all3__ <|fim▁end|>
"""Return a quote of the day (RFC 865)""" def connectionMade(self): self.transport.write(self.getQuote()) self.transport.loseConnection() def getQuote(self): """Return a quote. May be overrriden in subclasses.""" return "An apple a day keeps the doctor away.\r\n"
<|file_name|>wire.py<|end_file_name|><|fim▁begin|># Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """Implement standard (and unused) TCP protocols. These protocols are either provided by inetd, or are not provided at all. """ from __future__ import absolute_import, division import time import struct from zope.interface import implementer from twisted.internet import protocol, interfaces from twisted.python.compat import _PY3 class Echo(protocol.Protocol): """As soon as any data is received, write it back (RFC 862)""" def dataReceived(self, data): self.transport.write(data) class Discard(protocol.Protocol): """Discard any received data (RFC 863)""" def dataReceived(self, data): # I'm ignoring you, nyah-nyah pass @implementer(interfaces.IProducer) class Chargen(protocol.Protocol): """Generate repeating noise (RFC 864)""" noise = r'@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ !"#$%&?' def connectionMade(self): self.transport.registerProducer(self, 0) def resumeProducing(self): self.transport.write(self.noise) def pauseProducing(self): pass def stopProducing(self): pass class QOTD(protocol.Protocol): """Return a quote of the day (RFC 865)""" def connectionMade(self): <|fim_middle|> def getQuote(self): """Return a quote. May be overrriden in subclasses.""" return "An apple a day keeps the doctor away.\r\n" class Who(protocol.Protocol): """Return list of active users (RFC 866)""" def connectionMade(self): self.transport.write(self.getUsers()) self.transport.loseConnection() def getUsers(self): """Return active users. Override in subclasses.""" return "root\r\n" class Daytime(protocol.Protocol): """Send back the daytime in ASCII form (RFC 867)""" def connectionMade(self): self.transport.write(time.asctime(time.gmtime(time.time())) + '\r\n') self.transport.loseConnection() class Time(protocol.Protocol): """Send back the time in machine readable form (RFC 868)""" def connectionMade(self): # is this correct only for 32-bit machines? result = struct.pack("!i", int(time.time())) self.transport.write(result) self.transport.loseConnection() __all__ = ["Echo", "Discard", "Chargen", "QOTD", "Who", "Daytime", "Time"] if _PY3: __all3__ = ["Echo"] for name in __all__[:]: if name not in __all3__: __all__.remove(name) del globals()[name] del name, __all3__ <|fim▁end|>
self.transport.write(self.getQuote()) self.transport.loseConnection()