Esempio n. 1
0
    def process_request(self, command, request):
        # default : "" = not respond anything
        result = json.dumps("")
        if command == 'get_successor':
            successor = self.successor()
            result = json.dumps(
                (successor.address_.ip, successor.address_.port))
        if command == 'get_predecessor':
            # we can only reply if we have a predecessor
            pred = self.predecessor_
            if pred != None:
                predecessor = pred
                result = json.dumps(
                    (predecessor.address_.ip, predecessor.address_.port))
        if command == 'find_successor':
            successor = self.find_successor(int(request))
            result = json.dumps(
                (successor.address_.ip, successor.address_.port))
        if command == 'closest_preceding_finger':
            closest = self.closest_preceding_finger(int(request))
            result = json.dumps((closest.address_.ip, closest.address_.port))
        if command == 'notify':
            npredecessor = Address(
                request.split(' ')[0], int(request.split(' ')[1]))
            self.notify(Remote(npredecessor))
        if command == 'get_successors':
            result = json.dumps(self.get_successors())

        # or it could be a user specified operation
        for t in self.command_:
            if command == t[0]:
                result = t[1](request)
            self.log('sending response: ' + result)

        return result
Esempio n. 2
0
async def global_data_updater():
    remote = Remote(SOCK_PATH)
    while True:
        try:
            new_data = {}
            data = remote.get_global()
            diff = await Cached.update_global(data)
            if diff:
                new_data['global'] = diff
            data = remote.get_torrents()
            diff = await Cached.update_torrents(data)
            if diff:
                new_data['torrents'] = diff
            plugins_data = {}
            for plugin in Cached.plugins:
                plugin_output = await plugin.get(False)
                if plugin_output is not None:
                    plugins_data[plugin.name()] = plugin_output
            if plugins_data:
                new_data['plugins'] = plugins_data
            if len(new_data) > 0:
                await Cached.notify_clients(new_data)
        except Exception as e:
            logger.error(e, exc_info=e)
            asyncio.get_running_loop().stop()
            return
        await asyncio.sleep(RTR_RETR_INTERVAL)
Esempio n. 3
0
 def __new__(self, hostfile, passfile):
     self.hostfile = hostfile
     self.passfile = passfile
     if not self._instance:
         self._instance = super(MyServer, self).__new__(self)
         self.remote_server = Remote(self.hostfile, self.passfile)
     return self._instance
Esempio n. 4
0
 def setNext(self, ip, port) -> None:
     if (ip == self.ip and int(port) == self.port):
         self.next = self
     else:
         self.next = Node(ip, port)
         self.next.connection = Remote(self.next.ip, self.next.port)
     print('Added %s:%s as next' % (ip, port))
Esempio n. 5
0
def test_global_data():
    g = Remote(SOCK_PATH).get_global()
    assert g.throttle_global_down_max_rate == 1024
    assert g.throttle_global_up_max_rate == 1024
    assert g.network_max_open_files == 8000
    assert g.network_port_range == '22400-22400'
    assert g.network_listen_port == 22400
Esempio n. 6
0
def main():
    print('Receptor de Senales de Alarma Version 1.65')
    Lic = LicCheck()
    if Lic == True:
        if Modo != None:
            t = threading.Thread(target=AvisodeApertura, args=[Lic])
            t.setDaemon(False)
            t.start()

            #AvisodeApertura(Lic)
            app = QApplication(sys.argv)
            import qt4reactor
            qt4reactor.install()
            from twisted.internet import reactor
            #app.setStyle(QStyleFactory.create("plastique"))
            w = MainWindow(reactor)
            #Retornamos en BD 'No hay BD' en caso de que no se consiga la BD
            #Si el receptor esta en MODO de BD. Para que no muestre nunca la
            #Ventana.

            bd = w.IniciarReceptores()
            w.show()
            a = Remote(w)
            a.Iniciar()
            if bd == 'No hay BD':
                pass
            else:

                reactor.run()
                #sys.exit(app.exec_())

    else:
        AvisodeApertura(Lic)
        pass
Esempio n. 7
0
def test_api_version():
    sock_path = os.getenv('RTR_SCGI_SOCKET_PATH', SOCK_PATH)
    remote = Remote(sock_path)
    g = remote.get_global()
    assert g.system_client_version == os.getenv('RTR_SYSTEM_CLIENT_VERSION',
                                                '0.0.0')
    assert g.system_api_version == int(os.getenv('RTR_SYSTEM_API_VERSION', 0))
Esempio n. 8
0
def main():
    """ A remote control that is programmed to control the light in button 0
    and the garage door in the button 6
    """

    print("Initialization of the remote")
    remote = Remote()
    print(remote)

    # Programming button 1 to control lights
    light = Light()
    light_command = LightCommand(light)
    remote.set_command(0, light_command)
    print(remote)

    # Programming button 1 to control garage door
    garage_door = GarageDoor()
    garage_command = GarageDoorCommand(garage_door)
    remote.set_command(6, garage_command)
    print(remote)

    print("Testing possible actions")
    remote.press_on(0)
    remote.press_off(0)
    remote.press_on(6)
    remote.press_off(6)
    remote.press_on(1)
    remote.press_off(1)
Esempio n. 9
0
 def __init__(self):
     self.active_event = None
     self.lamp_timeout = 10
     self.double_timeout = 0.3
     self.inactive_events = {
         Spotify.NAME: Spotify(),
         Kodi.NAME: Kodi(),
         WatchTv.NAME: WatchTv(),
         WatchPlay.NAME: WatchPlay()
     }
     self.input_keys = {
         "up": Kodi,
         "down": WatchTv,
         "left": Spotify,
         "right": WatchPlay
     }
     self.lamp_keys = {
         "up": "ceiling",
         "left": "bed",
         "right": "sofa",
         "down": "all"
     }
     self.lamp_group = LampGroup({
         "sofa": Lamp(100, 1),
         "ceiling": Lamp(100, 2),
         "bed": Lamp(100, 3),
     })
     self.remotes = [Remote()]
     self.active_modkey = None
Esempio n. 10
0
def test_api_11_global():
    g = Remote(SOCK_PATH).get_global()
    if g.system_api_version >= 11:
        values = {
            cmd.replace('.', '_')
            for cmd in Remote.COMMANDS_PER_API_VERSION[11]
        }
        assert len(g.__dict__.keys() & values) == len(values)
Esempio n. 11
0
def test_peers():
    remote = Remote(SOCK_PATH)
    for hash in [
            'A6B69431743F085D96692A81C6282617C50243C4',
            '67DD1659106DCDDE0FEC4283D7B0C84B6C292675'
    ]:
        peers = remote.get_peers(hash)
        assert len(peers) == 0
Esempio n. 12
0
 def setPrevious(self, ip, port) -> None:
     if (ip == self.ip and int(port) == self.port):
         self.previous = self
     else:
         self.previous = Node(ip, port)
         self.previous.connection = Remote(self.previous.ip,
                                           self.previous.port)
     print('Added %s:%s as previous' % (ip, port))
Esempio n. 13
0
	def run(self):
		# should have a threadpool here :/
		# listen to incomming connections
		self.socket_ = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		self.socket_.bind((self.address_.ip, int(self.address_.port)))
		self.socket_.listen(10)

		while 1:
			self.log("run loop")
			try:
				conn, addr = self.socket_.accept()
			except socket.error:
				self.shutdown_ = True
				break

			request = read_from_socket(conn)
			command = request.split(' ')[0]

			# we take the command out
			request = request[len(command) + 1:]

			# defaul : "" = not respond anything
			result = json.dumps("")
			if command == 'get_successor':
				successor = self.successor()
				result = json.dumps((successor.address_.ip, successor.address_.port))
			if command == 'get_predecessor':
				# we can only reply if we have a predecessor
				if self.predecessor_ != None:
					predecessor = self.predecessor_
					result = json.dumps((predecessor.address_.ip, predecessor.address_.port))
			if command == 'find_successor':
				successor = self.find_successor(int(request))
				result = json.dumps((successor.address_.ip, successor.address_.port))
			if command == 'closest_preceding_finger':
				closest = self.closest_preceding_finger(int(request))
				result = json.dumps((closest.address_.ip, closest.address_.port))
			if command == 'notify':
				npredecessor = Address(request.split(' ')[0], int(request.split(' ')[1]))
				self.notify(Remote(npredecessor))
			if command == 'get_successors':
				result = json.dumps(self.get_successors())

			# or it could be a user specified operation
			for t in self.command_:
				if command == t[0]:
					result = t[1](request)

			send_to_socket(conn, result)
			conn.close()

			if command == 'shutdown':
				self.socket_.close()
				self.shutdown_ = True
				self.log("shutdown started")
				break
		self.log("execution terminated")
Esempio n. 14
0
 def remote(self, name='origin'):
     """
     Return
         Remote with the specified name
     
     Raise 
         ValueError if no remote with such a name exists
     """
     return Remote(self, name)
Esempio n. 15
0
    def setup(self):
        self.config = Config.load('config.json')

        self.remote = Remote()
        self.deviceMgr = devices.DeviceManager(self.remote)
        self.deviceMgr.setEventHandler(
            lambda device, event, data: self.handleEvent(device, event, data))
        Config.loadDevicesFromConfigData(self.config, self.deviceMgr)
        self.deviceMgr.initDevices()
Esempio n. 16
0
def test_trackers():
    remote = Remote(SOCK_PATH)
    trackers = remote.get_trackers('A6B69431743F085D96692A81C6282617C50243C4')
    assert len(trackers) == 2
    for t in trackers:
        assert t.is_enabled == 1
    trackers = remote.get_trackers('67DD1659106DCDDE0FEC4283D7B0C84B6C292675')
    assert len(trackers) == 6
    for t in trackers:
        assert t.is_enabled == 1
Esempio n. 17
0
def test_files():
    remote = Remote(SOCK_PATH)
    files = remote.get_files('A6B69431743F085D96692A81C6282617C50243C4')
    assert len(files) == 1
    assert files[0].path == 'debian-10.2.0-amd64-DVD-1.iso'
    assert files[0].size_bytes == 3918200832
    files = remote.get_files('67DD1659106DCDDE0FEC4283D7B0C84B6C292675')
    assert len(files) == 1
    assert files[0].path == '2ROrd80'
    assert files[0].size_bytes == 6964641792
Esempio n. 18
0
    def __init__(self, jobs_data, remote):
        """Create the submitter object

        Args:
            jobs_data: dict type, all information of the jobs to be managed
            remote: string type, the remote machine
        """
        super(SubmitterBase, self).__init__()
        self._data = jobs_data
        self._remote = Remote(remote)
Esempio n. 19
0
 def attemptConnection(self, ip_address, port, username, password):
     kodi = Kodi(username, password, ip_address, port)
     isConnected = kodi.Connect()
     if isConnected:
         print('Connected. Load remote window')
         self.builder.get_object('windowSetup').hide()
         remoteWin = Remote({'ip_address': ip_address, 'port': port, 'username': username, 'password': password})
         remoteWin.load_window(self.builder)
     else:
         print('Unable to connect. Keep showing setup window')
Esempio n. 20
0
def main():
    remote = Remote()
    lights = Lights()
    lights_on_command = LightsOnCommand(lights)
    lights_off_command = LightsOffCommand(lights)

    remote.set_command(lights_on_command)
    remote.pressButton()

    remote.set_command(lights_off_command)
    remote.pressButton()
Esempio n. 21
0
 def __init__(self, address="0.0.0.0:8081", stderr=sys.stderr):
     if (':' in address):
         self.port = address.split(":")[1]
     else:
         self.port = "8081"
     self.commands = {}
     with open("commands.config") as f:
         self.commands = json.load(f)
     self.error_message = "Command '%s' not found"
     self.stderr = stderr
     self.habitat_remote = Remote(address)
Esempio n. 22
0
def build_html(ip, username, password):

    remote = Remote(ip, username, password)
    shows = sorted(list_tv_shows(remote), key=lambda x: x.name)
    films = sorted(list_films(remote), key=lambda x: x.name)

    jinja2_env = jinja2.Environment(loader=jinja2.FileSystemLoader("."),
                                    extensions=['jinja2_time.TimeExtension'])

    return (jinja2_env.get_template('template.tpl').render(shows=shows,
                                                           films=films))
Esempio n. 23
0
def set_remote_config_url(url):
    """
    Set the base url for the REST query layer, normally taken from the user configuration file
    at ~/.materialscommons/config.json

    :param url: the URL as a string
    :return: None

    >>> mcapi.set_remote_config_url("http://mctest.localhost/api")

    """
    set_remote(Remote(config=Config(override_config={'mcurl': url})))
Esempio n. 24
0
    def join(self, remote_address=None):
        # initially just set successor
        self.finger_ = [None for x in range(LOGSIZE)]

        self.predecessor_ = None

        if remote_address:
            remote = Remote(remote_address)
            self.finger_[0] = remote.find_successor(self.id())
        else:
            self.finger_[0] = self

        self.log("joined")
Esempio n. 25
0
	def join(self, remote_address = None):
		# initially just set successor
		self.finger_ = list(map(lambda x: None, range(LOGSIZE)))

		self.predecessor_ = None

		if remote_address:
			remote = Remote(remote_address)
			self.finger_[0] = remote.find_successor(self.id())
		else:
			self.finger_[0] = self

		self.log("joined")
Esempio n. 26
0
def test_torrents():
    torrents = Remote(SOCK_PATH).get_torrents()
    assert len(torrents) >= 2
    for t in torrents:
        if t.hash == 'A6B69431743F085D96692A81C6282617C50243C4':
            assert t.name == 'debian-10.2.0-amd64-DVD-1.iso'
            assert t.size_bytes == 3918200832
            assert t.tracker_size == 2
            assert t.size_files == 1
        elif t.hash == '67DD1659106DCDDE0FEC4283D7B0C84B6C292675':
            assert t.name == '2ROrd80'
            assert t.size_bytes == 6964641792
            assert t.tracker_size == 6
            assert t.size_files == 1
Esempio n. 27
0
def run():
    log.basicConfig(format="[ %(asctime)s ] [ %(levelname)s ] %(message)s", level=log.INFO, stream=sys.stdout)

    # GrowBot 2
    r = Remote("e3dde6f2-5925-42e4-b37d-5214f18ae798", "ws://localhost:8080")
    print("Test")
    r.create_log_entry(LogType.UNKNOWN, "Hello, world!")
    print("Created")

    asyncio.ensure_future(r.connect())

    loop = asyncio.get_event_loop()
    pending = asyncio.Task.all_tasks()
    loop.run_until_complete(asyncio.gather(*pending))
Esempio n. 28
0
 def sendResponse(self, request, response):
     responseNodeIP = request['responseNodeIP']
     responseNodePort = int(request['responseNodePort'])
     if (self.ip == responseNodeIP and self.port == responseNodePort
             and 'requestID' not in request):
         return response
     try:
         requestID = request['requestID']
     except:
         return None
     conn = Remote(responseNodeIP, responseNodePort)
     res = json.dumps({
         'type': 'response',
         'requestID': requestID,
         'response': response
     })
     conn.send(res)
     return None
Esempio n. 29
0
    def __init__(self):
        self.vision = Vision(RobotController.model_xml,
                             RobotController.model_bin,
                             self,
                             is_headless=True,
                             live_stream=True,
                             confidence_interval=0.5)

        self.received_frame = None
        self.qr_reader = QRReader()
        self.last_qr_approached = None
        self.current_qr_approached = None
        self.approach_complete = True
        self.retrying_approach = False
        self.standby_mode = True
        self.standby_invoked = True
        self.serial_io = SerialIO('/dev/ttyACM0', 115200, self)
        self.actions = {}
        self.watered = False

        if config.RESPOND_TO_API:
            host = config.API_HOST
            if config.API_SECURE:
                host = "wss://" + host
            else:
                host = "ws://" + host

            self.remote = Remote(config.UUID, host)
            self.remote.add_callback(RPCType.MOVE_IN_DIRECTION,
                                     self.remote_move)
            self.remote.add_callback(RPCType.EVENTS, self.on_events_received)
            self.remote.add_callback(RPCType.SET_STANDBY, self.set_standby)

            rm_thread = threading.Thread(target=self.thread_remote,
                                         name="remote",
                                         daemon=True)
            rm_thread.start()
            # rm_thread.join()

        # Create the navigation system
        self.navigator = Navigator(self, verbose=True)

        threading.Thread(target=self.vision.start, name="vision").start()
Esempio n. 30
0
def remote_cmd(req):
    username = req.COOKIES.get('name', '')
    if req.method == 'POST' and req.POST:
        #type =  req.POST.get("submit_type",None)
        if 'sendcmd' in req.POST:
            ip = req.POST['ip']
            usr = req.POST['username']
            passwd = req.POST['password']
            cmd = req.POST['cmd']
            if req.POST['port']:
                port = int(req.POST['port'])
            else:
                port = 22
            #存储到历史指令
            db_cmd = CmdList()
            db_cmd.cmd = cmd
            db_cmd.host = ip
            db_cmd.time = datetime.datetime.now()
            print db_cmd.time
            db_cmd.save()
            #远程发送指令
            handler = Remote(ip, usr, passwd, port)
            recv = handler.ssh(cmd)
            showTag = 'recv'
            return render(req, 'remote_cmd.html', locals())
        elif 'history' in req.POST:
            #查询最近8条命令
            CMDs = CmdList.objects.order_by('-id')[:8]
            result = []
            for item in CMDs:
                result.append({
                    'time': item.time.strftime('%m-%d %H:%M:%S'),
                    'cmd': item.cmd,
                    'host': item.host
                })
            showTag = 'result'
            # print result
            return render(req, 'remote_cmd.html', locals())
        else:
            return render(req, 'remote_cmd.html')
    else:
        return render(req, 'remote_cmd.html')