def init(self): self.lock = Lock() self.taskManager = [] self.tmpTaskManger = [] self.delayTaskManager = [] self.delayTmpTaskManager = [] self.taskLock = Lock() self.thread = None self.stop = False self.Start()
def registerNewLock(self, bankNum, name, type, number, last): from Lock import Lock bankNum = "bank" + str(bankNum) if self.locks[bankNum] == None: if last == "LAST": self.locks[bankNum] = Lock(name + "," + type + "," + str(number) + ",LAST") else: self.locks[bankNum] = Lock(name + "," + type + "," + str(number)) return (True) else: return (False)
def get_devices(self): '''Get the list of registered locks''' api_url_lock = "https://api.tedee.com/api/v1.15/my/lock" r = requests.get(api_url_lock, headers=self._api_header, timeout=self._timeout) _LOGGER.debug("Locks %s", r.json()) result = r.json()["result"] for x in result: id = x["id"] name = x["name"] isConnected = x["isConnected"] state = x["lockProperties"]["state"] batteryLevel = x["lockProperties"]["batteryLevel"] isCharging = x["lockProperties"]["isCharging"] isEnabledPullSpring =x["deviceSettings"]["pullSpringEnabled"] durationPullSpring =x["deviceSettings"]["pullSpringDuration"] lock = Lock(name, id) lock.set_connected(isConnected) lock.set_state(state) lock.set_battery_level(batteryLevel) lock.set_is_charging(isCharging) lock.set_is_enabled_pullspring(isEnabledPullSpring) lock.set_duration_pullspring(durationPullSpring) self._lock_id = id '''store the found lock in _sensor_list and get the battery_level''' self._sensor_list.append(lock) if self._lock_id == None: raise TedeeClientException("No lock found")
def __init__(self): ## set priviate values self.config = Config(workpath) self.pid = os.getpid() self.pname = 'Scheduler.py' ## logger initial self.loggerInit() ## lock initial self.lockObj = Lock(self.pname, self.pid, self.config.LOCK_DIR, self.config.LOCK_FILE, self.logger) ## debug output self.logger.debug('Scheduler Initial Start') self.logger.debug('[SYS_CFG_DIR][%s]' % (self.config.SYS_CFG_DIR)) self.logger.debug('[LOCK_DIR][%s]' % (self.config.LOCK_DIR)) self.logger.debug('[LOCK_FILE][%s]' % (self.config.LOCK_FILE)) self.logger.debug('[LOG_DIR][%s]' % (self.config.LOG_DIR)) self.logger.debug('[LOG_FILE][%s]' % (self.config.LOG_FILE)) self.logger.debug('[LOG_LEVEL][%s]' % (self.config.LOG_LEVEL)) self.logger.debug('[LOG_MAX_SIZE][%s]' % (self.config.LOG_MAX_SIZE)) self.logger.debug('[LOG_BACKUP_COUNT][%s]' % (self.config.LOG_BACKUP_COUNT)) self.logger.debug('Scheduler Initial Done')
def __init__(self): ## set priviate values self.config = Config(workpath) self.pid = os.getpid() self.pname = 'Asset.py' ## logger initial self.loggerInit() ## lock initial self.lockObj = Lock(self.pname, self.pid, self.config.LOCK_DIR, self.config.LOCK_FILE, self.logger) ## debug output self.logger.debug('Asset Initial Start') self.logger.debug('[SYS_CIS][%s]' % (self.config.SYS_CIS)) self.logger.debug('[SYS_SAVE_CSV][%s]' % (self.config.SYS_SAVE_CSV)) self.logger.debug('[SYS_CSV_DIR][%s]' % (self.config.SYS_CSV_DIR)) self.logger.debug('[MQ_SERVERS][%s]' % (self.config.MQ_SERVERS)) self.logger.debug('[MQ_PORT][%s]' % (self.config.MQ_PORT)) self.logger.debug('[MQ_QUEUE][%s]' % (self.config.MQ_QUEUE)) self.logger.debug('[SUBPROC_SCRIPTSDIR][%s]' % (self.config.SUBPROC_SCRIPTSDIR)) self.logger.debug('[SUBPROC_TIMEOUT][%s]' % (self.config.SUBPROC_TIMEOUT)) self.logger.debug('[LOCK_DIR][%s]' % (self.config.LOCK_DIR)) self.logger.debug('[LOCK_FILE][%s]' % (self.config.LOCK_FILE)) self.logger.debug('[LOG_DIR][%s]' % (self.config.LOG_DIR)) self.logger.debug('[LOG_FILE][%s]' % (self.config.LOG_FILE)) self.logger.debug('[LOG_LEVEL][%s]' % (self.config.LOG_LEVEL)) self.logger.debug('[LOG_MAX_SIZE][%s]' % (self.config.LOG_MAX_SIZE)) self.logger.debug('[LOG_BACKUP_COUNT][%s]' % (self.config.LOG_BACKUP_COUNT)) self.logger.debug('Asset Initial Done')
def __init__(self): # set priviate values self.config = Config(workpath) self.pid = os.getpid() self.pname = 'CrontabService.py' # logger initial self.logger_init() # lock initial self.lockObj = Lock(self.pname, self.pid, self.config.LOCK_DIR, self.config.LOCK_FILE, self.logger) # debug output self.logger.debug('Crontab Initial') self.logger.debug('[SERVICE_INTERVAL][%s]' % (self.config.SERVICE_INTERVAL)) self.logger.debug('[CRONTAB_CFG_DIR][%s]' % (self.config.CRONTAB_CFG_DIR)) self.logger.debug('[CRONTAB_CFG_FILE][%s]' % (self.config.CRONTAB_CFG_FILE)) self.logger.debug('[MAX_THREADS][%s]' % (self.config.MAX_THREADS)) self.logger.debug('[THREAD_TIMEOUT][%s]' % (self.config.THREAD_TIMEOUT)) self.logger.debug('[LOCK_DIR][%s]' % (self.config.LOCK_DIR)) self.logger.debug('[LOCK_FILE][%s]' % (self.config.LOCK_FILE)) self.logger.debug('[LOG_DIR][%s]' % (self.config.LOG_DIR)) self.logger.debug('[LOG_FILE][%s]' % (self.config.LOG_FILE)) self.logger.debug('[LOG_LEVEL][%s]' % (self.config.LOG_LEVEL)) self.logger.debug('[LOG_MAX_SIZE][%s]' % (self.config.LOG_MAX_SIZE)) self.logger.debug('[LOG_BACKUP_COUNT][%s]' % (self.config.LOG_BACKUP_COUNT)) return (None)
class Microprocessor(Receiver): in_0 = KeyboardPanel() out_0 = LCD() out_1 = Bell() out_2 = Lock() def __init__(self): self.olh = OpenLockHandler(self) self.clh = ClosedLockHandler(self) self.pkh = PassKeyHandler(self) self.ckh = CtrlKeyHandler(self) self.pkch = PassKeyChangeHandler(self) self.cbh = CallButtonHandler(self) self.pkah = PassKeyAcceptHandler(self.pkh, self) self.ckah = PassKeyAcceptHandler(self.ckh, self) self.cbh.set_next(self.clh).set_next(self.pkh).set_next( self.olh).set_next(self.ckh).set_next(self.ckh).set_next(self.pkch) def receive_signal(self, signal): signal = self.in_0.invoke() self.cbh.handle(signal) self.out_0.receive_signal(signal) def procedure(self): self.out_2.receive_signal(None) print(f"Lock: {self.out_2.state.info}")
def __write(self, op): if (self.TransactionTable[op.tid].state == "BLOCKED"): self.LockTable[op.itemName].waitingOperations.append(op) print "Transaction %s already %s"%(self.TransactionTable[op.tid], self.TransactionTable[op.tid].state) elif (self.TransactionTable[op.tid].state == "ABORTED"): print "Transaction %s already %s"%(self.TransactionTable[op.tid], self.TransactionTable[op.tid].state) else: if self.LockTable.has_key(op.itemName): if self.LockTable[op.itemName].readlockedTIDS: for _tid in self.LockTable[op.itemName].readlockedTIDS: self.handleWaitDie(op, _tid) elif self.LockTable[op.itemName].writeLockTID is not None: self.handleWaitDie(op, self.LockTable[op.itemName].writeLockTID) else: self.writeLock(op) else: # print "Creating new WRITE LockTable Record for %s"%op.itemName new_lock = Lock(itemName=op.itemName, lockState="WRITE", readLockedTIDS=[], \ writeLockTID=op.tid, waitingOperations=[]) self.LockTable.update({ op.itemName:new_lock }) self.writeLock(op)
def __read(self, op): if (self.TransactionTable[op.tid].state == "BLOCKED"): self.LockTable[op.itemName].waitingOperations.append(op) print "Transaction %s already %s"%(self.TransactionTable[op.tid], self.TransactionTable[op.tid].state) elif (self.TransactionTable[op.tid].state == "ABORTED"): print "Transaction %s already %s"%(self.TransactionTable[op.tid], self.TransactionTable[op.tid].state) else: if self.LockTable.has_key(op.itemName): # print "%s already %s locked by T%s"%(op.itemName, self.LockTable[op.itemName].lockState, self.LockTable[op.itemName].readlockedTIDS) if self.LockTable[op.itemName].lockState == "WRITE": # print "Handle Wait Dies" self.handleWaitDie(op, self.LockTable[op.itemName].writeLockTID) print "Transaction T%s %s"%(self.TransactionTable[op.tid], self.TransactionTable[op.tid].state) else: print "T%s readlocks %s"%(op.tid,op.itemName) self.readLock(op) else: print "T%s readlocks %s"%(op.tid,op.itemName) new_lock = Lock(itemName=op.itemName, lockState="READ", readLockedTIDS=[op.tid], writeLockTID=None, waitingOperations=[]) self.LockTable.update({ op.itemName:new_lock }) self.readLock(op)
def create_lock(self, cur_dir, ami_path, exclusive): if ami_path == '': if cur_dir == None: ami_path = "SYS:" else: ami_path = cur_dir.ami_path else: ami_path = self.path_mgr.ami_abs_path(cur_dir, ami_path) sys_path = self.path_mgr.ami_to_sys_path(cur_dir, ami_path, searchMulti=True) name = self.path_mgr.ami_name_of_path(cur_dir, ami_path) if sys_path == None: log_lock.info("lock '%s' invalid: no sys path found: '%s'", name, ami_path) return None exists = os.path.exists(sys_path) if not exists: log_lock.info( "lock '%s' invalid: sys path does not exist: '%s' -> '%s'", name, ami_path, sys_path) return None lock = Lock(name, ami_path, sys_path, exclusive) self._register_lock(lock) return lock
def get_lock_list(self, oplocks, locktypes, opname, params): locks = [] requiredLocks = self.getlocks(opname, oplocks) for r in requiredLocks: for t in locktypes: if r["name"] == t["name"]: paramValues = [params[t["param"]]] lockname = "_".join([t["name"]] + paramValues) locktype = LockType(t["name"], t["param"], t["placement"]) newlock = Lock(lockname, locktype, r["mode"]) locks += [newlock] return locks
def setLocksAfterLoading(self): lines = self.codes["bank1"]["bank_configurations"].code.split("\n") for line in lines: if line.startswith("*"): continue else: if line.split("=")[0] == "bank1": self.kernel = line.split("=")[1].replace("\n", "").replace( "\r", "") else: from Lock import Lock self.locks[line.split("=")[0]] = Lock( line.split("=")[1].replace("\n", "").replace("\r", ""))
def init(self, addr, delegate): self.__addr = addr self.__delegate = delegate if delegate.SetSockServer: delegate.SetSockServer(self) self.__clientObj = [] self.__listenSock = None self.__eventSendSock = None self.__eventClient = None self.__threadEvent = threading.Event() self.__threadState = ThreeState.INIT self.__tmpClientObj = [] #上锁 self.__lock = Lock()
def get_by_b_addr(self, b_addr, none_if_missing=False): # current dir lock if b_addr == 0: (cur_dev, cur_path) = self.path_mgr.get_cur_path() ami_path = cur_dev + ":" + cur_path sys_path = self.path_mgr.ami_to_sys_path(ami_path) return Lock("local", ami_path, sys_path) elif self.locks_by_b_addr.has_key(b_addr): return self.locks_by_b_addr[b_addr] else: if none_if_missing: return None else: raise VamosInternalError("Invalid File Lock at b@%06x" % b_addr)
def accepting_connections(): close_connections() while True: try: conn, address = s.accept() s.setblocking(1) # prevents timeout try: device_type = conn.recv(201480) if (str(device_type) == "b'keypad_code'"): my_uid = conn.recv(201480) lock_uid = conn.recv(201480) new_Keypad = Keypad(address, conn, lock_uid, my_uid) keypad_list.append(new_Keypad) queue.put(3) create_workers(ADD_WORKER) print("Keypad has been established :" + address[0]) elif (str(device_type) == "b'lock_code'"): device_code = conn.recv(201480) my_uid = conn.recv(201480) keypad_uid = conn.recv(201480) new_Lock = Lock(address, conn, device_code, keypad_uid, my_uid) lock_list.append(new_Lock) print("Lock has been established :" + address[0]) elif (str(device_type) == "b'web_interface'"): global web_interface web_interface = Web_Interface(address, conn) queue.put(5) create_workers(ADD_WORKER) print("Web Interface has been established :" + address[0]) else: print("Unable to recognize incoming device") except: print("Something went wrong in obtaining a device code") except: print("Error accepting connections")
def get_devices(self): '''Get the list of registered locks''' api_url_lock = "https://api.tedee.com/api/v1.15/my/lock" r = requests.get(api_url_lock, headers=self._api_header, timeout=self._timeout) _LOGGER.debug("Locks %s", r.json()) result = r.json()["result"] for x in result: id = x["id"] name = x["name"] self._lock_id = id '''store the found lock in _sensor_list and get the battery_level''' self._sensor_list.append(Lock(name, id)) self.get_battery(id) if self._lock_id == None: raise TedeeClientException("No lock found")
def addJob(self, jobType, jobWeight=1): host, xWeight = self.getNextHost(jobWeight) xLock = Lock(os.path.join(self.JobDir, "lock-" + host)) xLock.getLock() try: hostDir = os.path.join(self.JobDir, 'Host.' + host) if not os.path.exists(hostDir): try: os.mkdir(hostDir) except: pass jFile = open(os.path.join(hostDir, 'JOB.' + jobType), "w") jFile.write(str(jobWeight)) jFile.close() self.updateHost(host) time.sleep(1) except: pass print 'ADDED JOB:', jobType, ':', jobWeight, '===>', host return host, xWeight
def getMachineId(self): WINDOW = xbmcgui.Window(10000) clientId = WINDOW.getProperty("client_id") if clientId != None and clientId != "": return clientId # we need to load and or generate a client machine id __addon__ = self.addon __addondir__ = xbmc.translatePath(__addon__.getAddonInfo('path')) machine_guid_lock_path = os.path.join(__addondir__, "machine_guid.lock") machine_guid_path = os.path.join(__addondir__, "machine_guid") clientId = "" try: lock = Lock(machine_guid_lock_path) locked = lock.acquire() if locked: fd = os.open(machine_guid_path, os.O_CREAT | os.O_RDWR) clientId = os.read(fd, 256) if len(clientId) == 0: uuid = uuid4() clientId = str("%012X" % uuid) self.logMsg("ClientId saved to FILE: %s" % clientId, 2) os.write(fd, clientId) os.fsync(fd) os.close(fd) self.logMsg("ClientId saved to WINDOW: %s" % clientId, 1) WINDOW.setProperty("client_id", clientId) finally: lock.release() return clientId
def getMachineId(self): WINDOW = xbmcgui.Window( 10000 ) clientId = WINDOW.getProperty("client_id") if(clientId != None and clientId != ""): return clientId # we need to load and or generate a client machine id __addon__ = xbmcaddon.Addon(id='plugin.video.xbmb3c') __addondir__ = xbmc.translatePath( __addon__.getAddonInfo('path')) machine_guid_lock_path = os.path.join(__addondir__, "machine_guid.lock") machine_guid_path = os.path.join(__addondir__, "machine_guid") clientId = "" try: lock = Lock(machine_guid_lock_path) locked = lock.acquire() if(locked == True): fd = os.open(machine_guid_path, os.O_CREAT|os.O_RDWR) clientId = os.read(fd, 256) if(len(clientId) == 0): uuid = uuid4() clientId = str("%012X" % uuid) xbmc.log("CLIENT_ID - > Client ID saved to FILE : " + clientId) os.write(fd, clientId) os.fsync(fd) os.close(fd) xbmc.log("CLIENT_ID - > Client ID saved to WINDOW : " + clientId) WINDOW.setProperty("client_id", clientId) finally: lock.release() return clientId
def __init__(self): ## set priviate values self.config = Config(workpath) self.pid = os.getpid() self.pname = 'ETL.py' ## logger initial self.loggerInit() ## lock initial self.lockObj = Lock( self.pname, self.pid, self.config.LOCK_DIR, self.config.LOCK_FILE, self.logger) ## debug output self.logger.debug('ETL Initial Start') self.logger.debug('[SYS_BUFFER_SIZE][%s]' % (self.config.SYS_BUFFER_SIZE)) self.logger.debug('[SYS_BUFFER_WAIT][%s]' % (self.config.SYS_BUFFER_WAIT)) self.logger.debug('[MQ_SERVER][%s]' % (self.config.MQ_SERVER)) self.logger.debug('[MQ_PORT][%s]' % (self.config.MQ_PORT)) self.logger.debug('[MQ_QUEUE][%s]' % (self.config.MQ_QUEUE)) self.logger.debug('[MARIADB_HOST][%s]' % (self.config.MARIADB_HOST)) self.logger.debug('[MARIADB_PORT][%s]' % (self.config.MARIADB_PORT)) self.logger.debug('[MARIADB_USER][%s]' % (self.config.MARIADB_USER)) self.logger.debug('[MARIADB_PASSWORD][%s]' % (self.config.MARIADB_PASSWORD)) self.logger.debug('[MARIADB_DATABASE][%s]' % (self.config.MARIADB_DATABASE)) self.logger.debug('[LOCK_DIR][%s]' % (self.config.LOCK_DIR)) self.logger.debug('[LOCK_FILE][%s]' % (self.config.LOCK_FILE)) self.logger.debug('[LOG_DIR][%s]' % (self.config.LOG_DIR)) self.logger.debug('[LOG_FILE][%s]' % (self.config.LOG_FILE)) self.logger.debug('[LOG_LEVEL][%s]' % (self.config.LOG_LEVEL)) self.logger.debug('[LOG_MAX_SIZE][%s]' % (self.config.LOG_MAX_SIZE)) self.logger.debug( '[LOG_BACKUP_COUNT][%s]' % (self.config.LOG_BACKUP_COUNT)) self.logger.debug('ETL Initial Done')
#!/usr/bin/env python3 from Lock import Lock from time import sleep # Usage try: lock = Lock("Worker") lock.acquire() print("fun1 starting") for loop in range(1, 5): print("Fun1 Working {}".format(loop)) sleep(1) print("fun1 finished") finally: print("Releasing Lock") lock.release()
def run(self): ret = 0 try: ret = os.system('rfcp '+self.castorFile+' '+self.localFile) except: ret = 1 if ret != 0: print "ERROR copying rawRefFile ", self.castorFile, ' to ', self.localFile print " rfcp returned: ", ret return def getRawRefs(): import PerfSuiteRawRef threadList = [] if not os.path.exists(PerfSuiteRawRef.rawRefDir): os.makedirs(PerfSuiteRawRef.rawRefDir) for castorDir, refList in PerfSuiteRawRef.referenceFiles.items(): for rem, ref in refList.items(): if os.path.exists(PerfSuiteRawRef.rawRefDir+'/'+ref) : print "Ignoring existing rawRefFile ", ref continue else: t = GetRawRefFile(castorDir+rem,PerfSuiteRawRef.rawRefDir+ref) t.start() threadList.append(t) for t in threadList: t.join() xLock = Lock('prefSuit.rawRef.lock') xLock.getLock(10,1000) getRawRefs()
buildDir = a plat = None try: plat = os.environ["SCRAM_ARCH"] except KeyError: plat = "slc5_ia32_gcc434" # assume this for now ... os.environ[ "SCRAM_ARCH"] = plat # make sure we have it for the others :) if not rel: usage() sys.exit(-1) bmgr = BuildManager(rel, ibdate, ibstamp) bmgr.setDryRun(dryRun) if not buildDir: from Lock import Lock lock = Lock(bmgr.topBuildDir + '/buildLock') if not lock: print 'WARNING: Another build is still running on ' + config.getHostName( ) + ' for release cycle ' + rel else: bmgr.checkout() bmgr.startBuild(buildDir) else: bmgr.startBuild(buildDir) sys.exit(0)
import cv2 import base64 import datetime from tkinter import * from PIL import Image, ImageTk from FaceRecognition import recognize import os from Lock import Lock import time device = cv2.VideoCapture(0) lock = Lock(18) root = Tk() root.geometry("500x350") lmain = Label(root) lmain.pack() lstatus = Label(root) lstatus.pack(side="top") def show_frame(): _, frame = device.read() frame = cv2.flip(frame, 1) cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA) cv2image = cv2.resize(cv2image, (300, 250)) img = Image.fromarray(frame) imgtk = ImageTk.PhotoImage(image=img) lmain.imgtk = imgtk lmain.configure(image=imgtk) lmain.after(10, show_frame)
def __init__(self): """Class constructor""" self.lock = Lock() self.riches = random.randint(100, 1000) self.is_cracked = False
def getLock(buildpath): return Lock(os.path.join(buildpath, 'lock'), True, 60 * 60 * 20)
import time from urlparse import urlparse from itchat.itchat import itchat from constdata import const import os #from tlrobot import TlRobot from protocal import protocal import json import copy from datetime import datetime import requests import threadpool from Lock import Lock, AutoLock l = Lock() def M(): AutoLock(l) M() def x(hh): #AutoLock(l) print "hello " + hh pool = threadpool.ThreadPool(10)
def __init__(self, id): self.sid = id self.variables = {} self.status = 0 # active = 0, failed = 1 self.init_variables() self.locks = Lock(self.variables)
from CheckFaceService import CheckFaceService from Lock import Lock from ButtonController import ButtonController from TaskManager import taskManager from PasswordController import PasswordController #from PCButtonController import PCButtonController from HistoryController import HistoryController from BulbController import bulbController import config historyController = HistoryController(config.USER_EMAIL, config.USER_PASSWORD, config.EQUIPMENT_NAME) lock = Lock() buttonController = ButtonController() PasswordController = PasswordController() checkFaceService = CheckFaceService() checkFaceService.check_success_task = lock.open_door checkFaceService.record_task = historyController.AddRecord taskManager.add_task(checkFaceService.model.update,2) taskManager.add_task(buttonController.password_controller.update,3) taskManager.add_task(checkFaceService.camera.CatchImage,0.1) buttonController.star_task = checkFaceService.start_check buttonController.password_correct_task = lock.open_door buttonController.add_record_task = historyController.AddRecord buttonController.camera = checkFaceService.camera buttonController.enable()
import socket from vectorizer import Vectorizer from Lock import Lock # Determine which machine the code is running on # myrtle is the only machine capable of running on GPU backend = 'cpu' cores = 1 if socket.gethostname() == 'myrtle': backend = 'gpu' cores = 16 converter = Vectorizer(backend=backend, cores=cores) backend_lock = Lock() def get_all_vecs(img_paths): if backend_lock.is_locked(): backend_lock.lock() img_vector_dict, failed_images = converter.get_batch_attribute_vectors( img_path_array=img_paths) backend_lock.unlock() return img_vector_dict, failed_images else: return {}, {img: 'Backend busy: Request ignored' for img in img_paths} def get_vecs_with_NSEW(img_paths): if backend_lock.is_locked(): backend_lock.lock()