def main(): parser = argparse.ArgumentParser() parser.add_argument("interface", type=str, help="the network interface", choices=interfaces(), ) parser.add_argument("user", type=str, default=os.environ['USER'], nargs='?', help="Your username", ) args = parser.parse_args() inet = ifaddresses(args.interface)[AF_INET] addr = inet[0]['addr'] masked = addr.rsplit('.', 1)[0] ctx = zmq.Context.instance() listen_thread = Thread(target=listen, args=(masked,)) listen_thread.start() bcast = ctx.socket(zmq.PUB) bcast.bind("tcp://%s:9004" % args.interface) print("starting chat on %s:9004 (%s.*)" % (args.interface, masked)) localnode = LocalNode() while True: try: msg = raw_input() #IP/tun0/bat0: freqChange rx/tx message = localnode.name + " freqChange 915000" bcast.send_string(message) #bcast.send_string("%s: %s" % (args.user, msg)) except KeyboardInterrupt: break bcast.close(linger=0) ctx.term() listen_thread.stop()
def getServiceSSL(address, port): socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9150) s = socks.socksocket(socket.AF_INET, socket.SOCK_STREAM) #s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(timeout) try: result = s.connect((address, port)) sock = ssl.wrap_socket(s) print("[*]Connected Sending Data") sock.send("USER " + botnick + " " + botnick + " " + botnick + " " + botnick + "\n") sock.send("NICK " + botnick + "\n") #sock.send("PRIVMSG nickserv :iNOOPE\r\n") #sock.send("LIST\n") #sock.send("JOIN "+ channel +"\n") print("[*]Send complete") recvSubProcess = Thread(target=getReponse, args=(sock, )) recvSubProcess.start() #recvSubProcess.join() time.sleep(5) #sock.send("LIST\n") #time.sleep(2) #sock.send("NAMES #hacking\n") datatosend = str(input("INPUT:")) while "!q" not in datatosend: datatosend = str(input("INPUT:")) sock.send(datatosend + "\n") recvSubProcess.stop() sock.close() except Exception as e: print("[!]Error connectiong to port " + str(port) + " of " + address + " :::::") print e
class Receiver: def __init__(self, ipAddr='127.0.0.1', port = 9001) : self.ipAddr = ipAddr self.port = port self.addr = (ipAddr, port) if LIBLO: self.t = liblo.ServerThread(port) else: self.osc = OSC.ThreadingOSCServer(self.addr) self.t = Thread(target=self.osc.serve_forever) self.t.start() def init(self): pass def listen(self): self.init() def quit(self): if LIBLO: self.t.stop() else: self.osc.close() def add(self, func, addr): if LIBLO: self.t.add_method(addr,None, lambda *f: func(f[1])) else: self.osc.addMsgHandler(addr, lambda *f: func(f[2])) def bind(self, addr,func): self.add(func, addr) def unbind(self, addr): if LIBLO: pass else: self.osc.delMsgHandler(addr) def remove(self, addr): self.unbind(addr)
class webServer: def emit(self,data): #print data for c in cl: c.write_message(data) def runWebServer(self,cntrl,wms): ApiHandler.controller = cntrl SocketHandler.controller = cntrl WMSHandler.wms = wms app = web.Application([ (r'/ws', SocketHandler), (r'/api', ApiHandler), (r'/wms', WMSHandler), (r'/(.*)', web.StaticFileHandler, {'path': "data/web", "default_filename": "index.html"}) ], debug=True) app.listen(5566) self.t = Thread(target=ioloop.IOLoop.instance().start) self.t.daemon = True self.t.start() def stop(): self.t.stop()
class Sceduler: def __init__(self, config): fs = config.get('scheduler', 'fs', 0) dest = config.get('store', 'path', 0) self.ioqueue = Queue() self.iothread = Thread(target=self.ioprocess) self.iothread.daemon = True self.observer = Observer() self.event_handler = IoTask(self.ioqueue, fs, dest) self.observer.schedule(self.event_handler, fs, recursive=True) def ioprocess(self): while True: t = self.ioqueue.get() try: t.process() finally: self.ioqueue.task_done() def start(self): self.observer.start() self.iothread.start() def stop(self): self.observer.stop() self.iothread.stop() def join(self): self.observer.join() self.iothread.join()
class CaptureImage(object): '''A class to capture images from webcam in a separate thread. It allows access to only the recent most image pairs. Methods defined here: @public: start() stop() load_images() @private: _capture_frames() ''' def __init__(self, LEFT_CAM, RIGHT_CAM): ''' Description: Initialise 2 webcams to capture images. Take 20 images to be discared, so that a small amount of time is given for webcams to adjust Parameters: LEFT_CAM - Port number corresponding to left webcam RIGHT_CAM - Port number corresponding to right webcam ''' self.left_capture = cv2.VideoCapture(LEFT_CAM) self.right_capture = cv2.VideoCapture(RIGHT_CAM) if not self.left_capture.isOpened(): self.left_capture.open() if not self.right_capture.isOpened(): self.right_capture.open() self.stopped = False for _ in range(20): ret, self.left_frame = self.left_capture.read() ret, self.right_frame = self.right_capture.read() def start(self): '''Description: Start a thread to capture images ''' self.t = Thread(target=self._capture_frames) self.t.setDaemon(True) self.t.start() def _capture_frames(self): '''Description: A method for thread to loop while capturing left and right images from webcams. The recent most image pairs are stored. ''' while True: if self.stopped: self.t.stop() self.left_capture.close() self.right_capture.close() return ret, self.left_frame = self.left_capture.read() ret, self.right_frame = self.right_capture.read() def load_images(self): '''Description: Returns the recent most left and right image pairs. ''' return self.left_frame, self.right_frame def stop(self): '''Description: Assign a thread termination indicating variable to True. ''' self.stopped = True
def run(): thread = Thread(target=load_model) if check_loadmd == False: thread.start() else: lbl_status1.configure(text="Stop") btn_run.configure(text="Run", bg="#0ac910") thread.stop()
def wrapper(*args, **kwargs): thread = Thread(target=func, args=args, kwargs=kwargs) wrapper.__thread__ = thread try: thread.start() except KeyboardInterrupt: thread.stop() return thread
class ClientServerApp(App): def build(self): self.service = None # self.start_service() self.server = server = OSCThreadServer() server.listen( address=b'localhost', port=3002, default=True, ) server.bind(b'/message', self.display_message) server.bind(b'/date', self.date) self.client = OSCClient(b'localhost', 3000) self.root = Builder.load_string(KV) return self.root def start_service(self): if platform == 'android': service = autoclass(SERVICE_NAME) mActivity = autoclass(u'org.kivy.android.PythonActivity').mActivity argument = '' service.start(mActivity, argument) self.service = service elif platform in ('linux', 'linux2', 'macos', 'win'): from runpy import run_path from threading import Thread self.service = Thread( target=run_path, args=['src/service.py'], kwargs={'run_name': '__main__'}, daemon=True ) self.service.start() else: raise NotImplementedError( "service start not implemented on this platform" ) def stop_service(self): if self.service: self.service.stop() self.service = None def send(self, *args): self.client.send_message(b'/ping', []) def display_message(self, message): if self.root: self.root.ids.label.text += '{}\n'.format(message.decode('utf8')) def date(self, message): if self.root: self.root.ids.date.text = message.decode('utf8')
def main(): controls = ['left', 'right', 'up', 'down'] control_syn = {} for control in controls: control_syn.setdefault(control, []) control_syn['left'].extend(['let', 'left', 'light', 'live', 'laugh']) control_syn['right'].extend( ['right', 'write', 'great', 'fight', 'might', 'ride']) control_syn['up'].extend(['up', 'hop', 'hope', 'out']) control_syn['down'].extend(['down', 'doubt', 'though']) device_list = load_device() stream_reader = audio_helper.StreamReader(device_list[1][0], received_frames) if not stream_reader.initialize(): print("Failed to initialize Stream Reader") speech.close() speech = None return speech = SpeechManager() print('speech config = ' + str(SPEECH_CONFIG)) if not speech.initialize(SPEECH_CONFIG, infer_device='CPU', batch_size=8): print("Failed to initialize ASR recognizer") speech.close() speech = None return stt = Queue() reading_thread = Thread(target=stream_reader.read_stream, \ args=(speech, stt), daemon=True) reading_thread.start() while (True): # if any sound is deciphered from thread then check last 3 words if (stt.qsize() > 0): utterance = stt.get() # print("From Parent: " + utterance) detectEvent(utterance, controls, control_syn) k = cv2.waitKey(1) & 0xFF # press 'q' to exit if k == ord('q'): break stopStream(stream_reader) reading_thread.stop()
class State: def __init__(self): self.game_thread = Thread(target=self.start_game) def start_game_thread(self): self.game_thread.start() def start_game(self): console = blazelib.core.load_console(folder=blazelib.core.BASE_DIR + 'chip8', name="BlazeLib CLI Virtual Console") blazelib.libemu.exec_rom('ibm.ch8', 1, console) def end_game_thread(self): self.game_thread.stop()
def aaa(event): if event.Key == 'Oem_3': global t1 flag = True if flag: falg = False t1 = Thread(target=create_qt5).start() else: t1.stop() t1 = Thread(target=create_qt5).start() return True
class ClientServerApp(App): def build(self): self.service = None # self.start_service() self.server = server = OSCThreadServer() server.listen( address=b'localhost', port=3002, default=True, ) server.bind(b'/message', self.display_message) server.bind(b'/date', self.date) self.client = OSCClient(b'localhost', 3000) self.root = Builder.load_string(KV) return self.root def start_service(self): if platform == 'android': service = autoclass(SERVICE_NAME) mActivity = autoclass(u'org.kivy.android.PythonActivity').mActivity argument = '' service.start(mActivity, argument) self.service = service elif platform in ('linux', 'linux2', 'macos', 'win'): from runpy import run_path from threading import Thread self.service = Thread(target=run_path, args=['src/service.py'], kwargs={'run_name': '__main__'}, daemon=True) self.service.start() else: raise NotImplementedError( "service start not implemented on this platform") def stop_service(self): if self.service: self.service.stop() self.service = None def send(self, *args): self.client.send_message(b'/ping', []) def display_message(self, message): if self.root: self.root.ids.label.text += '{}\n'.format(message.decode('utf8')) def date(self, message): if self.root: self.root.ids.date.text = message.decode('utf8')
def test_events_with_callback(): """Test subscribing to events with a callback handler.""" def callback_handler(message): """Event callback handler.""" global CALLBACK_EVENT_COUNT # pylint: disable=global-statement CALLBACK_EVENT_COUNT += 1 assert 'callback_test_event_' in message['data'] # print('EVENT CALLBACK!! ', message['data'], CALLBACK_EVENT_COUNT) def watcher_function(queue: events.EventQueue, timeout: float): """Function to monitor for events.""" start_time = time.time() while time.time() - start_time < timeout: queue.get() time.sleep(0.1) events.DB.flushall() aggregate_type = 'callback_test' subscriber = 'test_subscriber' event_type = 'test' aggregate_key = 'test:01' # Subscribe to the 'pb' aggregate events with the 'test' subscriber event_queue = events.subscribe(aggregate_type, subscriber, callback_handler) assert subscriber in events.get_subscribers(aggregate_type) # Test using a custom watcher thread for the event loop. thread = Thread(target=watcher_function, args=( event_queue, 2.0, ), daemon=False) thread.start() for _ in range(10): events.publish(aggregate_type, aggregate_key, event_type=event_type, event_data={}) thread.join() assert CALLBACK_EVENT_COUNT == 10 # Test using the provided pubsub subscriber thread thread = event_queue.pubsub().run_in_thread(sleep_time=0.01) for _ in range(10): events.publish(aggregate_type, aggregate_key, event_type=event_type, event_data={}) time.sleep(0.5) thread.stop() assert CALLBACK_EVENT_COUNT == 20
class DetectMouseClick(PyMouseEvent): def __init__(self): PyMouseEvent.__init__(self) self.buttons = {0: False, 1: False, 2: False} def click(self, x, y, button, press): self.buttons[button] = press def start(self): self.thread = Thread(target=self.run) self.thread.start() def stop(self): self.thread.stop()
def main(): threads = [] global dv, linkcontents try: if len(sys.argv) != 2: print "Please check the arguments passed." sys.exit("Usage: ./DistanceVectorRouting.py </Data/file>") # port = int(sys.argv[1]) file = sys.argv[1] filepath = os.getcwd() + "/" + file host = ".".join((".".join(file.split(".")[:1])).split("/")[1:]) port = GetPortNum(host) if not os.path.isfile(filepath): sys.exit("This directory does not exist") print "------------------Starting Distance Vector Algorithm------------------" linkcontents = InitDv(filepath) dv = InitDv(filepath) print "********************Printing Initial Routing costs********************" PrintLink(dv) numofneighbours = GetNumOfNeighbours(filepath) s = socket(AF_INET, SOCK_DGRAM) s.bind(('', port)) broadcast = RepeatedTimer(15, BroadcastThread) threads.append(broadcast) checkfile = Thread(target=CheckCostChange, args=(filepath, )) threads.append(checkfile) checkfile.daemon = True checkfile.start() while True: packet, addr = s.recvfrom(1024) packet = ast.literal_eval(packet) UpdateDv(packet) except KeyboardInterrupt: print " " print "Shutting down Server...." broadcast.stop() checkfile.stop() s.close() sys.exit(0)
def main_thread(): mainthread = Thread() mainthread.start() thread_ = Thread(target=command_thread) thread_.start() import time try: while True: time.sleep(1) if thread_.is_alive() is False: break except KeyboardInterrupt: mainthread.stop() thread_.stop() sys.exit()
class InputPipe: # Constructor # @args : # 1. filepath - path to the input accelerometer data to parse # 2. queue - the Queue object to add the data to. def __init__(self, filepath, queue): self.filepath = filepath self.queue = queue self.thread = None # Start the piping operation def start(self): try: self.thread = Thread(target = self.pipeInput, args = ()) self.thread.daemon = True self.thread.start() except: print('Error: Cannot start piping thread') # Check if the piping operation is still running def isRunning(self): if hasattr(self, 'thread'): return self.thread.isAlive() else: return False # Stop the piping operation def stop(self): if self.thread: self.thread.stop() # Worker function for the thread def pipeInput(self): data = utils.loadAccelCsv(self.filepath) for datapoint in data: self.queue.enqueue(datapoint) # time.sleep(Constants.SAMPLE_PERIOD) # Add an 'end' signal to the pipe to indicate the end of the data stream self.queue.enqueue('end')
class Cliente(object): def __init__(self, idioma, host="localhost", port=5021): self.idioma = idioma self.tradutor = tradutor.Tradutor(self.idioma) self.msg = None self.cliente = socket(AF_INET, SOCK_STREAM) self.send = Send() self.tem_mensagem = False self.processo = Thread(target=self.esperar, args=(self.cliente, self.send, host, port)) self.processo.start() def enviar_msg(self, msg): self.send.put(msg) def esperar(self, tcp, send, host='localhost', port=5020): destino = (host, port) #conecta a um servidor try: tcp.connect(destino) while True: print('Conectado a ', host, '.') #atribui a conexão ao manipulador send.con = tcp while True: #aceita uma mensagem self.msg = tcp.recv(1024) if not self.msg: break except: print("nao foi possivel conectar") kill(getpid(), SIGKILL) self.processo.stop() def pegar_msg(self): if self.msg: return self.tradutor.traduzir(self.msg.decode()) def fechar(self, widget): kill(getpid(), SIGKILL) def resetar(self): self.msg = None
def test_events_with_callback(): """Test subscribing to events with a callback handler.""" def _callback_handler(message): """Event callback handler.""" global CALLBACK_EVENT_COUNT # pylint: disable=global-statement CALLBACK_EVENT_COUNT += 1 assert 'callback_test_event_' in message['data'] # print('EVENT CALLBACK!! ', message['data'], CALLBACK_EVENT_COUNT) def _watcher_function(queue: EventQueue, timeout: float): """Monitor for events.""" start_time = time.time() while time.time() - start_time < timeout: queue.get() time.sleep(0.1) DB.flush_db() object_type = 'callback_test' subscriber = 'test_subscriber' event_type = 'test' object_id = 'test-01' # Subscribe to the 'pb' object events with the 'test' subscriber event_queue = subscribe(object_type, subscriber, _callback_handler) assert subscriber in get_subscribers(object_type) # Test using a custom watcher thread for the event loop. thread = Thread(target=_watcher_function, args=(event_queue, 2.0,), daemon=False) thread.start() for _ in range(10): publish(event_type=event_type, object_type=object_type, object_id=object_id) thread.join() assert CALLBACK_EVENT_COUNT == 10 # Test using the provided pubsub subscriber thread thread = event_queue.pubsub().run_in_thread(sleep_time=0.01) for _ in range(10): publish(event_type=event_type, object_type=object_type, object_id=object_id) time.sleep(0.5) thread.stop() assert CALLBACK_EVENT_COUNT == 20
def start(): print("Add new contact 'nc'") print("See all contacts 'ac'") print("Search for a contact 'sc'") print("Start chat session 'chat'") statics.handler = input() if statics.handler == "nc": name = input("Full name: ") number = input("Telephone number: ") nCObj = open("contacts.txt", "a") nCObj.write(name) nCObj.write(number) nCObj.write("\n") nCObj.close() if statics.handler == "ac": aCObj = open("contacts.txt") for line in aCObj: print(line.rstrip()) aCObj.close() if statics.handler == "sc": searchContact = input("For which contact do you wanna search \n") sCObj = open("contacts.txt", "r") for row in sCObj: if searchContact in row: print("\n--------------------------- \n" + row + "--------------------------- \n") sCObj.close() if statics.handler == "chat": t1 = Thread(target=chat.server) t2 = Thread(target=chat.client) t1.start() t2.start() while t1.is_alive: sleep(1) if statics.message == "exitchat": t2.stop t1.stop()
class Receiver: def __init__(self, ipAddr='127.0.0.1', port = 9001) : self.ipAddr = ipAddr self.port = port self.addr = (ipAddr, port) self.tags = set() if LIBLO: #self.t = liblo.ServerThread(port, proto=liblo.TCP) self.t = liblo.ServerThread(port, proto=liblo.UDP) else: self.osc = OSC.ThreadingOSCServer(self.addr) self.t = Thread(target=self.osc.serve_forever) self.t.start() def init(self): pass def listen(self): self.init() def close(self): self.quit() def quit(self): if LIBLO: self.t.stop(); self.t.free(); gc.collect() else: self.osc.running = False; self.t.join(); self.osc.close(); def add(self, func, tag): if tag in self.tags: return if LIBLO: self.t.add_method(tag,None, lambda *f: func(f[1])) else: self.osc.addMsgHandler(tag, lambda *f: func(f[2])) self.tags.add(tag) def bind(self, tag,func): self.add(func, tag) def unbind(self, tag): if tag not in self.tags: return if LIBLO: pass # self.t.del_method(tag, None) else: self.osc.delMsgHandler(tag) self.tags.remove(tag) def remove(self, tag): self.unbind(tag) def unbind_all(self): for tag in list(self.tags): self.unbind(tag)
def start_timer(fun, interval, *args): def proc(): while not thd.stop: fun(*args) time.sleep(interval) thd = Thread(target=proc) thd.stop = False # 外面可以设置此变量为True,逻辑停止工作函数. thd.start() return thd
def add_thread(self, obj, timeout=timedelta(seconds=1)): thread = Thread(target=obj.start) thread.stop = obj.stop thread.start() start_time = datetime.utcnow() while not obj.is_running: if (start_time + timeout) < datetime.utcnow(): raise TimeoutError() time.sleep(0.01) self._threads.append(thread) return len(self._threads) - 1
class Camera: def __init__(self, port): self.port = port self.cap = cv2.VideoCapture(port) self.latestFrame = np.zeros([480, 640, 3], dtype=np.uint8) self.latestFrame[:, 0:320] = (255, 0, 0) # (B, G, R) self.latestFrame[:, 320:640] = (0, 255, 0) self.latestProcessedFrame = np.zeros( [480, 640, 3], dtype=np.uint8) # Create empty frame def getMJPEGProcessedFrame(self): param = [int(cv2.IMWRITE_JPEG_QUALITY), 15] ret, jpeg = cv2.imencode('.jpg', self.latestProcessedFrame, param) if ret: return jpeg.tobytes() def setBrightness(self, value): os.system("v4l2-ctl -d /dev/video{} --set-ctrl=brightness={}".format( self.port, value)) def setProcessedFrame(self, frame): self.latestProcessedFrame = frame def connected(self): ret, frame = self.cap.read() if self.cap.isOpened(): return True return False def getFrames(self): while Thread.is_alive: ret, frame = self.cap.read() if ret: self.latestFrame = frame def startCap(self): self.capThread = Thread(target=self.getFrames).start() def stopCap(self): if self.capThread: self.capThread.stop()
class PLThread(object): ''' Create a Thread. ''' def __init__(self, plthread="", args=""): self.plthread = plthread self.args = args self.t_thread = "" def create_thread(self): if self.plthread == "": return elif self.args == "": self.t_thread = Thread(target=self.plthread) self.t_thread.start() else: self.t_thread = Thread(target=self.plthread, args=self.args) self.t_thread.start() def stop_thread(self): self.t_thread.stop()
class StreamSocketServerTCP(ThreadingTCPServer): class __Request(StreamRequestHandler): def setup(self): super().setup() self.selfmain.setup(self) def handle(self): super().handle() self.selfmain.handle(self) def finish(self): super().finish() self.selfmain.finish(self) def __init__(self, addr, **kwargs): self.thread = Thread(target=self.serve_forever, daemon=True) self.__Request.selfmain = self self.setup = FunctionType(self.setup.__code__, self.setup.__globals__) self.handle = FunctionType(self.handle.__code__, self.handle.__globals__) self.finish = FunctionType(self.finish.__code__, self.finish.__globals__) super().__init__(addr, self.__Request, True) def start(self): self.thread.start() def stop(self): self.thread.stop() def IsAlive(self): self.thread.is_alive() def __GetDaemon(self) -> bool: return self.thread.daemon def __SetDaemon(self, daemonic:bool): if isinstance(daemonic, bool) != True: return self.thread.daemon = daemonic def __DelDaemon(self): return daemon = property(__GetDaemon, __SetDaemon, __DelDaemon) def setup(self): pass def handle(self): pass def finish(self): pass
def get_networks(iface) -> list: global networks net_list = [] channel_sweeper = Thread(target=channel_sweep, kwargs=dict(iface=iface)) channel_sweeper.start() sniff(prn=callback_ap, iface=iface, timeout=25) channel_sweeper.stop = False channel_sweeper.join(timeout=1) for ssid in networks: params = {'bssid': networks[ssid]['bssid'], 'essid': ssid, 'channel': networks[ssid]['channel']} net_list.append(Network(**params)) return net_list
def mount(config): mountpoint = Path(config['mountpoint']).expanduser() nothreads = config['fuse_nothreads'] mountpoint.mkdir(parents=True, exist_ok=True) tree = Tree(config) if config.get('watch', True): thread = Thread(target=tree.change_watcher).start() else: thread = None logging.info('Not watching for changes in the repository.') logging.info(f'Mounting repository on {mountpoint}') try: FUSE(tree, mountpoint.as_posix(), foreground=True, nothreads=nothreads) except (KeyboardInterrupt, SystemExit): logging.info('Shutting down') if thread: tree.rm_watchers() thread.stop() exit()
class Manager(): def __init__(self, RenderInput, SendOutput, fixargs=None): self.RenderIn = RenderInput self.SendOut = SendOutput self.fixargs = fixargs #prop self.Renderfps = 1 self.OutputThread = None self.NextEmit = None self.Continuity = 0 self.RenderRoulette = RoundRender(RenderInput, fixargs) def Launch(self): self.NextEmit = current_milli_time() if self.OutputThread is None: self.OutputThread = Thread(target=Manager._Emitter, args=(self, )) self.OutputThread.start() def Restart(self): if self.OutputThread is not None: self.OutputThread.stop() self.OutputThread.start() def _Emitter(self): while True: if self.NextEmit > current_milli_time(): msDelta = self.NextEmit - current_milli_time() time.sleep(float(msDelta) / 1000) #print "WAITING" #EmitterRoutine #print "wait " + str(int(1000/float(self.Renderfps))) self.NextEmit = current_milli_time() + int( 1000 / float(self.Renderfps)) data = self.RenderRoulette.get(self.fixargs) #print "[MAIN]" + str(current_milli_time()) self.SendOut(data)
def run_sim(): doc.add_next_tick_callback(partial(reset)) global_parameters = {} param_file = open('./parameters.ini', 'w') global_parameters['population_size'] = int(population_input.value) global_parameters['number_of_generations'] = int(generations_input.value) global_parameters['output_file'] = './results/results_temp.tsv' for parameter, value in global_parameters.items(): param_file.write(parameter + ' = ' + str(value) + '\n') pause_button.disabled = False stop_button.disabled = False start_button.disabled = True global run_thread run_thread = Thread(target=run) run_thread.stop = False run_thread.pause = False run_thread.start()
def start_colours(cycle_mode): api = setup_api(gateway_ip, config_file) dining_room_lamp = get_dining_room_lamp(api) stop_all_colours() colours_to_show = colours if (cycle_mode == 'rainbow_cycle'): colours_to_show = rainbow_colours transition_time = 5 if ('slow' in cycle_mode): transition_time = 30 threads[cycle_mode] = Thread( target=cycle_colours, args=[api, dining_room_lamp, colours_to_show, transition_time]) threads[cycle_mode].stop = False threads[cycle_mode].start()
from threading import Thread import subprocess import os import download_binary config = subprocess.call(["python", "config.py", "--size=720x350"]) if config is 0: download_bin = Thread(target=download_binary.main) download_bin.start() download = subprocess.call(["python", "binary.py", "--size=720x350"]) if download is 0: download_bin.stop() end = subprocess.call(["python", "end.py", "--size=720x350"])
class Cam(): def __init__(self,url): self.stream = requests.get(url, stream = True) self.thread_cancelled = False self.thread = Thread(target = self.run) print "Camara inicializada" def nothing(): pass def start(self): self.thread.start() print "Streaming encendido" def run(self): global points global prom global video bytes = '' # prom = 0 # points = [] cresta = [] fps = 20 capSize =(320,240) codec = cv2.cv.CV_FOURCC('M','J','P','G') # ROJO ILUMINADO lower_blue = np.array((111,68,94)) upper_blue = np.array((180,188,235)) video = cv2.VideoWriter('video.avi',codec,fps,capSize,True) while not self.thread_cancelled: try: bytes+= self.stream.raw.read(1024) a = bytes.find('\xff\xd8') b = bytes.find('\xff\xd9') if a!=-1 and b!=-1: jpg = bytes[a:b+2] bytes = bytes[b+2:] img = cv2.imdecode(np.fromstring(jpg, dtype = np.uint8),cv2.IMREAD_COLOR) frame = cv2.blur(img,(3,3)) hsv = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV) hsv2 = hsv.copy() thresh = cv2.inRange(hsv,lower_blue,upper_blue) thresh = cv2.medianBlur(thresh,7) thresh2 = thresh.copy() countours, hierarchy = cv2.findContours(thresh, cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE) max_area = 0 best_cnt = 0 area = 0 for cnt in countours: area = cv2.contourArea(cnt) if area > max_area: max_area = area best_cnt = cnt M = cv2.moments(best_cnt) cx,cy=0,0 try: cx,cy = int(M['m10']/M['m00']), int(M['m01']/M['m00']) except: f = open('posiciones.txt','wa') print "Streaming terminado" for i in range(0,len(points)-1): f.write(str(points[i][0]) + " " + str(points[i][1]) + "\n") dif = points[0][0] - prom #print dif #print points if (dif < 0): dif = (dif * -1) res = dif *(1.90909090909090909090) int (res) #print res f = open('distancia.txt','wa') f.write( "Diferencia en pixeles: " + str(dif) + "\n" + "Diferencia en cm: " + str(res)) f.close() exit(0) video.release() coord = cx, cy cv2.line(frame,(0,120),(340,120),(0,255,0),1) #guarda las coordenadas si no estan repetidas, si el objeto no se mueve se guarda la misma pocision varias veces # if not (coord in points): if (cx != 0): points.append(coord) w = len(points) #Dibuja la onda senoidal for i in range(0,w-1): cv2.line(frame, (points[i]),(points[i+1]),(255,0,0),1) prom = points[i][1] + prom prom = prom / w int (prom) #Dibuja la linea promedio for i in range (0,w-1): cv2.line(frame, (points[i][0],prom), (points[i+1][0],prom),(255,255,0),1) #Dibuja la ruta que siguio de la posicion inicial a la final cv2.line(frame,(points[0]),(points[w-1]),(255,255,255),1) for i in range (10,w-5): if not (points[i] in cresta): if (points[i-3][1] < points[i][1]) and (points[i+3][1] < points[i][1]): cresta.append(points[i]) o = len(cresta) if (o > 2): for i in range(0,o-1): cv2.line(frame,cresta[i],cresta[i+1],(255,148,148),1) try: video.write(frame) except: print"Hubo algun error" cv2.imshow('Camara',frame) cv2.imshow('Objeto',thresh2) if cv2.waitKey(1) == 1048603: f = open('posiciones.txt','wa') print "Streaming terminado" for i in range(0,len(points)-1): f.write(str(points[i][0]) + " " + str(points[i][1]) + "\n") dif = points[0][0] - prom #print dif #print points if (dif < 0): dif = (dif * -1) res = dif *(1.90909090909090909090) int (res) #print res f = open('distancia.txt','wa') f.write( "Diferencia en pixeles: " + str(dif) + "\n" + "Diferencia en cm: " + str(res)) f.close() exit(0) video.release() except ThreadError: self.thread_cancelled = True cv2.namedWindow('Camara',cv2.CV_WINDOW_AUTOSIZE) cv2.namedWindow('Objeto',cv2.CV_WINDOW_AUTOSIZE) def end_cam(self): global points global prom global video f = open('posiciones.txt','wa') print "Streaming terminado" for i in range(0,len(points)-1): f.write(str(points[i][0]) + " " + str(points[i][1]) + "\n") dif = points[0][0] - prom #print dif #print points if (dif < 0): dif = (dif * -1) res = dif *(1.90909090909090909090) int (res) #print res f = open('distancia.txt','wa') f.write( "Diferencia en pixeles: " + str(dif) + "\n" + "Diferencia en cm: " + str(res)) f.close() exit(0) video.release() self.thread.stop() def is_running(self): return self.thread.isAlive() def shut_down(self): self.thread_cancelled = True while self.thread.isAlive(): time.sleep(1) return True def move_camera(self): abajo = "http://192.168.0.100/command/ptzf.cgi?relative=0810" for i in range(0,3): content = urllib.urlopen(abajo).read()
#---------------------------------------------------------------------------# # run the processes #---------------------------------------------------------------------------# from threading import Thread # Start running the context updater thread updateThread = Thread(target=updatingThread, args=(context,)) updateThread.daemon = True updateThread.start() # Start running the server thread servThread = Thread(target= StartSerialServer(context, framer=ModbusRtuFramer,identity=identity, port='/dev/ttyS0', timeout=0.01, baudrate=9600)) servThread.daemon = True servThread.start() #chill import msvcrt as m def wait(): m.getch() wait() updateThread.stop() servThread.stop()
], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # play music while mplayer.stdout.read1(100): if thread.stop: mplayer.terminate() mplayer.kill() return # start music as subprocess from threading import Thread musicThread = Thread(target=playMusic) musicThread.stop = False musicThread.start() else: musicThread = None ################################################################################################################################## ### ## some stuff that is somehow needed but slated for removal # ################################################################################################################################# # bad code: common variables with modules rooms.story = story chats.story = story # bad code: common variables with modules
class Orchestrator(object): def __init__(self, inboxer=Inboxer(), docker_agent=None): self.inboxer = inboxer self.inboxer.on("received", self.__handle_inbox_received_event) self.docker_agent = docker_agent self.id_to_cpu = {} self.id_to_metadata = {} if self.docker_agent is None: self.docker_agent = DockerAgent() # Setup pending queue self.pending = {} self.pending_thread = Thread(target=self.__process_pending) self.pending_thread.daemon = True self.pending_thread.start() # Clean up the id_to_cpu dict def __clean_container(self, container_id): if container_id in self.id_to_metadata: meta = self.id_to_metadata[container_id] Event.create(topic=meta['topic'], container=meta['container'], timestamp=meta['timestamp'], duration=(int(time() * 1000) - meta['timestamp'])) del self.id_to_metadata[container_id] if container_id in self.id_to_cpu: del self.id_to_cpu[container_id] # Save stat to database def __handle_stat(self, stat, id, topic, container_name): try: read_dt = parser.parse(stat['read']) timestamp = int((time.mktime(read_dt.timetuple()) + (read_dt.microsecond / 1000000.0)) * 1000) memory_usage = float(stat['memory_stats']['usage']) / float( stat['memory_stats']['limit']) Metric.create(topic=topic, container=container_name, timestamp=timestamp, name='memory', value=memory_usage) # Calculate CPU usage. The docker API returns the number of cycles consumed # by the container and the number of cycles consumed by the system. We need # to take the difference over time and divide them to retrieve the usage # percentage. total_usage = float(stat['cpu_stats']['cpu_usage']['total_usage']) system_usage = float(stat['cpu_stats']['system_cpu_usage']) if id in self.id_to_cpu: usage_diff = total_usage - self.id_to_cpu[id]['total'] system_diff = system_usage - self.id_to_cpu[id]['system'] if usage_diff >= 0: usage_pct = usage_diff / system_diff else: usage_pct = 0.0 Metric.create(topic=topic, container=container_name, timestamp=timestamp, name='cpu', value=usage_pct) self.id_to_cpu[id] = {'total': total_usage, 'system': system_usage} except: # We don't want to kill the stat thread, and we don't really mind # if some statistics aren't saved properly pass # Get listing of registered containers filtered by topic def __get_registered_containers(self, topic): return resolve_query( Registration.select().where(Registration.topic == topic)) # Clear the pending queue of a specific topic def __clear_pending(self, topic, container_name): if topic is not None and topic in self.pending: if container_name is not None and container_name in self.pending[ topic]: del self.pending[topic][container_name] # Iterate through the self.pending queue and act on anything queued # that has passed its timer def __process_pending(self): while (True): for_process = [] for topic in self.pending: for container in self.pending[topic]: if self.__get_current_time_in_seconds( ) > self.pending[topic][container]: # It's go time! Pop into array so we can run after the loop # Otherwise modiying the dictionary during runtime is bad (item is # removed from pending immediately upon start of processing) for_process.append({ "topic": topic, "container": container }) # Iterate the array and run the things inside for process in for_process: self.__process(process["topic"], process["container"]) del for_process[:] try: sleep(TIMER_INTERVAL) except KeyboardInterrupt: self.pending_thread.stop() def __process(self, topic, container_name): self.__clear_pending( topic, container_name) # Clear the topic so this isn't hit multiple times # Promote all files in the inbox, delineated by topic, to a directory for # a container to mount; returns a list of created inboxes container_inboxes = self.inboxer.promote_to_container_inbox( topic, str(uuid4())) if container_inboxes is None or len(container_inboxes) == 0: print "There are no container inboxes available for the event run; did something weird happen?" return None for container_inbox in container_inboxes: # container_inbox is the path inboxer promoted to be mounted in the docker container self.docker_agent.pull(container_name) container_id = self.docker_agent.start_container( host_inbox=container_inbox, image_name=container_name, on_terminate=self.__clean_container, topic=topic) self.id_to_metadata[container_id] = { 'topic': topic, 'container': container_name, 'timestamp': int(time() * 1000) } self.docker_agent.stats(container_id, topic, container_name, self.__handle_stat) # Get the current time, in seconds, since epoch def __get_current_time_in_seconds(self): return timegm(gmtime()) # This event handler is executed every time a file is put into the master inbox # The data argument includes a property specify the topic that was appended to def __handle_inbox_received_event(self, data): topic = data["topic"] count = self.inboxer.get_inbox_count(topic) # Get a list of all files in the inbox delineated by the topic in the event inbox_list = self.inboxer.get_inbox_list(topic) # If there are no items in the inbox then there is literally nothing to do if count == 0: return None container_infos = self.__get_registered_containers(data["topic"]) # We have no container infos! :( if container_infos is None: print "Container for topic not found; doing nothing..." return None for container_info in container_infos: container = container_info["container"] # If the count has reached the threshold then it's time to execute! threshold = container_info["threshold"] if container_info[ "threshold"] is not None else 1 if count >= threshold: self.__process(topic, container) else: # We haven't hit the threshold so we need to start counting down # Set the current time if topic not in self.pending: self.pending[topic] = {} self.pending[topic][container] = ( self.__get_current_time_in_seconds() + container_info["timeout"])
def recver(host, port): print('Recver>> Starting...') client = mqtt.Client('measure_recver') client.on_message = on_message client.connect(host, port) print('Recver>> Connected') client.subscribe('ping_t') print('Recver>> Subscribed') client.loop_start() time.sleep(100000) client.loop_stop() if __name__ == '__main__': host = 'localhost' port = 1883 payload = 'test' sender = Thread(target=sender, args=(host, port, payload)) recver = Thread(target=recver, args=(host, port)) sender.start() recver.start() while True: pass sender.stop() recver.stop()
ax.set_zlim(0, 400) plt.show() def updateMeasure(n): while True: retval = pic.get_dist() measurement.set((retval[0] - 53) / 14.7) time.sleep(1) pan_slider = Scale(root, orient=HORIZONTAL, from_=0, to=d_range, label='Pan Angle', variable = pan, command = move_servo) pan_slider.pack(anchor=CENTER) tilt_slider = Scale(root, orient=HORIZONTAL, from_=0, to=d_range, label='Tilt Angle', variable = tilt, command = move_servo) tilt_slider.pack(anchor=CENTER) measurement = StringVar() measure_lbl = Label(root, textvariable=measurement) measure_lbl.pack(anchor=CENTER) btn_auto = Button(root, anchor=CENTER, text='Auto-measurement', command=getPixelCloud) btn_auto.pack(anchor=CENTER) t = Thread(target=updateMeasure, args=(.01,)) t.start() root.mainloop() t.stop()
class ClassroomDiscover(activity.Activity): def __init__(self, handle): activity.Activity.__init__(self, handle) # avahi initialization self._service = None toolbar_box = ToolbarBox() self._vbox = Gtk.VBox() activity_button = ActivityToolbarButton(self) toolbar_box.toolbar.insert(activity_button, 0) activity_button.show() # get information from gconf client = GConf.Client.get_default() self._age = client.get_int('/desktop/sugar/user/age') self._gender = client.get_string('/desktop/sugar/user/gender') if self._gender is None: self._gender = 'male' teacher = (self._age >= 25) # if age is not configured age == 0 if teacher or self._age == 0: teacher_button = ToggleToolButton('%s-7' % self._gender) teacher_button.set_tooltip(_('Teacher')) teacher_button.show() teacher_button.connect('toggled', self.__start_teacher_cb) toolbar_box.toolbar.insert(teacher_button, -1) if teacher: teacher_button.set_active(True) if not teacher or self._age == 0: student_button = ToggleToolButton('%s-2' % self._gender) student_button.set_tooltip(_('Student')) student_button.show() student_button.connect('toggled', self.__start_student_cb) toolbar_box.toolbar.insert(student_button, -1) if self._age > 0: # is a student student_button.set_active(True) separator = Gtk.SeparatorToolItem() separator.props.draw = False separator.set_expand(True) separator.show() toolbar_box.toolbar.insert(separator, -1) stopbutton = StopButton(self) toolbar_box.toolbar.insert(stopbutton, -1) stopbutton.show() self.set_toolbar_box(toolbar_box) toolbar_box.show() self.scrolled = Gtk.ScrolledWindow() self.scrolled.add_with_viewport(self._vbox) self.scrolled.show_all() self.set_canvas(self.scrolled) self._inhibit_suspend() def _joined_cb(self, also_self): """Callback for when a shared activity is joined. Get the shared tube from another participant. """ self.watch_for_tubes() GObject.idle_add(self._get_view_information) def _show_received_student_info(self, student_data): logging.error('received data %s', student_data) hbox = Gtk.HBox() label_n = Gtk.Label() label_n.set_text('Name: %s' % student_data['nick_name'][0]) hbox.add(label_n) label_a = Gtk.Label() label_a.set_text('Age: %s' % student_data['age'][0]) hbox.add(label_a) label_g = Gtk.Label() label_g.set_text('Gender: %s' % student_data['gender'][0]) hbox.add(label_g) hbox.show_all() self._vbox.pack_start(hbox, False, False, 10) logging.error('added to the canvas') def __start_teacher_cb(self, button=None): if self._service is None: # get a free port sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) sock.bind(('', 0)) sock.listen(socket.SOMAXCONN) _ipaddr, self.port = sock.getsockname() sock.shutdown(socket.SHUT_RDWR) logging.error('Using port %d', self.port) # puvblish the server direction self._service = ZeroconfService(name="Teacher", port=self.port, text=profile.get_nick_name()) logging.error('Publish teacher zeroconf service') self._service.publish() # start the http server httpd = MyHTTPServer(('', self.port), lambda *args: TeacherRequestHandler( self._show_received_student_info, *args)) from threading import Thread self._server = Thread(target=httpd.serve_forever) self._server.setDaemon(True) self._server.start() logging.debug("After start server") else: logging.error('Unpublish teacher zeroconf service') self._service.unpublish() self._service = None self._server.stop() def __start_student_cb(self, button=None): TYPE = "_http._tcp" loop = DBusGMainLoop() bus = dbus.SystemBus(mainloop=loop) self._server = dbus.Interface(bus.get_object(avahi.DBUS_NAME, '/'), 'org.freedesktop.Avahi.Server') sbrowser = dbus.Interface( bus.get_object(avahi.DBUS_NAME, self._server.ServiceBrowserNew( avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, TYPE, 'local', dbus.UInt32(0))), avahi.DBUS_INTERFACE_SERVICE_BROWSER) sbrowser.connect_to_signal("ItemNew", self._new_zconf_item_handler) def _new_zconf_item_handler(self, interface, protocol, name, stype, domain, flags): print "Found service '%s' type '%s' domain '%s' " % (name, stype, domain) if flags & avahi.LOOKUP_RESULT_LOCAL: # local service, skip pass if name == "Teacher": self._server.ResolveService( interface, protocol, name, stype, domain, avahi.PROTO_UNSPEC, dbus.UInt32(0), reply_handler=self._service_resolved, error_handler=self._print_error) def _service_resolved(self, *args): logging.error('service resolved name: %s address %s port %s more %s', args[2], args[7], args[8], args) nick_name = profile.get_nick_name() teacher_ip = args[7] teacher_port = args[8] teacher_xo_id = args[5] for widget in self._vbox.get_children(): self._vbox.remove(widget) label = Gtk.Label() self._vbox.add(label) text = ("My name is %s \n" % nick_name) label.set_text(text) label = Gtk.Label() self._vbox.add(label) text = ("Teacher ip: %s \n" % teacher_ip) label.set_text(text) label = Gtk.Label() self._vbox.add(label) text = ("Teacher port: %s \n" % teacher_port) label.set_text(text) label = Gtk.Label() self._vbox.add(label) text = ("Teacher xo id: %s \n" % teacher_xo_id) label.set_text(text) self._vbox.show_all() # sent my information to the teacher student_data = {} student_data['nick_name'] = nick_name student_data['age'] = self._age student_data['gender'] = self._gender url_values = urllib.urlencode(student_data) response = urllib2.urlopen( 'http://%s:%d/student_info?%s' % (teacher_ip, teacher_port, url_values)) json_data = response.read() teacher_data = json.loads(json_data) label = Gtk.Label() self._vbox.add(label) text = ("Teacher name: %s \n" % teacher_data['nick_name']) label.set_text(text) label.show() def _print_error(self, *args): logging.error('error_handler %s', args[0]) def read_file(self, file_path): pass def write_file(self, file_path): pass def can_close(self): self._allow_suspend() return True # power management (almost copied from clock activity) def powerd_running(self): return os.access(POWERD_INHIBIT_DIR, os.W_OK) def _inhibit_suspend(self): if self.powerd_running(): fd = open(POWERD_INHIBIT_DIR + "/%u" % os.getpid(), 'w') fd.close() return True else: return False def _allow_suspend(self): if self.powerd_running(): if os.path.exists(POWERD_INHIBIT_DIR + "/%u" % os.getpid()): os.unlink(POWERD_INHIBIT_DIR + "/%u" % os.getpid()) return True else: return False
## KEYBINDINGS def keyDown(event): serialQueue.put(event.char) def keyRelease(event): serialQueue.put(event.char.upper()) os.system('xset r off') #stop X repeat multiple key presses root.bind("<KeyPress>", keyDown) root.bind("<KeyRelease>", keyRelease) ## Start Worker threads serialWorker = Thread(target=serialWorkerFunction, args=(serialQueue,)) serialWorker.setDaemon(True) serialWorker.start() statWorker = Thread(target=pollForStats) statWorker.start() # Hand main thread over to the Tkinter event loop root.mainloop() os.system('xset r on') # Close open handles on exit logFile.close() serial.close() serialWorker.stop() statWorker.stop()
class Orchestrator(object): def __init__(self, inboxer=Inboxer(), docker_agent=None): self.inboxer = inboxer self.inboxer.on("received", self.__handle_inbox_received_event) self.docker_agent = docker_agent self.id_to_cpu = {} self.id_to_metadata = {} if self.docker_agent is None: self.docker_agent = DockerAgent() # Setup pending queue self.pending = {} self.pending_thread = Thread(target=self.__process_pending) self.pending_thread.daemon = True self.pending_thread.start() # Clean up the id_to_cpu dict def __clean_container(self, container_id): if container_id in self.id_to_metadata: meta = self.id_to_metadata[container_id] Event.create( topic=meta["topic"], container=meta["container"], timestamp=meta["timestamp"], duration=(int(time() * 1000) - meta["timestamp"]), ) del self.id_to_metadata[container_id] if container_id in self.id_to_cpu: del self.id_to_cpu[container_id] # Save stat to database def __handle_stat(self, stat, id, topic, container_name): try: read_dt = parser.parse(stat["read"]) timestamp = int((time.mktime(read_dt.timetuple()) + (read_dt.microsecond / 1000000.0)) * 1000) memory_usage = float(stat["memory_stats"]["usage"]) / float(stat["memory_stats"]["limit"]) Metric.create(topic=topic, container=container_name, timestamp=timestamp, name="memory", value=memory_usage) # Calculate CPU usage. The docker API returns the number of cycles consumed # by the container and the number of cycles consumed by the system. We need # to take the difference over time and divide them to retrieve the usage # percentage. total_usage = float(stat["cpu_stats"]["cpu_usage"]["total_usage"]) system_usage = float(stat["cpu_stats"]["system_cpu_usage"]) if id in self.id_to_cpu: usage_diff = total_usage - self.id_to_cpu[id]["total"] system_diff = system_usage - self.id_to_cpu[id]["system"] if usage_diff >= 0: usage_pct = usage_diff / system_diff else: usage_pct = 0.0 Metric.create(topic=topic, container=container_name, timestamp=timestamp, name="cpu", value=usage_pct) self.id_to_cpu[id] = {"total": total_usage, "system": system_usage} except: # We don't want to kill the stat thread, and we don't really mind # if some statistics aren't saved properly pass # Get listing of registered containers filtered by topic def __get_registered_containers(self, topic): return resolve_query(Registration.select().where(Registration.topic == topic)) # Clear the pending queue of a specific topic def __clear_pending(self, topic, container_name): if topic is not None and topic in self.pending: if container_name is not None and container_name in self.pending[topic]: del self.pending[topic][container_name] # Iterate through the self.pending queue and act on anything queued # that has passed its timer def __process_pending(self): while True: for_process = [] for topic in self.pending: for container in self.pending[topic]: if self.__get_current_time_in_seconds() > self.pending[topic][container]: # It's go time! Pop into array so we can run after the loop # Otherwise modiying the dictionary during runtime is bad (item is # removed from pending immediately upon start of processing) for_process.append({"topic": topic, "container": container}) # Iterate the array and run the things inside for process in for_process: self.__process(process["topic"], process["container"]) del for_process[:] try: sleep(TIMER_INTERVAL) except KeyboardInterrupt: self.pending_thread.stop() def __process(self, topic, container_name): self.__clear_pending(topic, container_name) # Clear the topic so this isn't hit multiple times # Promote all files in the inbox, delineated by topic, to a directory for # a container to mount; returns a list of created inboxes container_inboxes = self.inboxer.promote_to_container_inbox(topic, str(uuid4())) if container_inboxes is None or len(container_inboxes) == 0: print "There are no container inboxes available for the event run; did something weird happen?" return None for container_inbox in container_inboxes: # container_inbox is the path inboxer promoted to be mounted in the docker container self.docker_agent.pull(container_name) container_id = self.docker_agent.start_container( host_inbox=container_inbox, image_name=container_name, on_terminate=self.__clean_container, topic=topic ) self.id_to_metadata[container_id] = { "topic": topic, "container": container_name, "timestamp": int(time() * 1000), } self.docker_agent.stats(container_id, topic, container_name, self.__handle_stat) # Get the current time, in seconds, since epoch def __get_current_time_in_seconds(self): return timegm(gmtime()) # This event handler is executed every time a file is put into the master inbox # The data argument includes a property specify the topic that was appended to def __handle_inbox_received_event(self, data): topic = data["topic"] count = self.inboxer.get_inbox_count(topic) # Get a list of all files in the inbox delineated by the topic in the event inbox_list = self.inboxer.get_inbox_list(topic) # If there are no items in the inbox then there is literally nothing to do if count == 0: return None container_infos = self.__get_registered_containers(data["topic"]) # We have no container infos! :( if container_infos is None: print "Container for topic not found; doing nothing..." return None for container_info in container_infos: container = container_info["container"] # If the count has reached the threshold then it's time to execute! threshold = container_info["threshold"] if container_info["threshold"] is not None else 1 if count >= threshold: self.__process(topic, container) else: # We haven't hit the threshold so we need to start counting down # Set the current time if topic not in self.pending: self.pending[topic] = {} self.pending[topic][container] = self.__get_current_time_in_seconds() + container_info["timeout"]
class TcpClientConnection(ModemConnection): def __init__(self, modem, remote_host, remote_port, local_host=None, local_port=None, timeout=0.1): self._incoming_line_buffer = "" self.connection_type = "udp" self.modem = modem self.timeout = timeout self._remote_host = remote_host self._remote_port = remote_port if local_host is None: self._local_host = "" else: self._local_host = local_host if local_port is None: self._local_port = remote_port else: self._local_port = local_port self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._socket.connect((self._remote_host, self._remote_port)) self._thread = Thread(target=self._listen) self._thread.setDaemon(True) self._thread.start() @property def is_connected(self): return True @property def can_change_baudrate(self): return False def change_baudrate(self,baudrate): return None def close(self): self._thread.stop() self._socket.close() def _listen(self): while True: msg_lines = self.readlines() # We are connected, so pass through to NMEA if msg_lines is not None: for line in msg_lines: self.modem._process_incoming_nmea(line) self.modem._process_outgoing_nmea() def readlines(self): """Returns a \n terminated line from the modem. Only returns complete lines (or None on timeout)""" rl = self._socket.recv(1024) if rl == "": return None self._incoming_line_buffer += rl # Make sure we got a complete line. Serial.readline may return data on timeout. if '\n' in self._incoming_line_buffer: # is there a newline at the end? lines = self._incoming_line_buffer.splitlines(True) # See if the last line has a newline at the end. if lines[-1][-1] != '\n': self._incoming_line_buffer = lines[-1] lines.pop() # remove it from the list to passed on # return the list of complete lines return lines else: return None def write(self, data): self._socket.send(data)
class ResourceMonitor(object): # Start monitoring all resources. def __init__ (self,duration,numsamples): self.duration = duration self.numsamples = numsamples self.cpuarray = [] self.iorkbpsarray = [] self.iowkbpsarray = [] def Start(self): self.t = Thread(target=self.myfunc, args=(self.duration,self.numsamples)) self.t.start() # Stop monitoring all resources. def Stop(self): self.t.stop() def myfunc (self,duration,numsamples): while 1: self.cpuarray.append (self.GetIndividualStatisticCPU ()); if (len (self.cpuarray) > numsamples): self.cpuarray.pop(0) self.iorkbpsarray.append (self.GetIndividualStatisticIORKBPS ()); if (len (self.iorkbpsarray) > numsamples): self.iorkbpsarray.pop(0) self.iowkbpsarray.append (self.GetIndividualStatisticIOWKBPS ()); if (len (self.iowkbpsarray) > numsamples): self.iowkbpsarray.pop(0) print "Start sleeping for ",duration #time.sleep (duration) threading.Event().wait(duration) print "Stop sleeping" # Get the latest value (moving average) for the statistic 'stat_name'. def GetIndividualStatisticCPU(self): p = os.popen("iostat") i=0; while 1: line = p.readline() if not line: break if (i==3): tmparray = [float(x) for x in line.split()] f = float (tmparray[0]) return f i += 1 print line def GetIndividualStatisticIORKBPS(self): p = os.popen("iostat -d -x -h -k sda") i=0; while 1: line = p.readline() if not line: break if (i==3): tmparray = [x for x in line.split()] f = float (tmparray[5]) return f i += 1 print line def GetIndividualStatisticIOWKBPS(self): p = os.popen("iostat -d -x -h -k sda") i=0; while 1: line = p.readline() if not line: break if (i==3): tmparray = [x for x in line.split()] f = float (tmparray[6]) return f i += 1 print line def GetStatistic (self,stat_name): if (stat_name is "cpu"): array = self.cpuarray; elif (stat_name == "io-rkbps"): array = self.iorkbpsarray; elif (stat_name == "io-wkbps"): array = self.iowkbpsarray else: print "Big problem. No such statistic",stat_name return -1 sumarray = sum (array) numsamples = len (array) avg = sumarray / float (numsamples) return avg
class output_interface(): def __init__(self, address, mock=False): if(mock): from libs.i2c_lcd_driver_mock import i2c_lcd else: from libs.i2c_lcd_driver import i2c_lcd self.__device = i2c_lcd(address) self.screensaver = None self.load_custom_chars(custom_characters.get_data()) self.set_screensaver(Screensaver) self.clear() def render(self, data): ## Update LCD line1 = unichr(1) + " " + "{:.1f}%".format(data['humidity']) line1 += " " line1 += unichr(0) + " " + "{:.1f}".format(data['temp']) + unichr(0b11011111) if data['standby']: line2 = ' {time}' else: line2 = unichr(4) + " Target: " + "{:.1f}".format(data['desired']) + unichr(0b11011111) self.display_string(line1, 1) self.display_string(line2, 2) def set_screensaver(self, Screensaver): self.screensaver = Thread(target=Screensaver, args=(self,)) self.screensaver.setDaemon(True) def clear(self): self.__device.clear() def load_custom_chars(self, data): self.__device.load_custom_chars(data) def backlight(self, status): self.__device.backlight(status) def display_string(self, text, line=1, pos=0): text = text.replace("{time}", strftime( unichr(2) + "%H:%M:%S", localtime())) self.__device.display_string(text, line, pos) def startScreensaver(self): if(self.screensaver): self.screensaver.start() def stopScreensaver(self): if(self.screensaver): self.screensaver.stop() def parseCommand(self, data): validCommands = { 'clear': r'clear', 'clearline': r'clearline ([12])', 'setline': r'setline ([12]) (.*)', 'setchar': r'setchar ([12]) ([1-9]{1,2}) ([a-z])', 'backlight': r'backlight ([01])', 'screensaver': 'screensaver ([01])', 'quit': r'quit' } command = None args = None data = data.rstrip() for i in validCommands: matchObj = re.match(validCommands[i], data, re.I) if matchObj: command = i args = matchObj.groups() if command: if command != 'quit': self.sendCommand(command, args) return { 'command': command, 'args': args } else: return False def sendCommand(self, cmd, args): global device if cmd == 'setline': line = int(args[0]) text = args[1] if text == "{test}": text = unichr(0)+unichr(1)+unichr(2)+unichr(3)+unichr(4)+unichr(5)+unichr(6)+unichr(7) print "printing: ", text, " in line ", line self.display_string(text,line) elif cmd == 'setchar': line = int(args[0]) pos = int(args[1]) text = args[2] self.display_string(text,line,pos) elif cmd == 'clearline': line = args[0] self.display_string(" ",line) elif cmd == 'backlight': status = int(args[0]) self.backlight(status) elif cmd == 'screensaver': status = int(args[0]) if status: self.startScreensaver() else: self.stopScreensaver() elif cmd == 'clear': self.clear() return 'OK: ', cmd, args
if (counter == 5): urllib2.urlopen("http://dev.chris-the-tuner.de/pi.php?cents=200") counter = 0 count = 1 print("Ready to process the next payment !") time.sleep(1) def thirdFunction(): while True: if (counting == 0): global ts ts = time.time() time.sleep(1) try: t1 = Thread(target = firstFunction) t2 = Thread(target = secondFunction) t3 = Thread(target = thirdFunction) t1.start() t2.start() t3.start() except KeyboardInterrupt: t1.stop() t2.stop() t3.stop() GPIO.cleanup()
class VPNService(Container,MultiPointVPNService): def __init__(self): Resource.__init__(self,"MultiPointVPNService") print "MultiPoint VPN Service is starting" self.vpnIndex = {} self.vpnIndexById = {} self.topology = None self.coretopology = None self.lock = threading.Lock() self.properties['mat'] = True # Default. self.loadService() self.saveThread = Thread(target=self.autosave) self.saveThread.start() if self.topology != None: self.setscc() def setscc(self): self.SCC = SdnControllerClient() self.sccThread = JavaThread(self.SCC) self.sccThread.start() self.VPNcallback = VpnCallback("MP-VPN Service", self) setcallback(self.VPNcallback) self.SCC.setCallback(self.VPNcallback) def settopos(self, popstoponame, coretoponame): self.properties['topology'] = popstoponame self.topology = Container.getContainer(self.properties['topology']) self.properties['coretopology'] = coretoponame self.coretopology = Container.getContainer(self.properties['coretopology']) # We can now set up the callback self.setscc() self.saveService() def shutdown(self): self.saveThread.stop() if self.sccThread != None: self.sccThread.stop() self.SCC.clearCallback() MultiPointVPNServiceFactory.delete() def autosave(self): while True: if not self.topology == None: self.saveService() for (x,vpn) in self.vpnIndex.items(): vpn.saveVPN() time.sleep(60) def saveService(self): self.properties['sid'] = self.sid if self.topology != None: self.properties['topology'] = self.topology.getResourceName() if self.coretopology != None: self.properties['coretopology'] = self.coretopology.getResourceName() try: self.save() except: print "Failed to save VPN Service\n", sys.exc_info()[0] def loadService(self): stored = Container.getContainer(self.getResourceName()) mapResource (obj=self,resource=stored) if 'topology' in self.properties: self.topology = Container.getContainer(self.properties['topology']) if 'coretopology' in self.properties: self.coretopology = Container.getContainer(self.properties['coretopology']) vpns = self.loadResources({"resourceType":"VPN"}) for v in vpns: vpn = VPN(v.getResourceName()) vpn.loadVPN(self) self.vpnIndex[v.getResourceName()] = vpn self.vpnIndexById[vpn.vid] = vpn if not 'mat' in self.properties: self.properties['mat'] = True def newVid(self): with self.lock: while True: v = random.randint(1,65535) if not v in self.vpnIndexById: return v def getSite(self,s): global sites if s in sites: return sites[s] else: return None def getHost(self,s): return tbns[s] def addVpn(self,vpn): self.vpnIndex[vpn.name] = vpn self.vpnIndexById[vpn.vid] = vpn self.saveResource(vpn) def createVPN(self,vpnname): if vpnname in self.vpnIndex: return None vpn = VPN(vpnname,vs=self) self.vid = self.newVid() self.addVpn(vpn) return vpn def deleteVPN(self,vpnname): if not vpnname in self.vpnIndex: print "vpn name %s not found" % vpnname return vpn = self.vpnIndex[vpnname] for h in vpn.hostsites.keys(): self.delhostbymac(vpn, h) for s in vpn.vpnsites.values(): self.delsite(vpn, s) for p in vpn.pops.values(): self.delpop(vpn, p) self.vpnIndex.pop(vpn.name) self.vpnIndexById.pop(vpn.vid) self.deleteResource(vpn) print "VPN %s removed successfully." % (vpn.name) return True def getVPN(self,vpnname): if not vpnname in self.vpnIndex: return None return self.vpnIndex[vpnname] def addPOP(self,vpn, pop): if not vpn.addpop(pop): return False return True def deletePOP(self,vpn, pop): if not vpn.delpop(pop): return False return True def addSite(self, vpn, site, vlan): if not vpn.addsite(site, vlan): # possible issues: duplicated site return False return True def deleteSite(self, vpn, site): if not vpn.delsite(site): return False return True def addhostbymac(self, vpn, site, mac): if not vpn.addhostbymac(site, mac): print "Error while adding host." return print "Host %s has been added into VPN %s successfully at site %s" % (mac, vpn.name, site['name']) def delhostbymac(self,vpn, mac): if not vpn.delhostbymac(mac): print "Error while deleting host." return
class MainUI(Ui_ASTM_Clent): def _del_(self): if hasattr(self, "server"): self.server.shutdown() self.server = None self.t._stop() def searchClicked(self): sid = self.txtSearch.text() result = OperationDB().selectTest((sid,)) print(result) self.searchCallBack(result) def testConnClicked(self): sendIP = self.txtSendIP.text() sendPort = self.txtSendPort.text() try: TCPClient(sendIP, sendPort).send(("testConn", ()), self.testConnCallBack) except Exception as e: print(e) self.txtConsole.append(str(e)) def testConnCallBack(self, params): print(params) if params == "success": print(params) self.txtConsole.append(params) def listening(self): if hasattr(self, "server"): self.server.shutdown() self.server = None self.t._stop() listenIP = self.txtLocalIP.text() listenPort = self.txtLocalPort.text() try: self.server = ThreadingTCPServer((listenIP, int(listenPort)), EchoRequestHandler) print("server running at", listenIP, listenPort) self.txtConsole.append("server running at " + listenIP + " " + listenPort) self.t = Thread(target=self.server.serve_forever) self.t.start() except Exception as e: print(e) self.txtConsole.append(str(e)) def connClicked(self): sendIP = self.txtSendIP.text() sendPort = self.txtSendPort.text() try: TCPClient(sendIP, sendPort).send(("testConn", ()), self.connCallBack) except Exception as e: print(e) self.txtConsole.append(str(e)) def connCallBack(self, params): print(params) if params == "success": self.sendIP = self.txtSendIP.text() self.sendPort = self.txtSendPort.text() self.txtConsole.append(self.sendIP + ":" + self.sendPort + " connected.") else: self.txtConsole.append(self.sendIP + ":" + self.sendPort + " connect failed.") def orderButClicked(self): sid = self.txt_sid.text() pid = self.txt_pid.text() pname = self.txt_pname.text() page = self.txt_page.text() pgender = self.txt_gender.text() status = self.txt_status.text() if sid == "": self.txtConsole.append("please type sid") return if pid == "": self.txtConsole.append("please type pid") return if pname == "": self.txtConsole.append("please type name") return if page == "": self.txtConsole.append("please type age") return if pgender == "": self.txtConsole.append("please type gender") return if status == "": self.txtConsole.append("please type status") return albchecked = self.chk_ALB.isChecked() altchecked = self.chk_ALT.isChecked() astchecked = self.chk_AST.isChecked() alpchecked = self.chk_ALP.isChecked() mgchecked = self.chk_MG.isChecked() ggtchecked = self.chk_GGT.isChecked() hcychecked = self.chk_HCY.isChecked() uricchecked = self.chk_URIC.isChecked() bunchecked = self.chk_BUN.isChecked() cholchecked = self.chk_CHOL.isChecked() sycschecked = self.chk_SYCS.isChecked() glucchecked = self.chk_GLUC.isChecked() testnames = [] if albchecked: testnames.append(self.chk_ALB.text()) if altchecked: testnames.append(self.chk_ALT.text()) if astchecked: testnames.append(self.chk_AST.text()) if alpchecked: testnames.append(self.chk_ALP.text()) if mgchecked: testnames.append(self.chk_MG.text()) if ggtchecked: testnames.append(self.chk_GGT.text()) if hcychecked: testnames.append(self.chk_HCY.text()) if uricchecked: testnames.append(self.chk_URIC.text()) if bunchecked: testnames.append(self.chk_BUN.text()) if cholchecked: testnames.append(self.chk_CHOL.text()) if sycschecked: testnames.append(self.chk_SYCS.text()) if glucchecked: testnames.append(self.chk_GLUC.text()) if len(testnames) == 0: self.txtConsole.append("please a test at least.") return params = (sid, pid, pname, page, pgender, status, testnames) result = OperationDB().orderEntry(params) self.orderEntryCallBack(result) def orderEntryCallBack(self, params): print(params) self.txtConsole.append(params) # transform data # TCPClient(self.sendIP, self.sendPort).send(("orderEntry", params), self.orderEntryCallBack) def searchCallBack(self, params): print(params) index = 0 for param in params: if not param is None: _translate = QtCore.QCoreApplication.translate self.table_test.setRowCount(index + 1) if param[0] == "P": item = QtWidgets.QTableWidgetItem() self.table_test.setItem(index, 1, item) item.setText(param[1]) item = QtWidgets.QTableWidgetItem() self.table_test.setItem(index, 2, item) item.setText(param[2]) item = QtWidgets.QTableWidgetItem() self.table_test.setItem(index, 3, item) item.setText(param[3]) item = QtWidgets.QTableWidgetItem() self.table_test.setItem(index, 4, item) item.setText(param[4]) elif param[0] == "O": item = QtWidgets.QTableWidgetItem() self.table_test.setItem(index, 0, item) item.setText(param[1]) item = QtWidgets.QTableWidgetItem() self.table_test.setItem(index, 5, item) item.setText(param[2]) elif param[0] == "R": item = QtWidgets.QTableWidgetItem() self.table_test.setItem(index, 6, item) item.setText(param[1]) item = QtWidgets.QTableWidgetItem() self.table_test.setItem(index, 7, item) item.setText(param[2]) index += 1 def closeWindown(self): if hasattr(self, "server"): self.server.shutdown() self.server = None self.t.stop()
print ("Waiting ", detectCounter[0]) detectCounter[0] += 1 else: GPIO.output(16,GPIO.HIGH) image = frame.array captureTime = time.time() # print("FRAME Time", captureTime-prevTime) prevTime = captureTime # if frameCount == 0: # frameCount = 0 #if i == 0: t1 = Thread(target = classfier, args = (image,i,captureTime,detectCounter)) t1.start() threadPick = t1.join() # cv2.imshow("Frame", image) key = cv2.waitKey(1) & 0xFF # clear the stream in preparation for the next frame rawCapture.truncate(0) # if the `q` key was pressed, break from the loop if key == ord("q"): cleanup_stop_thread(); sys.exit() t1.stop() break
def quit(self): Thread.stop() sys.exit(app.exec_())
class TcpClientConnection(ModemConnection): def __init__(self, modem, remote_host, remote_port, local_host=None, local_port=None, timeout=0.1): self._incoming_line_buffer = "" self.connection_type = "udp" self.modem = modem self.timeout = timeout self._remote_host = remote_host self._remote_port = remote_port if local_host is None: self._local_host = "" else: self._local_host = local_host if local_port is None: self._local_port = remote_port else: self._local_port = local_port self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._socket.connect((self._remote_host, self._remote_port)) self._thread = Thread(target=self._listen) self._thread.setDaemon(True) self._thread.start() @property def is_connected(self): return True @property def can_change_baudrate(self): return False def change_baudrate(self, baudrate): return None def close(self): self._thread.stop() self._socket.close() def _listen(self): while True: msg_lines = self.readlines() # We are connected, so pass through to NMEA if msg_lines is not None: for line in msg_lines: self.modem._process_incoming_nmea(line) self.modem._process_outgoing_nmea() def readlines(self): """Returns a \n terminated line from the modem. Only returns complete lines (or None on timeout)""" rl = self._socket.recv(1024) if rl == "": return None self._incoming_line_buffer += rl # Make sure we got a complete line. Serial.readline may return data on timeout. if '\n' in self._incoming_line_buffer: # is there a newline at the end? lines = self._incoming_line_buffer.splitlines(True) # See if the last line has a newline at the end. if lines[-1][-1] != '\n': self._incoming_line_buffer = lines[-1] lines.pop() # remove it from the list to passed on # return the list of complete lines return lines else: return None def write(self, data): self._socket.send(data)
self.stopped = True @socketio.on('connect', namespace='/test') def test_connect(): #emit('my response', {'data': 'Power', 'count': random.random() }) global thread global thread_stop_event if not thread.isAlive(): print "Starting Thread" thread_stop_event = Event() thread = LiveData() thread.start() @socketio.on('disconnect request', namespace='/test') def disconnect_request(): #session['receive_count'] = session.get('receive_count', 0) + 1 #emit('my response', # {'data': 'Disconnected!', 'count': session['receive_count']}) thread_stop_event.set() disconnect() if __name__ == '__main__': try: socketio.run(app,host="0.0.0.0",port=8080) except (KeyboardInterrupt, SystemExit) as e : global thread thread.stop() sys.exit()
import os from time import sleep from threading import Thread, current_thread from itertools import count def foo(): for i in count(0): if hasattr(current_thread(), "stop"): break print "In foo: counting", i t1 = Thread(target=foo) t1.start() sleep(5) t1.stop = True
class simpleFrame(wx.Frame): def __init__(self,parent,ID,title): wx.Frame.__init__(self, parent,ID,title, size=wx.Size(300,200) ) self.ser = serial.Serial(C_serial, C_serial_speed) self.EnableCloseButton(False) self.timeleft = 0 self.sizer = wx.BoxSizer(wx.VERTICAL) self.m_statusBar1 = self.CreateStatusBar( 1, wx.ST_SIZEGRIP, wx.ID_ANY ) self.Bind( serialrx, self.serial) self.t = Thread(target=self.readSerial) self.t.start() self.SetSizer(self.sizer) self.Layout() self.Centre( wx.BOTH ) self.timer = wx.Timer(self, 100) wx.EVT_TIMER(self, 100, self.ontimer) def ontimer(self,evt): self.guitime.SetValue( self.timeleft ) self.timeleft = self.timeleft - 1 self.m_statusBar1.SetStatusText("User is: %s Time Left: %d minutes" % (self.userName , self.timeleft/60) ) if self.timeleft < 0: self.logoutfunc(False) def logoutfunc(self,evt): self.timer.Stop() log("%s stopped using device" % self.userName) self.ser.write('user:-1') self.sizer.Clear(True) self.sizer.AddSpacer( ( 0, 30), 1, wx.EXPAND, 5 ) self.sizer.Add( wx.StaticText( self, wx.ID_ANY, u"Scan Badge to login" ),wx.ALL|wx.ALIGN_CENTER,5) self.m_statusBar1.SetStatusText("Scan Badge to login") self.userName = False self.Layout() def serial(self, evt): global C_code usercode = evt.attr1 # print("got %s" % usercode) print( "%s/device/0/code/%s" % ( C_server, usercode) ) code = requests.get( url="%s/device/0/code/%s" % ( C_server, usercode) ) code = int(code.text) C_code = code self.m_statusBar1.SetStatusText("Level is: %s" % levels[code]) # if they have access to the machine if code > 0: self.userName = requests.get( url="%s/user/code/%s" % ( C_server, usercode) ) self.userName = str(self.userName.text) self.ser.write('%s:1' % self.userName) log("%s started using device" % self.userName) self.timeleft = C_timeout self.sizer.Clear(True) self.logout = wx.Button(self, wx.ID_ANY, u"Logout", wx.DefaultPosition, wx.DefaultSize, wx.BU_EXACTFIT) self.timertext = wx.StaticText( self, wx.ID_ANY, u"Time Left" ) self.guitime = wx.Gauge( self, wx.ID_ANY, C_timeout , wx.DefaultPosition, wx.DefaultSize, wx.GA_HORIZONTAL) self.sizer.AddSpacer( ( 0, 30), 1, wx.EXPAND, 5 ) self.sizer.Add(self.timertext, wx.ALL|wx.ALIGN_CENTER,5) self.sizer.Add(self.guitime, wx.ALL|wx.ALIGN_CENTER,5) self.sizer.AddSpacer( ( 0, 20), 1, wx.EXPAND, 5 ) self.sizer.Add(self.logout, wx.ALL|wx.ALIGN_CENTER,5) self.sizer.AddSpacer( ( 0, 20), 1, wx.EXPAND, 5 ) self.guitime.SetValue(self.timeleft) self.logout.Bind( wx.EVT_BUTTON, self.logoutfunc) self.Layout() self.timer.Start(1000) else: self.ser.write('user:-1') def readSerial(self): while True: message = self.ser.readline()[2:-4].strip() evt = s(attr1=message) wx.PostEvent(self,evt) time.sleep(5) def onClose(self,event): self.t.stop()
lcd.backlight(0) loggingProcess = Thread(target=loggingToGoogle, args=(GDOCS_OAUTH_JSON, GDOCS_SPREADSHEET_NAME, LOGGING_FREQUENCY, thSource, weatherSource, smogSource)) loggingProcess.daemon = True loggingProcess.start() stateMachine = stateMachine() print("Meteo Station started!") while work: try: work = stateMachine.executeState() except: work = True loggingProcess.stop = True distanceProcess.stop = True smogProcess.stop = True weatherProcess.stop = True thProcess.stop = True del proximitySensor del smogSource except: loggingProcess.stop = True distanceProcess.stop = True smogProcess.stop = True weatherProcess.stop = True thProcess.stop = True lcd.clear() lcd.backlight(0) del proximitySensor
class Tracker: def __init__(self,mode="2D"): self.mode = 0 if mode == "2D" else 1 self.capture = cv2.VideoCapture(0) self.current_image = Queue() if mode == "2D": self.current_point = (0,0) else: self.capture2 = cv2.VideoCapture(1) self.current_image2 = Queue() self.current_point = (0,0,0) self.c_tracker = Thread(target=self.continues_tracker, args=()) for i in range(1,10): okay, image = self.capture.read() #init camera if mode == "3D": okay, image = self.capture2.read() #init camera def colorBased(self,image,lower_color,upper_color): blur = cv2.GaussianBlur(image, (5,5),0) hsv = cv2.cvtColor(blur, cv2.COLOR_BGR2HSV) mask = cv2.inRange(hsv, lower_color, upper_color) bmask = cv2.GaussianBlur(mask, (5,5),0) moments = cv2.moments(bmask) m00 = moments['m00'] centroid_x, centroid_y = None, None if m00 != 0: centroid_x = int(moments['m10']/m00) centroid_y = int(moments['m01']/m00) ctr = (-1,-1) if centroid_x != None and centroid_y != None: ctr = (centroid_x, centroid_y) return ctr def motionBased(self, image): # returns the boundingboxes of areas in motion, may only work in continus tracking return (-1,-1) def findCircles(self, image, minDist): #finds circles, warning: this takes a lot of cpu img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gray = cv2.GaussianBlur(img, (5,5),5) circles = cv2.HoughCircles(gray, cv2.cv.CV_HOUGH_GRADIENT,1.7, minDist,2) if circles is not None: circles = np.round(circles[0, :]).astype("int") return circles #this is a list else: return None def _3d(self): points_colorbased = list() circles_xy = None circles_z = None while 1: okay, image = self.capture.read() okay, image2 = self.capture2.read() # 1. step: color_tracking ctr_colorbased = self.colorBased(image,np.array([40,70,0]),np.array([80,200,200])) ctr_colorbased2 = self.colorBased(image2,np.array([40,70,0]),np.array([80,200,200])) if not ctr_colorbased[0] == -1: if not ctr_colorbased2[0] == -1: points_colorbased.append((ctr_colorbased[0],ctr_colorbased[1],ctr_colorbased2[0])) else: points_colorbased.append((ctr_colorbased[0],ctr_colorbased[1],self.current_point[2])) else: points_colorbased.append(self.current_point) # 2. step: find circles, quite expensive circles_xy = self.findCircles(image,600) circles_z = self.findCircles(image2,600) self.current_point = self.mean(points_colorbased) if circles_xy is not None: for (x, y, r) in circles_xy: cv2.circle(image, (x, y), r, (0, 255, 0), 4) if self.in_circle(x,y,r,self.current_point[0],self.current_point[1]): self.current_point = (x,y,self.current_point[2]) # TODO: circletracking for z-axis here del points_colorbased[:] if ctr_colorbased[0] != None and ctr_colorbased[1] != None: cv2.circle(image, ctr_colorbased, 10, (0,0,255)) cv2.circle(image, (self.current_point[0],self.current_point[1]), 20, (255,0,255),4) cv2.circle(image2, (int(ctr_colorbased2[0]),int(ctr_colorbased2[1])), 20, (255,0,255),4) cv2.putText(image, str(self.current_point), (100,100), cv2.FONT_HERSHEY_SCRIPT_SIMPLEX, 2, np.array([0,0,0]), 3, 8) if self.current_image.empty(): self.current_image.put(image) if self.current_image2.empty(): self.current_image2.put(image2) def _2d(self): points_colorbased = list() circles_xy = None while 1: okay, image = self.capture.read() # 1. step: color_tracking ctr_colorbased = self.colorBased(image,np.array([40,70,0]),np.array([80,200,200])) if not ctr_colorbased[0] == -1: points_colorbased.append((ctr_colorbased[0],ctr_colorbased[1],0)) else: points_colorbased.append(self.current_point) # 2. step: find circles, quite expensive circles_xy = self.findCircles(image,600) self.current_point = self.mean(points_colorbased) if circles_xy is not None: for (x, y, r) in circles_xy: cv2.circle(image, (x, y), r, (0, 255, 0), 4) if self.in_circle(x,y,r,self.current_point[0],self.current_point[1]): self.current_point = (x,y,0) del points_colorbased[:] if ctr_colorbased[0] != None and ctr_colorbased[1] != None: cv2.circle(image, ctr_colorbased, 10, (0,0,255)) cv2.circle(image, (self.current_point[0],self.current_point[1]), 20, (255,0,255),4) cv2.putText(image, str(self.current_point), (100,100), cv2.FONT_HERSHEY_SCRIPT_SIMPLEX, 2, np.array([0,0,0]), 3, 8) if self.current_image.empty(): self.current_image.put(image) def continues_tracker(self): if self.mode == 1: self._3d() else: self._2d() def in_circle(self,center_x, center_y, radius, x, y): square_dist = (center_x - x) ** 2 + (center_y - y) ** 2 return square_dist <= radius ** 2 def mean(self,points): x,y,z = 0,0,0 for a in points: x += a[0] y += a[1] z += a[2] return (x/len(points),y/len(points),z/len(points)) def start_cont_tracker(self): if not self.c_tracker.isAlive(): self.c_tracker.start() else: print "c_tracker already runs" time.sleep(1) def stop_cont_tracker(self): if self.c_tracker.isAlive(): self.c_tracker.stop() else: print "c_tracker does not run" def get_current_point(self): return self.current_point def get_current_image(self): return self.current_image def get_current_image2(self): return self.current_image2 def track(self,image): ctr_colorbased = self.colorBased(image,np.array([40,70,70]),np.array([80,200,200])) # calibrated for bright green circles = self.findCircles(image,100) if ctr_colorbased[0] != None and ctr_colorbased[1] != None: # mark colorbased trackpoint cv2.circle(image, ctr_colorbased, 10, (0,0,255)) if circles is not None: for (x, y, r) in circles: cv2.circle(image, (x, y), r, (0, 255, 0), 4) return ctr_colorbased,image def getAbsolutePosition(self): okay, image = self.capture.read() return self.track(image)