def service_enable_request(): enable = True if request.json['enabled'].lower() == "true" else False WatchDog.get_instance().enable_disable_driver(enable) global controller platform = PiRevEn.detect_platform() if PlatformEn[request.json['platform']] == PlatformEn.SHELBYGT500: from components.core.PiCarController import PiCarController controller = PiCarController.get_instance() controller.activate_control(enable, PlatformEn.SHELBYGT500) return Response(request.data) if platform == PiRevEn.PI3B_PLUS: global __speed_service, __steer_service, speed_driver, steer_driver controller = None import rpyc if enable and not (speed_driver or steer_driver): __speed_service = rpyc.connect_by_service("SpeedDriver") __steer_service = rpyc.connect_by_service("SteeringDriver") speed_driver = __speed_service.root steer_driver = __steer_service.root speed_driver.enable_disable_driver(True) steer_driver.enable_disable_driver(True) else: speed_driver.enable_disable_driver(False) steer_driver.enable_disable_driver(False) __speed_service.close() __steer_service.close() speed_driver, steer_driver = None, None __speed_service, __steer_service = None, None return Response(request.data) else: return Response(status=409)
def set_states(a, b): """ Attempts to set the ports valves on ports A and B to the specified values. ARGUMENTS: both arguments are binary numbers as strings, each bit represents the state of a valve a - state of port A b - same, for port B RETURNS: A status code, and a message intended for relaying to the end user. Status codes: 0 - Success 1 - Serial Error (any kind) Any other kind of exception results in raising an actual exception. Other exceptions may appear. In any case, they will return a status code higher than 0. """ SUCCESS, FAIL = 0, 1 try: # Connect to RPyC server and get main object connection = rpyc.connect_by_service("LBNCCONTROLLER") r = connection.root r.open_serial() except DiscoveryError, e: return FAIL, "Serial interface daemon unreachable."
def login(self,retry = True): ''' Log in to the controller. First try to reach the controller via the standard service registry, if that fails try to access it via the supplied hostname/port arguments. If that fails, sleep a little and try again. ''' while True: try: self.conn = rpyc.connect_by_service(const.ctrlServiceName,config = {"allow_public_attrs" : True}) break except: try: self.conn = rpyc.connect(self.ctrlrHost,self.ctrlrPort,config = {"allow_public_attrs" : True}) break except: if retry == False: return False time.sleep(5) continue self.bgsrv = rpyc.BgServingThread(self.conn,self.handleBgServingThreadException) resp = self.conn.root.login(self.hostAddress,self.callback,self.riapsApps) if type(resp) == tuple and resp[0] == 'dbase': # Expected response: (redis) database host:port pair if self.depm != None: self.depm.doCommand(('setDisco',) + resp[1:]) return True else: pass # Ignore any other response return False
def service_enable_request(): enable = True if request.json['enabled'].lower() == "true" else False platform = PiRevEn.detect_platform() global ultrasonic if platform == PiRevEn.PIZEROW: ultrasonic = UltrasonicSensor.get_instance() ultrasonic.enable_disable_driver(enable) elif platform == PiRevEn.PI3B_PLUS: global ultrasonic_service if enable: import rpyc ultrasonic_service = rpyc.connect_by_service("UltrasonicSensor") ultrasonic = ultrasonic_service.root ultrasonic.enable_disable_driver(True) elif ultrasonic: ultrasonic.enable_disable_driver(False) ultrasonic_service.close() ultrasonic = None ultrasonic_service = None else: raise Exception('Cannot initialize Ultrasonic Sensor due to invalid platform!') return Response(request.data)
def service_enable_acc_request(): enable = True if request.json['enabled'].lower() == "true" else False platform = PiRevEn.detect_platform() global acc if platform == PiRevEn.PIZEROW: from components.drivers.ShelbyGT500.HBridgeSpeedDriver import HBridgeSpeedDriver acc = AdaptiveCruiseController.get_instance() speed_driver = HBridgeSpeedDriver.get_instance() acc.enable_disable_driver(enable, speed_driver) elif platform == PiRevEn.PI3B_PLUS: import rpyc global acc_service if enable: acc_service = rpyc.connect_by_service("AdaptiveCruise") acc = acc_service.root acc.enable_disable_driver(True) else: acc.enable_disable_driver(False) acc_service.close() acc = None acc_service = None else: raise Exception( 'Cannot initialize adaptive cruise control due to invalid platform!' ) return Response(request.data)
def service_enable_colav_request(): enable = True if request.json['enabled'].lower() == "true" else False platform = PiRevEn.detect_platform() global colav if platform == PiRevEn.PIZEROW: from components.drivers.ShelbyGT500.HBridgeSpeedDriver import HBridgeSpeedDriver colav = CollisionAvoidanceSystem.get_instance() speed_driver = HBridgeSpeedDriver.get_instance() colav.enable_disable_driver(enable, speed_driver) elif platform == PiRevEn.PI3B_PLUS: import rpyc global colav_service if enable: colav_service = rpyc.connect_by_service("CollisionAvoidance") colav = colav_service.root colav.enable_disable_driver(True) else: colav.enable_disable_driver(False) colav.close() colav = None colav_service = None else: raise Exception( 'Cannot initialize collision avoidance due to invalid platform!') return Response(request.data)
def __pid_control_speed(self, speed_driver): platform = PiRevEn.detect_platform() if platform == PiRevEn.PIZEROW: self.pid = PID(-4, 0, -1, setpoint=self.TARGET_DISTANCE) ultrasonic = UltrasonicSensor.get_instance() elif platform == PiRevEn.PI3B_PLUS: import rpyc # self.pid = PID(-0.5, -0.1, -0.25, setpoint=self.TARGET_DISTANCE) self.pid = PID(-0.1, 0, -0.015, setpoint=self.TARGET_DISTANCE) ultrasonic_service = rpyc.connect_by_service("UltrasonicSensor") ultrasonic = ultrasonic_service.root else: raise Exception('Cannot initialize ACC due to invalid platform!') self.pid.sample_time = 1.0 / ultrasonic.DISTANCE_SAMPLING_FREQ self.pid.output_limits = (-100, 100) time.sleep(1) # wait for the sensor measurement to settle t = threading.current_thread() while getattr(t, self.THREAD_RUN_REQUESTED, True): dist = ultrasonic.get_filtered_data() next_speed = round(self.pid(dist)) if next_speed < 0: speed_driver.set_speed(0, math.floor(abs(next_speed))) print('PID: dist: %.2f - pwm: %.2f' % (dist, next_speed)) else: print('PID: dist :%.2f - no pwm' % dist) time.sleep(self.pid.sample_time) speed_driver.set_speed(0, 0) return
def probe_peer(self, host): """Probes a discovered node for info""" hostname = None ifaces = None addrs = None cluster_iface = None try: c = rpyc.connect_by_service('storage', host=host) hostname = str(c.root.peer_hostname()) uuid = str(c.root.peer_uuid()) cluster_iface = dict(c.root.peer_get_cluster_iface()) ifaces = dict(c.root.peer_list_addrs()) addrs = dict([(y['addr'], y['netmask']) for x in ifaces.values() for y in x]) if None in [hostname, uuid, ifaces, addrs, cluster_iface]: raise DiscoveryError("Failed to probe discovered peer host=%s: Probe has invalid data.", host) logger.debug("Discovered peer host=%s; hostname=%s.", host, hostname) except Exception, e: logger.error("Failed to probe discovered peer host=%s: %s", host, e) return
def __handle_watchdog_expiry(): platform = PiRevEn.detect_platform() if platform == PiRevEn.PI3B_PLUS: import rpyc __speed_service = rpyc.connect_by_service("SpeedDriver") __steer_service = rpyc.connect_by_service("SteeringDriver") speed_driver = __speed_service.root steer_driver = __steer_service.root speed_driver.set_speed(0, 0) steer_driver.set_steering(0, 0) speed_driver.enable_disable_driver(False) steer_driver.enable_disable_driver(False) else: from components.core.PiCarController import PiCarController controller = PiCarController.get_instance() controller.request_speed(0, 0) controller.request_steering(0, 0) controller.activate_control(False, PlatformEn.SHELBYGT500)
def get_server_connection(sevice_name, config=None): # refer to: rpyc/core/protocol.py for various config options config_default = { 'allow_public_attrs': True, # 'allow_pickle': True, # 'allow_getattr': True } config = config_default if config is None else config # refer to: rpyc/core/protocol.py for various config options cserv = rpyc.connect_by_service(sevice_name, config=config) return cserv
def connect_with_name(data): conn = None try: conn = rpyc.connect_by_service( 'central_control', config={'sync_request_timeout': DEFAULT_REQUEST_TIMEOUT}) print( f'connected {conn.root.get_service_name().lower()} then wait for processing...' ) result = conn.root.process(data) except: result = (CODE_FAILED, f'errors in app_client: {sys.exc_info()}') finally: if conn is not None: conn.close() print(f'result: {result}')
def set_states(states): """ Connects to the server and sets the states of all twelve valves to the specified value :param states: twelve element-long array of ints, representing the states of each valve :type states: array of integers :return: A return code (0 for success, 1 for failure), and a feedback message (to be relayed to the user). """ SUCCESS, FAIL = 0, 1 # Return codes, used by the web app try: # Connect to RPyC server and get main object connection = rpyc.connect_by_service("TAMAGOTCHIP") r = connection.root except DiscoveryError, e: return FAIL, "Serial interface daemon unreachable."
def service_enable_lka_request(): enable = True if request.json['enabled'].lower() == "true" else False platform = PiRevEn.detect_platform() global lka if platform == PiRevEn.PI3B_PLUS: import rpyc global lka_service if enable: lka_service = rpyc.connect_by_service("LaneKeepAssistant") lka = lka_service.root lka.enable_disable_driver(True) else: lka.enable_disable_driver(False) lka.close() lka = None lka_service = None else: raise Exception( 'Cannot initialize lane keep assistant due to invalid platform!') return Response(request.data)
def get_service(self, name, default='exception', cache=True, client_service=None): """Looks for service on Peer. Returns an existing one if possible, otherwise instantiates one.""" NAME = str(name).upper() check_service = None if cache: check_service = self._services.get(NAME) if not client_service: client_service = rpyc.VoidService if not check_service or check_service.closed: service = None try: service = rpyc.connect_by_service(NAME, host=self.cluster_addr, service=client_service, #config=conf.rpyc_conn_config, ) # Remove existing aliases to old service if cache: if check_service: for alias in self._services.keys(): if self._services[alias] == check_service: self._services.pop(alias) # Add in the new service's for alias in service.root.get_service_aliases(): self._services[alias] = service except Exception, e: if check_service: check_service.close() if service: service.close() if default == 'exception': raise ConnectionError('Cannot get service "%s": "%s"', name, e.message) else: return default
__author__ = 'kirtap' import rpyc server = "PrimesServer" #c = rpyc.connect(server, port = 12345) c = rpyc.connect_by_service("PrimesServer") c.root c.root.isPrime(5)
#!/usr/bin/env python import dmd import time try: import rpyc tmp = rpyc.connect_by_service('LISTENER') actor = tmp.root except: print "Using local service" actor = dmd.ListenerService(None) def long_time(t): result = '' for number, singular, plural in ((t//60, 'hour ', 'hours'), (t%60, 'minute ', 'minutes')): if number: result += "%2i %s "%(number, singular if number == 1 else plural) return result or 'none' def chrono_display((timeperiod, _, __), actor): for t, m in actor.exposed_history(range(timeperiod-1, -1, -1)): print "%40s %s %s"%(time.ctime(t), '*' if m.endswith('**') else ' ', m.rstrip('* ')) def grouped_display((timeperiod, _, __), source): data = list(source.exposed_grouped(range(timeperiod))) for task, tm in sorted(data, key=lambda t:t[1], reverse=True): print "% 40s %s %s"%(task.rstrip('* '), '*' if task.endswith('**') else ' ', long_time(tm))
import rpyc c = rpyc.connect_by_service("TIME") print( "server's time is", c.root.get_time())
def RunRobotSim(scale=0.5, dt=0.1, invert=False): counter = 0 decTime = time.time() pygame.init() print "Screen: ", pygame.display.get_driver() mPerPixel = 0.01 / scale sizeX = int(1600 * scale) sizeY = int(800 * scale) screen = pygame.display.set_mode((sizeX, sizeY)) disp = pygame.Surface((sizeX / 2, sizeY)) disp2 = pygame.Surface((sizeX / 2, sizeY)) from optparse import OptionParser parser = OptionParser() parser.add_option("-a", default="", dest="ip", help="addres of robot", metavar="IP") parser.add_option("-c", default="auto", dest="acontrol", help="Automatic Control", metavar="CONTROL") options, args = parser.parse_args() ip = options.ip acontrol = options.acontrol #acontrol="auto" engine = None if ip: import rpyc engine = rpyc.connect_by_service("engine", ip) print "Connectted to service!" run = True robotV = RobotVis.RobotVis(RobotSim.RobotSim(mPerPixel), mPerPixel) #robotShaddow = RobotVis.RobotVis(RobotSim.RobotReal('192.168.0.203', 13500)) activeU = [robotV.robot.maxU, robotV.robot.maxU] enviroment = Enviroment.Enviroment(sizeX / 2) enviroment2 = Enviroment.Enviroment(sizeX / 2) enviroment.LoadFromFile('map.txt') robotV.enviroment = enviroment enviroment2.SetClear(80, 60) graph = grapher.Grapher(sizeX, sizeY / 4) robotV.robot.dT = dt joy = None pygame.joystick.init() try: joy = pygame.joystick.Joystick(0) joy.init() except: pass timeControl = time.time() #TODO:Fix while run: time.sleep(0.02) for e in pygame.event.get(): if e.type == pygame.QUIT: run = False #main cycle U = robotV.robot.Au(activeU) X = robotV.robot.Vr(U) S = robotV.robot.Vs(enviroment, enviroment2) activeU = [0, 0] if engine: activeU = [0, 0] #commands = engine.root.Get(5) else: try: #print [joy.get_axis(0) * 64, -joy.get_axis(1) * 64] #print joy.get_axis(0), joy.get_axis(1) x = joy.get_axis(0) * 60 y = -joy.get_axis(1) * 60 activeU = [y + x / 2, y - x / 2] if activeU == [0.0, 0.0]: raise Exception() timeControl = time.time() #ret[0] = round(joy.get_axis(0)) #ret[1] = round(joy.get_axis(1)) except: pass if timeControl + 2 < time.time(): if acontrol == "auto": activeU = robotV.robot.As(S) #print activeU #paint sensor response graph.AddData(S) #paint robot enviroment.paint(disp) enviroment2.paint(disp2) if decTime + 2 < time.time(): decTime = time.time() print decTime for i, x in enumerate(enviroment2.map): for j, y in enumerate(x): enviroment2.map[i][j] -= 8 if enviroment2.map[i][j] < 0: enviroment2.map[i][j] = 0 robotV.enviroment.paint(disp) robotV.paint(disp) if invert: screen.fill((255, 255, 255)) screen.blit(disp, (0, 0), None, pygame.BLEND_SUB) screen.blit(disp2, (sizeX / 2, 0), None, pygame.BLEND_SUB) else: screen.blit(disp, (0, 0)) screen.blit(disp2, (sizeX / 2, 0)) for y in range(0, int(sizeY * mPerPixel)): for x in range(0, int(sizeX * mPerPixel)): pygame.draw.circle( screen, (255, 255, 0), map(int, (x / mPerPixel, y / mPerPixel)), 2) graph.Paint(screen, sizeY - graph.gr.get_height(), invert) pygame.display.flip()
def exposed_start(self): __steer_service = rpyc.connect_by_service("STEERINGDRIVER") steer = __steer_service.root self.lka.enable_disable_driver(True, steer) self.started = True
def exposed_start(self): __speed_service = rpyc.connect_by_service("SpeedDriver") speed = __speed_service.root self.colav.enable_disable_driver(True, speed) self.started = True