class Process(): # class variables # lock, logger and loader type m_lock = "" m_logger = "" m_loaderType = "" # Picard PG object m_report_pg = "" m_report_nz = "" def __init__(self, configFile): """ Purpose: Constructor :param self: class object itself :param configFile: Configuration file to use """ # Initialize global logger object self.m_logger = Logger(logging.INFO, configFile) self.m_logger.addFileHandler(logging.DEBUG) try: # Add generic information fname = inspect.getfile(inspect.currentframe()) fpath = os.path.dirname(os.path.abspath(fname)) self.m_logger.addGenericInfo(fpath + "/" + fname) # Create NZ Data Warehouse object self.m_report_nz = Netezza(configFile, self.m_logger) self.m_report_nz.initDatabase(os.environ['NZ_USER'], os.environ['NZ_PASSWD'], os.environ['NZ_HOST'], os.environ['NZ_DATABASE'], os.environ['NZ_PORT']) # Create Picard Postgres Datamart object self.m_report_pg = Postgre(configFile, self.m_logger) # Create lock for the process self.m_lock = Lock(os.environ['LOCK_FILE'], self.m_logger) # pre and post processing dictionaries initialization self.sql_process_dict = defaultdict(list) except Exception, e: self.m_logger.error( "ERROR: Unable to initialize the process due to: %s" % str(e)) if self.m_reportpg: self.m_reportpg.closeConnection() if self.m_lock: self.m_lock.remove() sys.exit("ERROR: Unable to initialize the process due to: %s" % str(e))
def __init__(self, configFile): """ Purpose: Constructor :param self: class object itself :param configFile: Configuration file to use """ # Initialize global logger object self.m_logger = Logger(logging.INFO, configFile) self.m_logger.addFileHandler(logging.DEBUG) try: # Add generic information fname = inspect.getfile(inspect.currentframe()) fpath = os.path.dirname(os.path.abspath(fname)) self.m_logger.addGenericInfo(fpath + "/" + fname) # export all the values from config into environment configObject = configuration(configFile, True) # Create Adama replica PG db object self.m_adamapg = Postgre(os.environ['adama_pg'], self.m_logger) # Create Picard Postgres Datamart object self.m_picardpg = Postgre(os.environ['picard_pg'], self.m_logger) # Create lock for the process self.m_lock = Lock(os.environ['LOCK_FILE'], self.m_logger) # loader type self.m_loaderType = self.getloaderType() # process name self.process_name = os.environ['process_name'] self.m_logger.info("Initializing the process, %s" % self.process_name) except Exception, e: self.m_logger.error( "ERROR: Unable to initialize the process due to: %s" % str(e)) self.updateProcessStatus("F") if self.m_adamapg: self.m_adamapg.closeConnection() if self.m_picardpg: self.m_picardpg.closeConnection() if self.m_lock: self.m_lock.remove() sys.exit("ERROR: Unable to initialize the process due to: %s" % str(e))
class Process(): # class variables # lock, logger and loader type m_lock = "" m_logger = "" m_loaderType = "" # Picard PG object m_report_pg = "" m_report_nz = "" def __init__(self, configFile): """ Purpose: Constructor :param self: class object itself :param configFile: Configuration file to use """ # Initialize global logger object self.m_logger = Logger(logging.INFO, configFile) self.m_logger.addFileHandler(logging.DEBUG) try: # Add generic information fname = inspect.getfile(inspect.currentframe()) fpath = os.path.dirname(os.path.abspath(fname)) self.m_logger.addGenericInfo(fpath + "/" + fname) # Create NZ Data Warehouse object self.m_report_nz = Netezza(configFile, self.m_logger) self.m_report_nz.initDatabase(os.environ['NZ_USER'], os.environ['NZ_PASSWD'], os.environ['NZ_HOST'], os.environ['NZ_DATABASE'], os.environ['NZ_PORT']) # Create Picard Postgres Datamart object self.m_report_pg = Postgre(configFile, self.m_logger) # Create lock for the process self.m_lock = Lock(os.environ['LOCK_FILE'], self.m_logger) # pre and post processing dictionaries initialization self.sql_process_dict = defaultdict(list) except Exception, e: self.m_logger.error("ERROR: Unable to initialize the process due to: %s" % str(e)) if self.m_reportpg: self.m_reportpg.closeConnection() if self.m_lock: self.m_lock.remove() sys.exit("ERROR: Unable to initialize the process due to: %s" % str(e))
def __init__(self, FPGAReader): DemoEngine.SceneBase.__init__(self, 800, 480) #Lock colors: lockScreen = pygame.Surface(self.LockSize) self.lock = Lock.Lock(lockScreen, self) #Random bits: rand = pygame.Surface(self.RandomBitsSize) self.randScreen = RandScreen.RandScreen(rand, FPGAReader, self) randT = pygame.Surface(self.RandomTitleSize) self.randTitle = RandScreenButtons.RandScreenButtons( randT, self.randScreen, self, self.RandomTitlePos) #Live data: liveScreen = pygame.Surface(self.LiveSize) self.liveData = LiveData.LiveData(liveScreen, FPGAReader, self) #Graph: graphScreen = pygame.Surface(self.GraphSize) self.graph = Graph.Graph(graphScreen, FPGAReader, self, self.GraphPos) #Bounds button: boundScreen = pygame.Surface(self.BoundButSize) self.boundButton = BoundButton.BoundButton(boundScreen, FPGAReader, self) #ROSel: RSScreen = pygame.Surface(self.RSSize) self.RS = RS.RS(RSScreen, FPGAReader, self) #Lock light: lockLightScreen = pygame.Surface(self.LockLightSize) self.lockLight = Light.Light(lockLightScreen, 'Lock', FPGAReader.getLock, self) #Not found light: nfLightScreen = pygame.Surface(self.NFLightSize) f = lambda: not (FPGAReader.getFound()) self.nfLight = Light.Light(nfLightScreen, 'Found', f, self) #FPGA reader: self.FPGAReader = FPGAReader
def data_based_on_control_type(self, control_type, data): ''' Process the data based on the control type ''' if control_type == "free form": return data if control_type == "valid": byte_stream = self.string_to_byte_stream(data) lock = Lock.Lock(byte_stream, 1) byte_stream_string = self.byte_stream_to_string( lock.get_real_key()) self.save_patterns.append(byte_stream_string) return byte_stream_string if control_type == "valid but extra": byte_stream = self.string_to_byte_stream(data) lock = Lock.Lock(byte_stream, 1) key = lock.get_real_key() key.append(random.randrange(0, 255)) byte_stream_string = self.byte_stream_to_string(key) return byte_stream_string if control_type == "valid but short": byte_stream = self.string_to_byte_stream(data) lock = Lock.Lock(byte_stream, 1) key = lock.get_real_key() del key[-1] byte_stream_string = self.byte_stream_to_string(key) return byte_stream_string if control_type == "random": length = random.randrange(1, 1000) + 1024 byte_stream = bytearray() for index in range(length): byte_stream.append(random.randrange(0, 255)) byte_stream_string = self.byte_stream_to_string(byte_stream) return byte_stream_string print("control file error - unknow control type: " + control_type) exit(-1)
def __init__(self, configFile): """ Purpose: Constructor :param self: class object itself :param configFile: Configuration file to use """ # Initialize global logger object self.m_logger = Logger(logging.INFO, configFile) self.m_logger.addFileHandler(logging.DEBUG) try: # Add generic information fname = inspect.getfile(inspect.currentframe()) fpath = os.path.dirname(os.path.abspath(fname)) self.m_logger.addGenericInfo(fpath + "/" + fname) # export all the values from config into environment configObject = configuration(configFile, True) # Create Adama replica PG db object self.m_adamapg = Postgre(os.environ['adama_pg'], self.m_logger) # Create Picard Postgres Datamart object self.m_picardpg = Postgre(os.environ['picard_pg'], self.m_logger) # Create lock for the process self.m_lock = Lock(os.environ['LOCK_FILE'], self.m_logger) # loader type self.m_loaderType = self.getloaderType() # process name self.process_name = os.environ['process_name'] self.m_logger.info("Initializing the process, %s" % self.process_name ) except Exception, e: self.m_logger.error("ERROR: Unable to initialize the process due to: %s" % str(e)) self.updateProcessStatus("F") if self.m_adamapg: self.m_adamapg.closeConnection() if self.m_picardpg: self.m_picardpg.closeConnection() if self.m_lock: self.m_lock.remove() sys.exit("ERROR: Unable to initialize the process due to: %s" % str(e))
def run_server(self): ''' Run Server method - this starts the server ''' print("bluetooth RFCOMM server is listening") last_seed = 0 lock = None while True: client = None try: client, address = self.server_socket.accept() print("Connection accepted") data = client.recv(1024) if data: if lock is None: print( "Making a lock - this should fail to authenticate") lock = Lock.Lock(data, last_seed) else: print("Checking a new incoming key") lock.check_another_key(data) if lock.is_locked(): print("Data is not of the expected pattern") client.send("Authentication Failed") else: print("Data pattern is acceptable") self.switch.press() client.send("Command Successful") client.close() # close the socket connection except KeyboardInterrupt: print("Closing socket and exiting") if client: client.close() break except Exception as err: print(err) print("Closing socket") client.close() self.server_socket.close()
j.setState( states.getJSONObject( j.id ) ) jobs[j.id] = j for i in startlist: jobs[i].start() for i in stoplist: jobs[i].stop() if lst: for i in jobs: print "Job:\t+" jobs[i].dump( " \t| ", " \t|- " ) if run: l = Lock( config.getString( "lockfile" ) ) if not l.lock(): print "busy" quit() for i in jobs: j = jobs[i] if j.pending(): subprocess.call( [ "/bin/sh", "-c", j.cmd ] ) j.done() outstate = JSONObject() for i in jobs: j = jobs[i] outstate.put( j.id, j.getState() ) savejson( statefn, outstate )
def writeInfo(image, json): Lock.waitforlock("info.json") Lock.lockfile("info.json") info = open("info.json", "w") info.seek(0) info.write(json) info.truncate() info.close() Lock.unlockfile("info.json") Lock.waitforlock("target.png") Lock.lockfile("target.png") cv2.imwrite( "target.png", cv2.resize(bgr, (bgr.shape[1] / SCALE_FACTOR, bgr.shape[0] / SCALE_FACTOR)), params) Lock.unlockfile("target.png")
def writeInfo(image, json): Lock.waitforlock("info.json") Lock.lockfile("info.json") info = open("info.json", "w") info.seek(0) info.write(json) info.truncate() info.close() Lock.unlockfile("info.json") Lock.waitforlock("target.png") Lock.lockfile("target.png") cv2.imwrite("target.png", cv2.resize(bgr, (bgr.shape[1]/SCALE_FACTOR, bgr.shape[0]/SCALE_FACTOR)), params) Lock.unlockfile("target.png")
class HCE_MFRC522_Interface: READER = None KEY = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF] BLOCK_ADDRS = [8, 9, 10] ANDROID_AID = [0xF0, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06] ANDROID_ADPU = [0x00, 0xB0, 0x00, 0x00, 0x0F, 0xBE, 0xEF] CurrentCommand = None QUIT = 1 CREATE = 2 CREATE_TEMP = 3 SUCCESS = 1 Device_Serial = None PIN = None Veh_Name = None VehID = None Key = None counter = 0 lock = Lock.Lock() QB = DB.DBQueryBuilder() def get_bytes(self, s): lst = [] for ch in s: hv = ord(ch) lst.append(int(float(hv))) #print("Bytes: "+str(lst)) return lst def __init__(self): self.READER = MFRC522.MFRC522() def addLoop(self): id = 0 while 1: id, test = self.addLoopC() while not id: id, test = self.addLoopC() if (id == None): id = 0 #print("\n\n\nWaiting") pause.sleep(1) #print("Touch NFC\n\n\n") return id def write(self): id, test = self.write_no_block() return id def HCE_write(self): id = self.HCE_basics() if (id == self.SUCCESS): self.counter = self.counter + 1 #print("Card Authorised") if self.CurrentCommand == None: ret = self.HCE_default() if (ret != self.SUCCESS): IO.out("(" + str(self.counter) + ".)Communication failed please retouch device") return ret elif (len(self.CurrentCommand) > 0): if (self.CurrentCommand[0] == self.QUIT): return None elif (self.CurrentCommand[0] == self.CREATE): ret = self.HCE_Create() if (ret != self.SUCCESS): IO.out("(" + str(self.counter) + ".)Creation failed please retouch device") return ret elif (self.CurrentCommand[0] == self.CREATE_TEMP): ret = self.HCE_Create_temp() if (ret != self.SUCCESS): IO.out("(" + str(self.counter) + ".)Creation failed please retouch device") return ret else: return self.HCE_default() if (ret != self.SUCCESS): IO.out("(" + str(self.counter) + ".)Communication failed please retouch device") return ret else: return None return None def HCE_Create(self): self.Key = KeyData.KeyData() status, backData = self.HCE_send_AID() if status == self.SUCCESS: self.Device_Serial = re.sub( '[\W_]+', '', str(''.join(chr(i) for i in backData).lower().strip())) text = "create@@" + self.Veh_Name + "@@" + str(self.VehID) status, backData = self.HCE_APDU(self.get_bytes(text)) if status == self.SUCCESS: #print("".join(chr(i) for i in backData)) if ("".join(chr(i) for i in backData).lower() == "dupe".lower()): if (self.QB.user_exists(self.VehID, self.Device_Serial)): IO.out( "> This user already has a valid key, touch another device to add key" ) return None status, backData = self.HCE_APDU(self.get_bytes(text)) self.QB.create_user(self.CurrentCommand[2], self.Device_Serial, self.VehID, self.Key.roller, self.Key.key) IO.out("Successfully created key task") return self.SUCCESS return None def HCE_Create_temp(self): self.Key = KeyData.KeyData() status, backData = self.HCE_send_AID() if status == self.SUCCESS: self.Device_Serial = re.sub( '[\W_]+', '', str(''.join(chr(i) for i in backData).lower().strip())) text = "create@@" + self.Veh_Name + "@@" + str( self.VehID) + "@@" + self.CurrentCommand[3] status, backData = self.HCE_APDU(self.get_bytes(text)) if status == self.SUCCESS: if (re.search( "dupe", re.sub( '[\W_]+', '', str(''.join( chr(i) for i in backData).lower().strip())).lower())): if (self.QB.user_exists(self.VehID, self.Device_Serial)): IO.out( "> This user already has a valid key, touch another device to add key" ) return None #print(text) status, backData = self.HCE_APDU(self.get_bytes(text)) self.QB.create_temp_user(self.CurrentCommand[2], self.Device_Serial, self.VehID, self.Key.roller, self.Key.key, self.CurrentCommand[3]) IO.out("Successfully created key task") return self.SUCCESS return None def HCE_basics(self): (status, TagType) = self.READER.MFRC522_Request(self.READER.PICC_REQALL) if status != self.READER.MI_OK: return 0 (status, uid) = self.READER.MFRC522_Anticoll() if status != self.READER.MI_OK: return 0 id = self.uid_to_num(uid) self.READER.MFRC522_SelectTag(uid) status = self.READER.MFRC522_Authorise_Android() if status != self.READER.MI_OK: return 0 return self.SUCCESS def HCE_default(self): status, backData = self.HCE_send_AID() if status == self.SUCCESS: self.Device_Serial = re.sub( '[\W_]+', '', str(''.join(chr(i) for i in backData).lower().strip())) text = "default@@" + str(self.VehID) status, backData = self.HCE_APDU(self.get_bytes(text)) if status == self.SUCCESS: text = re.sub( '[\W_]+', '', str(''.join(chr(i) for i in backData).lower().strip())) if (re.search("toggle", text)): if (self.QB.verify_temp_key(self.VehID, self.Device_Serial) or self.QB.verify_device_key( self.VehID, self.Device_Serial)): self.lock.toggle() status, backData = self.HCE_APDU( self.get_bytes("default")) return self.SUCCESS else: IO.out("Key not recognised") return None else: IO.out("Device doesn't have a valid key") return self.SUCCESS return None def HCE_send_AID(self): status, backData = self.READER.MFRC522_SelectAID() if status == 2: #print("4.) Failed AID Selection") return 0, [] else: #print("4.) Sussessful AID Selection") status, backData = self.AndroidRetry(status, backData) if status == 2: return 0, [] else: return self.SUCCESS, backData def HCE_APDU(self, apdu): status, backData, sentData = self.READER.MFRC522_ANDROID_ADPU(apdu) if status != self.READER.MI_OK: #print("5.) Failed ADPU Selection") return 0, [] else: #print("5.) Sussessful ADPU Selection") status, backData = self.AndroidRetry(status, backData) if status != self.READER.MI_OK: #print("\t-Failed retry") return 0, [] else: #print("\t-Sussessful retry") return self.SUCCESS, backData def addLoopC(self): (status, TagType) = self.READER.MFRC522_Request(self.READER.PICC_REQALL) if status != self.READER.MI_OK: #print("1.) Failed Request") return 0, None #else: #print("1.) Sussessful Request") (status, uid) = self.READER.MFRC522_Anticoll() if status != self.READER.MI_OK: #print("2.) Failed AntiCollision") return 0, None #else: #print("2.) Sussessful AntiCollision") id = self.uid_to_num(uid) self.READER.MFRC522_SelectTag(uid) status = self.READER.MFRC522_Authorise_Android() if status != self.READER.MI_OK: #print("3.) Failed Authorisation") return 0, None #else: #print("3.) Sussessful Authorisatsion") status, backData = self.READER.MFRC522_SelectAID() if status != self.READER.MI_OK: #print("4.) Failed AID Selection\n") return 0, None #else: #print("4.) Sussessful AID Selection\n") #print( '\tMessage: '.join(chr(i) for i in backData)) #print( '\tReceived: '+str(backData)) if self.AndroidRetry(status, backData) != self.READER.MI_OK: #print("\t-Failed retry") return 0, None #else: #print("\t-Sussessful retry") while (status != 2): self.ANDROID_ADPU[len(self.ANDROID_ADPU) - 1] = backData[len(backData) - 1] status, backData, sentData = self.READER.MFRC522_ANDROID_ADPU( self.ANDROID_ADPU) if status != self.READER.MI_OK: #print("5.) Failed ADPU Selection") #print("\tSendData: "+str(sentData)) return 0, None #else: #print("5.) Sussessful ADPU Selection") #print( '\tReceived: '+str(backData)) if self.AndroidRetry(status, backData) != self.READER.MI_OK: #print("\t-Failed retry") return 0, None #else: #print("\t-Sussessful retry") #print( ''.join(chr(i) for i in backData)) status = self.READER.MFRC522_ANDROID_Deselect() return id, "this" def write_no_block(self): (status, TagType) = self.READER.MFRC522_Request(self.READER.PICC_REQALL) if status != self.READER.MI_OK: #print("1.) Failed Request") return 0, None #else: #print("\n\n1.) Sussessful Request") (status, uid) = self.READER.MFRC522_Anticoll() if status != self.READER.MI_OK: #print("2.) Failed AntiCollision") return 0, None #else: #print("2.) Sussessful AntiCollision") id = self.uid_to_num(uid) self.READER.MFRC522_SelectTag(uid) status = self.READER.MFRC522_Authorise_Android() if status != self.READER.MI_OK: #print("3.) Failed Authorisation") return 0, None #else: #print("3.) Sussessful Authorisatsion") status, backData = self.READER.MFRC522_SelectAID() if status != self.READER.MI_OK: #print("4.) Failed AID Selection") return 0, None #else: #print("4.) Sussessful AID Selection") status, backData = self.AndroidRetry(status, backData) if status == self.READER.MI_ERR: #print("\t-Failed retry") #print( '\tStatus: '+str(status)) #print( '\tbackData: '+str(backData)) return 0, None #else: #print("\t-Sussessful retry") #print( '\tMessage: '+"".join(chr(i) for i in backData)) #print( '\tReceived: '+str(backData)) status, backData, sentData = self.READER.MFRC522_ANDROID_ADPU( self.ANDROID_ADPU) if status != self.READER.MI_OK: #print("5.) Failed ADPU Selection") #print("\tSendData: "+str(sentData)) return 0, None #else: #print("5.) Sussessful ADPU Selection") status, backData = self.AndroidRetry(status, backData) if status == self.READER.MI_ERR: #print("\t-Failed retry") #print( '\tStatus: '+str(status)) #print( '\tbackData: '+str(backData)) return 0, None #else: #print("\t-Sussessful retry") #print( '\tMessage: '+"".join(chr(i) for i in backData)) #print( '\tReceived: '+str(backData)) status = self.READER.MFRC522_ANDROID_Deselect() return id, "this" def uid_to_num(self, uid): n = 0 for i in range(0, 5): n = n * 256 + uid[i] return n def verify_retry(self, status, backData): if status == 2: return 0 if (len(backData) > 0): if backData[0] == 0xF2: return 1 return 0 def AndroidRetry(self, status, backData): while (self.verify_retry(status, backData) == 1): #print("\nAndroid wants more time") status, backData = self.READER.MFRC522_ANDROID_SEND_MESSAGE( backData) return status, backData def ANDROID_Deselect(self): id, test = self.ANDROID_Deselect_Long() while not id: id, test = self.ANDROID_Deselect_Long() return id def ANDROID_Deselect_Long(self): (status, TagType) = self.READER.MFRC522_Request(self.READER.PICC_REQALL) if status != self.READER.MI_OK: return None, None (status, uid) = self.READER.MFRC522_Anticoll() if status != self.READER.MI_OK: return None, None id = self.uid_to_num(uid) self.READER.MFRC522_SelectTag(uid) status = self.READER.MFRC522_ANDROID_Deselect() #print("Status: "+ str(status)) return status, None
def do_GET(s): if s.path == "/target.png": s.send_response(200) s.send_header("Content-Type", "image/png") s.end_headers() Lock.waitforlock("target.png") Lock.lockfile("target.png") f = open("target.png", "rb") s.wfile.write(f.read()) f.close() Lock.unlockfile("target.png") elif s.path == "/crio": s.send_response(200) s.send_header("Content-Type", "application/json") s.send_header("Access-Control-Allow-Origin", "*") s.end_headers() Lock.waitforlock("info.json") Lock.lockfile("info.json") f = open("info.json", "r") Lock.unlockfile("info.json") data = pack_data(f.read()) s.wfile.write(data[0]) s.wfile.write(data[1]) else: s.send_response(200) s.send_header("Content-Type", "application/json") s.send_header("Access-Control-Allow-Origin", "*") s.end_headers() f = open("info.json", "r") s.wfile.write(f.read())
import Lock mutex = Lock() MAX_CONNECTIONS = 20 class Broker(object): def __init__(self, brokerName, brokerIP): self.Name = brokerName self.IP = brokerIP self.num_connections = 0 class BrokerDiscoveryLoadBalancing(object): def __init__(self): self.connection_map = {} self.brokers = [] def register_broker(self, brokerName, brokerIP): self.brokers.append(Broker(brokerName, brokerIP)) self.connection_map[brokerIP] = 0 def insert_connection(self, brokerIP): mutex.acquire() try: self.connection_map[brokerIP] += 1 except: self.connection_map[brokerIP] = 1 mutex.release()