예제 #1
0
 def __init__(self):
     conn1, conn2 = multiprocessing.Pipe()
     self.conn = conn2
     self.listener = Listener(debug_connection=conn1)
     self.listener.start()
     self.bpm_to_test = [0]
     self.bpm_energies = [0]
예제 #2
0
def add_macro():
    global database, listenter
    name = request.form.get("name")
    language = request.form.get("language")
    age_group = request.form.get("age")
    gender = request.form.get("gender")
    description = request.form.get("description")
    keyboard_events_path = request.form.get("key_file")
    event_strings = request.form.get("events_string")
    sound_1 = request.form.get("sound_1")
    sound_2 = request.form.get("sound_2")
    sound_3 = request.form.get("sound_3")

    ok, message = training_service.get_model(name, (sound_1, sound_2, sound_3),
                                             language, age_group, gender)
    if (not ok):
        return jsonify({"message": message})
    else:
        try:
            database.insert((name, language, age_group, gender, description,
                             event_strings, keyboard_events_path, message))
            try:
                listenter.stop()
            except Exception as e:
                pass
            if (len(database.get_all()) > 0):
                listenter = Listener(sensitivity=args.sensitivity,
                                     speed_factor=args.speed_factor)
                listenter.start()
            return jsonify({"message": "ok"})
        except sqlite3.Error as e:
            return jsonify({"message": e.args[0]})
예제 #3
0
 def __init__(self, filter, ignore, reactor, parent=None):
     Listener.__init__(self, filter, ignore, reactor)
     self.reactor = reactor
     self.dwDict = {
     }  # Dictionary to keep track of which dataset goes to which window
     self.windowDict = {}  # Maps window names to PlotWindow objects
     self.startTimer()
예제 #4
0
 def __init__(self, peer):
     # print "A communicator is created!"
     self.peer = peer
     self.messageQueue = peer.messageQueue
     self.mylistener = Listener(peer)
     self.mylistener.setDaemon(True)
     self.mylistener.start()
예제 #5
0
파일: bot.py 프로젝트: caciolai/SHRIProject
    def __init__(self,
                 name,
                 color,
                 verbose=True,
                 silent=False,
                 menu_path=None):
        """
        Constructor
        :param name: the bot's name it will use in the dialogues
        :param color: the color the bot will use in the prompt
        :param verbose: whether the bot should print info about
        the command it receives (dependency tree, lemmas info)
        :param silent: if true, then only use print (no text to speech)
        :param menu_path: the path of the stored menu
        """

        self._name = name
        self._speaker = Speaker(rate=150, volume=1)
        self._listener = Listener(mic_index=0)
        self._prompt = colored(f'{self._name}: ', color)
        self._verbose = verbose
        self._silent = silent

        self._frame_stack = []
        self._current_frame = None

        self._is_over = False

        if menu_path is not None:
            self._load_menu(menu_path)
        else:
            self._menu = {"entries": []}

        # when finished setup, welcome user
        self._say(self._welcome())
예제 #6
0
class Controller:

    # requestQueue is shared queue among all processes
    def __init__(self, database: DB):
        if not isinstance(database, DB):
            raise TypeError('Controller was not supplied a DB object')
        self.manifest = Manifest()
        self.request_queue = multiprocessing.Queue()
        self.listener = Listener(self.request_queue)
        self.database = database

    def _create_request_processor(self):
        req = RequestProcessor(self.request_queue, self.database)
        req.process_requests()

    def create_request_processors(self):
        processes = []
        for i in range(self.manifest.number_of_request_processors):
            log(f"creating request processor {str(i)}", level=INFO)
            # print('Creating processes %d' % i)
            processes.append(Process(target=self._create_request_processor))
        for i in processes:
            i.start()

    def create_listener(self):
        log('creating request listener', level=INFO)
        self.listener.create_listener()
        thread = Thread(target=self.listener.listen)
        thread.start()
        thread.join()
예제 #7
0
def main():

    parser = argparse.ArgumentParser(description='Set configuration.')

    parser.add_argument("-c",
                        "--file",
                        type=str,
                        nargs=1,
                        metavar=('file'),
                        help="Choose file with URL's list")

    parser.add_argument("-l",
                        "--log",
                        type=str,
                        nargs=1,
                        metavar=('log'),
                        help="Choose log file")

    args = parser.parse_args()

    with open(args.file[0]) as file:
        data = json.load(file)
        dict_list = data['pages']

    manager = mp.Manager()
    q = manager.Queue()
    pool = mp.Pool(mp.cpu_count() + 2)
    listener = Listener(q, args.log[0])

    for web_page in dict_list:
        workers.put(MyTask(web_page, q))

    w = pool.apply_async(listener.listener())
예제 #8
0
    def run(self):
        self.is_running = True

        if self.is_listening:
            if self.is_verbose:
                print "\033[34m[*]\033[0m starting the listener ...."
            ''' START Listener '''
            self.listener = Listener(open_sock=self.sock,
                                     isVerbose=self.is_verbose)
            self.listener.daemon = True
            self.listener.start()

        if self.is_verbose:
            print "\033[34m[*]\033[0m starting the sender ...."
        ''' START Sender'''
        self.sender = Sender(sock=self.sock,
                             messages=self.messages,
                             peers=self.peer,
                             isVerbose=self.is_verbose,
                             msg_freq=self.msgs_freq,
                             wait_time=self.wait_time,
                             gtp_port=self.gtp_port)
        self.sender_daemon = True
        self.sender.start()
        self.sender.join()
        time.sleep(5)
        self.stop()
예제 #9
0
 def __init__(self, database: DB):
     if not isinstance(database, DB):
         raise TypeError('Controller was not supplied a DB object')
     self.manifest = Manifest()
     self.request_queue = multiprocessing.Queue()
     self.listener = Listener(self.request_queue)
     self.database = database
예제 #10
0
def main(arglist):
    logging.basicConfig(
        format='%(funcName)s:%(lineno)d %(levelname)s %(message)s',
        level=logging.INFO)
    parser = argparse.ArgumentParser()
    parser.add_argument('--mode',
                        dest='mode',
                        default=RUN_MODE.UPLOAD,
                        help='The mdoe to run Good drive uploader',
                        choices=RUN_MODE.CHOICES)
    parser.add_argument('--upload',
                        dest='upload',
                        default='',
                        help='Upload a file or directory')
    args = parser.parse_args(arglist[1:])

    if args.mode == RUN_MODE.UPLOAD:
        if not args.upload:
            raise ValueError('params --upload required')
        GoogleDriveUpload.upload_in_shared(args.upload)

    elif args.mode == RUN_MODE.LISTENER:
        PORT = 4242
        IP = '127.0.0.1'
        uploader = GoogleDriveUpload()
        listener = Listener(IP, PORT, uploader)
        listener.listen()
 def __init__(self, ip, binary, name="noname", port=22):
     self.name = name
     self.ip = ip
     self.port = port
     listener_port = random.randint(20000, 25000)
     self.listener = Listener(name, ip, listener_port, self)
     self.binary = Binary(binary, self)
예제 #12
0
def main():
    """ The entry point of red agent """
    listener_port = constant.DEFAULT_LISTENER_PORT

    #TODO: Command line arguments should be handled elegantly.
    if len(sys.argv) > 1:
        listener_port = sys.argv[1]
    AttackDB().update()

    Listener().work(constant.DEFAULT_LISTENER_IP, int(listener_port))

    assumed_state = {
        constant.STATE_KEY_PROTOCOL: constant.STATE_VALUE_PROTOCOL_IP,
        constant.STATE_KEY_ADDRESS: constant.DEFAULT_TARGET_IP
    }

    goal = Condition()
    goal.add((constant.STATE_KEY_SHELL, constant.CONDITION_OPERATOR_EQUAL,
              constant.STATE_VALUE_SHELL_PERMANENT))
    goal.add((constant.STATE_KEY_PRIVILEGE, constant.CONDITION_OPERATOR_EQUAL,
              constant.STATE_VALUE_PRIVILEGE_ROOT))

    planner = Planner(assumed_state, goal)
    try:
        planner.make_plan()
        print(planner)
        planner.run()

    except Exception as e:
        traceback.print_exc()
        Listener().stop()
        raise e

    Listener().stop()
    sys.exit(0)
예제 #13
0
def main():
  listener = Listener()
  listener.start()
  while True:
    recv_queue_data = listener.queue.get()
    recv_data = recv_queue_data.msgtype
    distance = recv_queue_data.msg
    if recv_data == 0x05: # Follower to move forward
      totalMoves(distance)
      print ("Received Follower move forward")
    elif recv_data == 0x06: # Follower to move backward
      totalMoves(distance)
      print ("Received Follower move backward")
    elif recv_data == 0x07: # Follower to move left
      totalMoves(distance)
      print ("Received Follower move left")
    elif recv_data == 0x09: # Follower to move right
      totalMoves(distance)
      print ("Received Follower move right")
    elif recv_data == 0x13: # Follower reports found token
      followerTokenFND()
    elif recv_data == 0x15: # Scanning Follower Servo
      print ("Received Scanning Beginning")
    elif recv_data == 0x16: # Scan returned Lead Found
      scanServo()
    elif recv_data == 0x17: # Scan returned Object Found
      scanServo()
    else:
      # Something unexpected happened
      print("Received unexpected data %d" % recv_data)
  try:
    cmdInput(listener.queue)
  except KeyboardInterrupt:
    pass
  listener.close()
예제 #14
0
class BluetoothPlugin(ConnectionPlugin):
    ADDR_FILE = 'config/bluetooth_address'

    def __init__(self):
        super().__init__()
        self.listener = Listener()
        self.addr = self.__get_bluetooth_addr()

    # API method
    def broadcast(self, msg):
        print("BROADCASTING")
        NetworkScanner(msg).start()

    # API method
    def run(self):
        self.listener.start()

    # API method
    def address(self):
        return self.addr

    def __get_bluetooth_addr(self):
        with open(BluetoothPlugin.ADDR_FILE, 'r') as file:
            addr = file.read()

        print("Bluetooth Address: {}".format(addr))
        return addr.strip()
예제 #15
0
def _listener(arguments):
    """
    Listener subcommand callback
    """
    logging.info('Starting Listener')
    listener = Listener(silence_time=arguments.silence_time, threshold=arguments.threshold, filename_prefix=arguments.filename_prefix)
    listener.get_utterance()
예제 #16
0
class BluetoothPlugin(ConnectionPlugin):
    ADDR_FILE = 'config/bluetooth_address'

    def __init__(self):
        super().__init__()
        self.listener = Listener()
        self.addr = self.__get_bluetooth_addr()

    # API method
    def broadcast(self, msg):
        print("BROADCASTING")
        NetworkScanner(msg).start()

    # API method
    def run(self):
        self.listener.start()

    # API method
    def address(self):
        return self.addr

    def __get_bluetooth_addr(self):
        with open(BluetoothPlugin.ADDR_FILE, 'r') as file:
            addr = file.read()

        print("Bluetooth Address: {}".format(addr))
        return addr.strip()
예제 #17
0
    def __run_remote(self, state):
        """
        Perform command(private method related to \"run\" method)
        This is for executing command on remote machine, which means it will interact with Listener.

        :param: state State

        :return: Dict state
        """
        interface = state["address"]

        if self.__get_command_type() == "FILE":
            raise RuntimeError("NOT IMPLEMENTED")

        if self.__get_recv() == "NONE":
            Listener().send_only(interface, self.__get_command(state))
        elif self.__get_recv() == "shell":
            Listener().send_only(interface, self.__get_command(state))
            Listener().update_state_as_address(interface)
            state["shell"] = Listener().get_state(interface)
        else:
            print("command : " + self.__get_command(state))
            response = Listener().send(interface, self.__get_command(state))
            if response == None:
                print("response : None")
            else:
                if len(response) > 30:
                    print("response : " + response[:30] + " ...")
                else:
                    print("response : " + response)
            if response != None:
                state[self.__get_recv()] = response
        return state
예제 #18
0
 def __init__(self):
     pyautogui.PAUSE = round(uniform(1.5, 2.3), 2)
     self.listener = Listener()
     self.search = Search()
     self.bglistener = None
     self.waypoints = []
     self.end = False
예제 #19
0
def _listener(arguments):
    """
    Listener subcommand callback
    """
    logging.info('Starting Listener')
    listener = Listener(silence_time=arguments.silence_time,
                        threshold=arguments.threshold,
                        filename_prefix=arguments.filename_prefix)
    listener.get_utterance()
예제 #20
0
 def __init__(self, is_debug):
     self.__init_base_services(is_debug)
     self.__init_plugins()
     self.__init_apps()
     self.last_msg = time.time()
     self.__monitoring_thread = threading.Thread(target=self.monitor_apps,
                                                 daemon=True)
     self.__monitoring_thread.start()
     self.__listener = Listener(self)
예제 #21
0
def main():
    global EXIT
    
    ##join with the tables
    hour_subscription=Subscriber()
    hour_subscription.subscribe('/topic/enrich/hour', 'join_hour', Listener(hour_subscription,hourly_action))
    day_subscription=Subscriber()
    day_subscription.subscribe('/topic/report/day', 'join_day', Listener(day_subscription,daily_action))
    while not EXIT:
        pass
예제 #22
0
    def __init__(self):
        Listener.__init__(self)

        self.parser = Parser()
        self.connection = Connection()

        self.connection.add_listener("readline", self.readline_handler)
        self.connection.add_listener("connect", self.connect_handler)
        self.connection.add_listener("disconnect", self.disconnect_handler)

        self.connection.connect()
예제 #23
0
    def __init__(self):
        #self.nc = NATS()

        #self.nc.connect()
        '''
        try:
            yield from nc.connect()
        except:
            pass
        '''

        super().__init__()

        #self.nc = NATS()
        #self.nc.connect()
        #self.nc.subscribe("help", "workers", cb=self.request_handler)

        self.ui = loadUi('ms_main.ui', self)
        self.model = Model(self)
        self.ui.lv_news.setModel(self.model)
        #self.setCentralWidget(ui)

        self.ui.lv_news.setItemsExpandable(False)
        self.ui.lv_news.setIndentation(0)
        self.ui.lv_news.setSelectionMode(QAbstractItemView.ExtendedSelection)

        toolBar = QToolBar()
        self.addToolBar(toolBar)

        delButton = QPushButton('削除')
        delButton.clicked.connect(self.removeItems)
        toolBar.addWidget(delButton)

        addButton = QPushButton('追加')
        addButton.clicked.connect(self.rcv_nats)
        toolBar.addWidget(addButton)

        addButton = QPushButton('publish')
        addButton.clicked.connect(self.nats_pub)
        toolBar.addWidget(addButton)

        self.addToolBar(toolBar)

        #loop = asyncio.get_event_loop()
        #component = Component(nc, loop)
        #thr = Thread(target=another_thread, args=(component,))
        #thr.start()

        #loop.run_forever()

        self.c = Listener(["nats://localhost:4222"])
        tt = TestThread(ccc=self.c)
        tt.start()
예제 #24
0
 def __init__(self,
              ctx,
              logger_name,
              logger_addr,
              rpcClient,
              loglevel_filter=logevent_pb2.L_FATAL):
     Listener.__init__(self, ctx, logger_name, logger_addr)
     self.trace_callback = self.printTraceNotif
     self.format_string = self.DEFAULT_MSG_FORMAT
     self.rpcClient = rpcClient
     self.loggers = []
     self.loglevel_filter = loglevel_filter
예제 #25
0
def main():
  listener = Listener()
  #incoming_message_Thread = Thread(target=incoming_message_handle, args=[listener.clientList], daemon=True)
  listener.start()
  #incoming_message_Thread.start()
  while True:
    try:
      recv_queue_data = listener.queue.get(timeout=1)
      print("Message : ", recv_queue_data)
    except Empty:
      print("empty")
      pass
  try:
      recv_data = recv_queue_data.msgtype
      message_pack_recv = recv_queue_data.msg
      if recv_data == "Rover Move": # Follower to move FORWARD
        if message_pack_recv == ROVER_FORWARD:
          #totalMoves(distance)
          print ("Received Follower move forward")
        elif message_pack_recv == ROVER_BACKWARD: # Follower to move BACKWARD
          #totalMoves(distance)
          print ("Received Follower move backward")
        elif message_pack_recv == ROVER_LEFT: # Follower to move LEFT
          #totalMoves(distance)
          print ("Received Follower move left")
        elif message_pack_recv == ROVER_RIGHT: # Follower to move RIGHT
          #totalMoves(distance)
          print ("Received Follower move right")
        elif message_pack_recv == ROVER_STOP: # Follower to STOP
          #totalMoves(distance)
          print ("Received Follower STOP")
      elif recv_data == "Follower Distance": # Follower reports distance traveled
        totalMoves(message_pack_recv)
        print ("Received Follower Distance: ", message_pack_recv)
      elif recv_data == "Follower Token Found": # Follower reports found token
        followerTokenFND()
      elif recv_data == "Scanning Follower Servo": # Scanning Follower Servo
        if message_pack_recv == SCAN_STARTED: # Servo Scan Started
          print ("Received Scanning Beginning")
        elif message_pack_recv == LEAD_FOUND: # Scan returned Lead Found
          scanServo()
        elif message_pack_recv == OBJECT_FOUND: # Scan returned Object Found
          scanServo()
      elif recv_data == "Follower Distance To Lead": # Follower reports found token
        print ("Received Follower Distance To Lead: ", message_pack_recv)
      else:
        # Something unexpected happened
        print("Received unexpected data %d" % recv_data)
  except KeyboardInterrupt:
    print("CTRL C Detected")
    return
  listener.close()
예제 #26
0
def main():
    """
	main function
	Creates the main Listener and calls listen()
	Catches the last exception and exit upon that
	:return: Program returned value
	"""
    l = Listener()
    try:
        l.listen()
    except Exception as e:
        print "Server main() exception: {}".format(e)
        sys.exit()
예제 #27
0
파일: driver.py 프로젝트: swiftcoder/aevum
def main(argv):
    input = FileStream(argv[1])
    lexer = aevumLexer(input)
    stream = CommonTokenStream(lexer)
    parser = aevumParser(stream)
    tree = parser.top_level()

    listener = Listener()
    walker = ParseTreeWalker()
    walker.walk(listener, tree)

    listener.typecheck()
    print(listener.emit())
예제 #28
0
    def __init__(self):
        self.queue_in = Queue()
        self.queue_out = Queue()
        self.predictor_queue = Queue()
        self.running = Value('i', False)
        self.tempo = Value('f', default_tempo)
        self.deadline = Value('f', 0)

        self.player = Player(self.queue_out, self.running, self.tempo,
                             self.deadline)
        self.predictor = ChordPredictor(self.queue_in, self.queue_out)
        self.listener = Listener(self.queue_in, self.running, self.tempo,
                                 self.deadline)
예제 #29
0
	def onSubscribe(self, _):
		if self.subscribed:
			self.listener.kill()
			self.listener.join()
			self.listener = None
			self.subscribed = False
			self.bSubscribe.SetLabel("Subscribe")
		else:
			ip = self.teIpAddr.GetValue()
			pt = self.teSPort.GetValue()
			self.listener = Listener(self, ip, pt)
			self.listener.start()
			self.subscribed = True
			self.bSubscribe.SetLabel("Unsubscribe")
예제 #30
0
파일: main.py 프로젝트: TheKysek/MiNode
def start_ip_listener():
    listener_ipv4 = None
    listener_ipv6 = None

    if socket.has_ipv6:
        try:
            listener_ipv6 = Listener(shared.listening_host,
                                     shared.listening_port,
                                     family=socket.AF_INET6)
            listener_ipv6.start()
        except Exception as e:
            logging.warning(
                'Error while starting IPv6 listener on port {}'.format(
                    shared.listening_port))
            logging.warning(e)

    try:
        listener_ipv4 = Listener(shared.listening_host, shared.listening_port)
        listener_ipv4.start()
    except Exception as e:
        if listener_ipv6:
            logging.warning(
                'Error while starting IPv4 listener on port {}. '.format(
                    shared.listening_port) +
                'However the IPv6 one seems to be working and will probably accept IPv4 connections.'
            )
        else:
            logging.error(
                'Error while starting IPv4 listener on port {}. '.format(
                    shared.listening_port) +
                'You will not receive incoming connections. Please check your port configuration'
            )
            logging.error(e)
예제 #31
0
def main():
    logging.basicConfig(filename='/var/log/executioner/executioner.log',
                        level=logging.INFO,
                        format='%(asctime)s %(message)s')

    #not handling signals because python can't reconcile them with multithreading. supposedly Py3.3 does though.
    #signal.signal(signal.SIGINT, handle_signal)
    #signal.signal(signal.SIGTERM, handle_signal)

    sys.stdout = LoggerWriter(logging.info)
    sys.stderr = LoggerWriter(logging.error)
    MotorController.init()
    SwitchController.init()
    listener = Listener()
    listener.start()
예제 #32
0
def delete(id=None):
    global listenter, database, args
    _, _, _, _, _, _, _, ke_path, model_path = database.get_macro(id)
    os.remove(ke_path)
    os.remove(model_path)
    database.delete_macro(id)
    try:
        listenter.stop()
    except Exception as e:
        pass
    if (len(database.get_all()) > 0):
        listenter = Listener(sensitivity=args.sensitivity,
                             speed_factor=args.speed_factor)
        listenter.start()
    return redirect('/')
예제 #33
0
    def listen(self) -> Listener:
        """Listen (Passive open) is the Action of waiting for Connections from remote Endpoints. Before listening
        the transport system will resolve transport properties for candidate protocol stacks. A local endpoint must be
        passed to the Preconnection prior to listen.

        :return: A listener object.
        """
        if not self.local_endpoint:
            shim_print("Listen error - Local Endpoint MUST be specified if when calling listen on the preconnection", level="error")
            backend.clean_up(self.__context)
            sys.exit(1)

        candidates = self.transport_properties.select_protocol_stacks_with_selection_properties()
        if candidates is None:
            shim_print("Unfulfilled error - No stacks meeting the given constraints by properties", level="error")
            if self.unfulfilled_handler:
                self.unfulfilled_handler()
            else:
                backend.clean_up(self.__context)

        backend.pass_candidates_to_back_end(candidates, self.__context, self.__flow)

        if self.security_parameteres:
            self.register_security(is_server=True)

        shim_print("LISTEN!")
        listener = Listener(self.__context, self.__flow, self.__ops, self)
        return listener
예제 #34
0
파일: model.py 프로젝트: ladriangb/Observer
 def __init__(self, id=None, data=None):
     if data is None:
         data = {}
     self.listeners = []
     self.attributes = data
     self.id = id
     listenerA = Listener("<Crud Notification>", self)
예제 #35
0
def main():
    global EXIT
    subscription = Subscriber()
    subscription.subscribe('/queue/analytics/hour', 'report_',
                           Listener(subscription, action))
    while not EXIT:
        pass
예제 #36
0
    def __run_local(self, state, interface):
        """
        Perform command.
        This is for executing command on local machine, which means it will not interact with Listener.

        :param: state State
        :param: interface A file path used as an interface between an agent and an external attack script.

        :return: Dict state
        """
        command = self.__get_command(state)
        args = shlex.split(command)
        args.append(interface)

        with open(os.devnull, "wb") as err:
            subprocess.Popen(args, stdout=err, stderr=err).communicate()

        with open(interface, "r") as f:
            state = json.load(f)

        if self.__get_recv() == "interface":
            pass
        elif self.__get_recv() == "shell":
            shell_state = Listener().get_state(state["address"])
            if shell_state != None:
                state["shell"] = shell_state
        else:
            raise RuntimeError("NOT IMPLEMENTED")

        return state
예제 #37
0
class DataGen(object):
    def __init__(self):
        conn1, conn2 = multiprocessing.Pipe()
        self.conn = conn2
        self.listener = Listener(debug_connection = conn1)
        self.listener.start()
        self.bpm_to_test = [0]
        self.bpm_energies = [0]

    def __iter__(self):
        return self
        
    def next(self):
        while self.conn.poll():
            self.bpm_to_test, self.bpm_energies = self.conn.recv()
        return (self.bpm_to_test, self.bpm_energies)
예제 #38
0
 def __init__(self):
     conn1, conn2 = multiprocessing.Pipe()
     self.conn = conn2
     self.listener = Listener(debug_connection = conn1)
     self.listener.start()
     self.bpm_to_test = [0]
     self.bpm_energies = [0]
예제 #39
0
 def loadLevel(self):
     if self.networkingEnabled:
         self.broadcaster = Broadcaster()
         self.listener = Listener()
         self.listener.start()
         self.broadcaster.start()
     if self.server or not self.networkingEnabled:
         self.remainingIDs.append([1,""])
         self.remainingIDs.append([2,""])
예제 #40
0
파일: kmlogger.py 프로젝트: andredalton/bcc
 def __init__(self):
     threading.Thread.__init__(self)
     self.devices = get_devices()
     self.keyfile = ".keymap"    # Arquivo padrão para o mapa de caracteres
     self.keymap = KeyMap(self.devices)
     self.listener = Listener(self.devices)
     self.history = History()
     self.lock = False
     self.listen()
     self.copy = False
예제 #41
0
def main():
    """
    Allows Winston to be installed as a package and to be run from the command line.

    This simply inits Winston using the config file.
    """

    # Define and start a scheduler. These store tasks that are run at given times
    scheduler = config.SCHEDULER
    scheduler.start()

    # Load the commands in the interpreter. These dispatch commands. See the Interpreter's doc for details.
    interpreter = Interpreter(scheduler=config.SCHEDULER)
    for command in config.COMMANDS:
        interpreter.register(command)

    # Create a listener for pocketsphinx. It forwards recognized strings to Interpreters. See Listener's doc for details.
    listener = Listener(fsg_path=config.GRAMMAR_FILE, dict_path=config.DICT_FILE)
    listener.register(interpreter)

    # And wait...
    raw_input()
예제 #42
0
class DIM:
    def __init__(self, host, port):
        # sageGate is the network connection with SAGE
        self.sageGate = SageGate()
        setSageGate(self.sageGate)

        # the event manager takes care of properly dispatching events
        self.evtMgr = EventManager()
        setEvtMgr(self.evtMgr)
        self.evtMgr.addHandlers()

        # sageData keeps the current state of the SAGE windows/apps
        self.sageData = SageData()
        setSageData(self.sageData)
        
        # overlay manager creates, destroys and updates overlays
        self.overlayMgr = OverlayManager()
        setOverlayMgr(self.overlayMgr)

        # contains all the devices and takes care of loading plugins for them
        # also, distributes HW messages to each device 
        self.devMgr = DeviceManager()
        setDevMgr(self.devMgr)

        # connect to SAGE
        for i in range(5):  # try to connect to SAGE for 5 seconds
            if self.sageGate.connectToSage(host, port) != 0:
                self.sageGate.registerSage()
                break
            time.sleep(1)
        else:  # we didn't manage to connect to sage in 5 seconds... so quit
            exitApp()

        # start listening for the device events
        time.sleep(2)   # wait till all the messages come in
        self.listener = Listener(LISTENER_PORT, self.devMgr.onHWMessage)
        self.listener.serve_forever()
예제 #43
0
파일: 03.py 프로젝트: BuloZB/development
def EmonHub():
    
    # Load settings
    settings = ConfigObj("emonhub.conf", file_error=True)
    
    # Create queue for node packets
    queue = Queue.Queue(0)

    # Create and start serial listener
    a = Listener(queue,settings)
    a.start()
    
    # Create and start http dispatcher
    b = Dispatcher(queue,settings)
    b.start()

    while 1:
        try:
            time.sleep(0.1)
        except KeyboardInterrupt:
            print "Stopping threads"
            a.stop = True
            b.stop = True
            break
예제 #44
0
    def init_listener(self, address_list, msg_type_list):
        '''Initialise listener that receives messages about new files
        to be processed, etc.
        '''
        # Create Pipe connection
        parent_conn, child_conn = Pipe()
        self.listener_parent_conn = parent_conn
        self.listener_child_conn = child_conn

        # Create a Listener instance
        self.listener = Listener(address_list=address_list, 
                                 msg_type_list=msg_type_list, 
                                 pipe=self.listener_child_conn)
        #self.listener.add_address_list(address_list)
        #self.listener.type_list = msg_type_list

        # Create subscriber
        #self.listener.create_subscriber()
        print "Listener initialised"
예제 #45
0
파일: main.py 프로젝트: spaibs/eCARus-IT
    def __init__(self):
        QMainWindow.__init__(self)

        # make variables
        self.voltage = 0
        self.current = 0

        # load gui.ui
        self.ui = loadUi('../gui/gui.ui')

        self.ui.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
        self.ui.destroyed.connect(self.shutdown)

        # show window
        self.ui.show()

        # make new log object
        self.log = Log(self.ui)

        # make new sender object
        self.sender = Sender(self.ui, self.log)

        # set events
        self.set_events()

        # initial reset
        self.sender.reset()

        # new listener
        self.listener = Listener()

        # new_data_received signal
        self.listener.data_received.connect(self.new_data_received)

        # start listener
        self.listener.start()

        # new interpreter
        self.interpreter = Interpreter(self.log, self.ui)

        # add tree
        self.add_tree()
예제 #46
0
파일: musicbox.py 프로젝트: ccampbell/mmlx
    def play(self, args, local):
        # create an intial logger so we can log before args are processed
        self.logger = Logger({"verbose": False})
        self.drawLogo()

        options = self.processArgs(args, local)
        self.options = options

        # set up the logger with the correct options
        self.logger = Logger(self.options)

        listener = Listener(self.logger)
        listener.onChange(self.processFile)

        if os.path.isdir(options['start']) and not os.path.isdir(options['end']):
            os.mkdir(options['end'])

        if self.options['listen']:
            listener.watch(options['start'], options['end'])
        else:
            listener.process(options['start'], options['end'])
            self.logger.log(self.logger.color('Done!', self.logger.PINK))
            sys.exit(0)
예제 #47
0
파일: main.py 프로젝트: TheKysek/MiNode
def start_ip_listener():
    listener_ipv4 = None
    listener_ipv6 = None

    if socket.has_ipv6:
        try:
            listener_ipv6 = Listener(shared.listening_host, shared.listening_port, family=socket.AF_INET6)
            listener_ipv6.start()
        except Exception as e:
            logging.warning('Error while starting IPv6 listener on port {}'.format(shared.listening_port))
            logging.warning(e)

    try:
        listener_ipv4 = Listener(shared.listening_host, shared.listening_port)
        listener_ipv4.start()
    except Exception as e:
        if listener_ipv6:
            logging.warning('Error while starting IPv4 listener on port {}. '.format(shared.listening_port) +
                            'However the IPv6 one seems to be working and will probably accept IPv4 connections.')
        else:
            logging.error('Error while starting IPv4 listener on port {}. '.format(shared.listening_port) +
                          'You will not receive incoming connections. Please check your port configuration')
            logging.error(e)
예제 #48
0
    elif msgstring == "start":
      try:
        testcase = int(input("Select Test Case:"))
        assert testcase in range(1, 8)
      except (TypeError, AssertionError):
        print("Test case does not exist")
        continue
      listener.queue.put(InternalMessage(ROUTER, START_GAME, bytes([testcase])))

    elif msgstring == "end":
      listener.queue.put(InternalMessage(ROUTER, END_GAME, bytes([0])))

    else:
      msgstring = msgstring.encode()
      while msgstring:
        msg = InternalMessage(ROUTER, DEBUG_MSG, msgstring[:INTERNAL_MSG_SIZE + 1])
        listener.queue.put(msg)
        msgstring = msgstring[INTERNAL_MSG_SIZE + 1:]

if __name__ == "__main__":
  listener = Listener()
  outWorker = OutboundWorker(listener.queue, listener.clientList, listener.clientDict)
  listener.start()
  outWorker.start()
  try:
    cmdInput(listener)
  except KeyboardInterrupt:
    pass
  listener.close()

#!/usr/bin/python
# this script needs root privileges

from listener import Listener

listener = Listener()

listener.initTemperature(15)
listener.initCapturing(10)

listener.sendSMS("Device is up and listening")
listener.listenForCommands()
예제 #50
0
#!/usr/bin/python
# this script needs root privileges

from listener import Listener
import time
import thread
import datetime
import os

os.system("export LD_LIBRARY_PATH=/usr/local/lib")


# crash-catching loop
while True:
    try:
        listener = Listener()
        listener.initCapturing(60)
        listener.initGetTimeFromGPS(600)
        
        # listen for commands via SMS
        thread.start_new_thread( listener.listenForCommands, () )
        listener.sendSMS("Device is up and listening")
        
        # main loop
        while True:
            time.sleep(4)
            
            temperatureExternal= listener.getTemperatureExternal()
            
            temperatureInternal = listener.getTemperatureInternal()
            
예제 #51
0
# initialize ALSA 
alsaseq.client( 'MidiCube', 1, 1, False )
if params.alsaOut is not None:
    (client, port) = params.alsaOut
    alsaseq.connectto(0, client, port)
if params.alsaIn is not None:
    (client, port) = params.alsaIn
    alsaseq.connectfrom(0, client, port)

# connect to bluetooth device
sock = com.connect(params.btMAC)
if not sock:
    logging.error('connection to MIDI cube failed')
    exit(-1)

listener = Listener(sock, params.btMAC)
scheduler = Scheduler(params)
alsain = alsaInput()

scheduler.start()
listener.start()
time.sleep(1)

com.stopCube(sock)
if not com.startCube(sock):
    terminate()

try:
    while True:
        time.sleep(1)
        if sync.disconnect.isSet():
예제 #52
0
파일: main.py 프로젝트: Peque/Pyro4
from __future__ import print_function
import sys
import Pyro4
from listener import Listener


if len(sys.argv) != 2:
    print("Give topic as argument.")
else:
    topic = sys.argv[1].strip()
    if not topic:
        raise ValueError("Must give topic name.")
    listener = Listener(topic)
    daemon = Pyro4.Daemon()
    daemon.register(listener)
    listener.register_with_dispatcher()
    print("Listener for topic {} waiting for data.".format(topic))
    daemon.requestLoop()
예제 #53
0
파일: main.py 프로젝트: alberand/database
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import logging.config

from config import config
from listener import Listener

logging.filename = 'logs/{}_log'.format(config['server_name'])
logging.config.fileConfig('logging.ini')

if __name__ == '__main__':
    if '-h' in sys.argv or '--help' in sys.argv:
        print('Run this file and as the first argument send name of the config'
              'file. For example: python main.py config.ini')

    if len(sys.argv) < 2:
        logging.error('Please specify config name.')
        sys.exit(1)

    listener = Listener()
    try:
        listener.start()
    except KeyboardInterrupt:
        logging.info('KeyboardInterrupt. Exiting...')
        listener.stop()
        listener.join()
예제 #54
0
 def __init__(self, address='127.0.0.1',
              port=8035, torrent=None):
     Listener.__init__(self, address, port)
     assert torrent
     self.torrent = torrent
예제 #55
0
파일: monitor.py 프로젝트: jjdmol/LOFAR
#! /usr/bin/env python


from config import Config # this is a subdir
from listener import Listener
from poller import Poller
import sys

if __name__ == "__main__":
    """Run the monitor. The listener class waits for requests. The
    poller class polls the PIDs that were input and forwards output
    to the output class."""
    parpid = sys.argv[1]
    cfg = Config()
    cfg.add_item('parentpid',parpid)
    lst = Listener(cfg)
    lst.start()
    print "listener started"
    # Where is the output class?
    
    pol = Poller(cfg)   
    pol.start()
    print "Poller started"
예제 #56
0
	def start( self ):
		myConfigurationFile = ConfigurationFile( self.fileName )
		myConfiguration = myConfigurationFile.load()

		myListener = Listener( myConfiguration )
		myListener.start()
예제 #57
0
 def __init__(self, address='127.0.0.1',
              port=7000, torrent=None):
     Listener.__init__(self, address, port)
     self.torrent = torrent
예제 #58
0
 def __init__(self):
     Listener.__init__(self)
     Thread.__init__(self)
     print "init"
예제 #59
0
파일: main.py 프로젝트: spaibs/eCARus-IT
class Main(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        # make variables
        self.voltage = 0
        self.current = 0

        # load gui.ui
        self.ui = loadUi('../gui/gui.ui')

        self.ui.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
        self.ui.destroyed.connect(self.shutdown)

        # show window
        self.ui.show()

        # make new log object
        self.log = Log(self.ui)

        # make new sender object
        self.sender = Sender(self.ui, self.log)

        # set events
        self.set_events()

        # initial reset
        self.sender.reset()

        # new listener
        self.listener = Listener()

        # new_data_received signal
        self.listener.data_received.connect(self.new_data_received)

        # start listener
        self.listener.start()

        # new interpreter
        self.interpreter = Interpreter(self.log, self.ui)

        # add tree
        self.add_tree()

    def add_tree(self):
        # Items for tree
        voltage_item = QTreeWidgetItem(["Spannung", str(self.voltage) + " V"])
        self.ui.treeView.addTopLevelItem(voltage_item)

        current_item = QTreeWidgetItem(["Strom", str(self.current) + " A"])
        self.ui.treeView.addTopLevelItem(current_item)

        power_item = QTreeWidgetItem(["Watt", "0 W"])
        self.ui.treeView.addTopLevelItem(power_item)

    def set_events(self):
        # sendButton clicked
        self.ui.sendButton.clicked.connect(lambda: self.sender.send("debug"))

        # holdButton clicked
        self.ui.holdButton.clicked.connect(self.log.toggle_hold)

        # clearButton clicked
        self.ui.clearButton.clicked.connect(self.log.clear_log)

        # messageInput return pressed
        self.ui.messageInput.returnPressed.connect(lambda: self.sender.send("debug"))

        # sliders value changed
        self.ui.voltageSlider.sliderReleased.connect(lambda: self.sender.send("slider-voltage"))
        self.ui.currentSlider.sliderReleased.connect(lambda: self.sender.send("slider-current"))

        # reset action
        self.ui.resetActionButton.triggered.connect(self.sender.reset)

        # automode checkbox
        self.ui.automodeCheckbox.stateChanged.connect(lambda: self.sender.send("checkbox-automode"))

        # lamp checkboxes
        self.ui.lamp1Checkbox.stateChanged.connect(lambda: self.sender.send("checkbox-lamp"))
        self.ui.lamp2Checkbox.stateChanged.connect(lambda: self.sender.send("checkbox-lamp"))
        self.ui.lamp3Checkbox.stateChanged.connect(lambda: self.sender.send("checkbox-lamp"))
        self.ui.lamp4Checkbox.stateChanged.connect(lambda: self.sender.send("checkbox-lamp"))

    def new_data_received(self, text):
        self.interpreter.interpret(text)

    def shutdown(self):
        self.listener.exit()
예제 #60
-1
파일: dim.py 프로젝트: Vadiza/sage-3.5b
    def __init__(self, host, port, loadState, autosave, doLog):
       
        print "\n\n=========   Starting DIM  ============\n"

        # the log object
        if doLog:
            setLog(Log())
            print "Logging user interaction into: ", getLog().getLogFilename(), "\n\n"

        # sageGate is the network connection with SAGE
        self.sageGate = SageGate()
        setSageGate(self.sageGate)

        # the event manager takes care of properly dispatching events
        self.evtMgr = EventManager()
        setEvtMgr(self.evtMgr)
        self.evtMgr.addHandlers()

        # sageData keeps the current state of the SAGE windows/apps
        self.sageData = SageData(autosave, self.sageGate)
        setSageData(self.sageData)
        
        # overlay manager creates, destroys and updates overlays
        self.overlayMgr = OverlayManager()
        setOverlayMgr(self.overlayMgr)

        # contains all the devices and takes care of loading plugins for them
        # also, distributes HW messages to each device 
        self.devMgr = DeviceManager()
        setDevMgr(self.devMgr)

        # connect to SAGE
        if (DEBUG):
            print "\n\nRUNNING IN DEBUG MODE!!!!\n\n"
        else:
            time.sleep(2)
        
        for i in range(20):  # try to connect to SAGE for X seconds
            retval = self.sageGate.connectToSage(host, port)
            if retval == 1:
                self.sageGate.registerSage("dim")
                print "DIM: successfully connected to SAGE", (host, port)
                break
            elif retval == 0:
                print "DIM: SAGE", (host, port), "is not ready yet. Retrying..."
            elif retval == -1:
                print "DIM: Couldn't connect to appLauncher. appLauncher is not ready yet. Retrying..."
            time.sleep(1)
        else:  # we didn't manage to connect to sage in X seconds... so quit
            exitApp()

        # start listening for the device events
        time.sleep(2)   # wait till all the messages come in
        self.overlayMgr._addGlobalOverlays()   # add all the UI plugins for the display

        # automatically load a saved state if so desired
        if loadState:
            print "\n===> Autoloading state: ", loadState, "\n"
            t = Timer(3, self.sageData.loadState, [loadState])
            t.start()
        
        self.listener = Listener(LISTENER_PORT, self.devMgr.onHWMessage)
        self.listener.serve_forever()