def menu(): phone_book = {} while True: print(yellow("\n1-Mostrar lista de contactos")) print(yellow("2-Añadir contacto (nombre y teléfono)")) print(yellow("3-Borrar contacto (nombre)")) print(yellow("4-Salir\n")) menu = input("¿Menú a elegir?: ") if menu == "1": show_contacts(phone_book) elif menu == "2": name = input(green("¿Contacto que desea añadir?: ")) if name not in phone_book: phone = input(green("¿Número de contacto?: ")) add_contact(phone_book, name, phone) else: print(red("ERROR: este contacto ya existe")) elif menu == "3": name = input(green("¿Contacto que desea eliminar?: ")) remove_contact(phone_book, name) elif menu == "4": break else: print(red("ERROR: menú incorrecto!!"))
def diff_all_table_data(self): failures = 0 print(bold(red('Starting table analysis.'))) with warnings.catch_warnings(): warnings.simplefilter("ignore", category=sa_exc.SAWarning) tables = sorted( self.firstinspector.get_table_names(schema="public")) for table in tables: if table in self.exclude_tables: print(bold(yellow(f"Ignoring table {table}"))) continue with Halo(text=f"Analysing table {table}. " f"[{tables.index(table) + 1}/{len(tables)}]", spinner='dots') as spinner: result, message = self.diff_table_data(table) if result is True: spinner.succeed(f"{table} - {message}") elif result is None: spinner.warn(f"{table} - {message}") else: failures += 1 spinner.fail(f"{table} - {message}") print(bold(green('Table analysis complete.'))) if failures > 0: return 1 return 0
def _printNode(self, key, val, padding='', last=False, maxdepth=None, maxcount=None): from fabulous.color import highlight_blue, red, blue, green, cyan, yellow, bold from tables import Array if isinstance(val, H5Node): val.printTree(padding=padding, last=last, maxdepth=maxdepth, maxcount=maxcount) else: if isinstance(val, Array): val = yellow('Array(%s,__dtype__=%s)' % (','.join(str(i) for i in val.shape), val.dtype)) elif isinstance(val, Table): val = green(val) else: val = red('%s,__dtype__=%s' % (str(val), type(val).__name__)) if last: print '%s `%s [%s]' % (padding[:-1], cyan(key), val) else: print '%s`%s [%s]' % (padding, cyan(key), val)
def count(self): ''' This scenario lets the drone count all the objects on a predefined trajectory ''' print highlight_magenta( ' COUNTING STARTED ') print magenta('fly to start point!') counting_list = [[50], [51], [52], [53], [54], [55], [56], [57], [58], [59], [60], [61], [62], [63], [64], [65], [66], [67], [68], [69], [70], [71], [72], [73], [74], [75], [76], [77], [78], [79]] red_c = 0 blue_c = 0 green_c = 0 counted_list = [] while [11] not in self.ids: rospy.sleep(0.5) print magenta('starting to count') while [12] not in self.ids: for i in self.ids: if i in counting_list: counting_list.remove(i) counted_list.append(i) print magenta(' >>> found one <<< ') rospy.sleep(0.5) for i in counted_list: if 50 <= i[0] <= 59: red_c += 1 elif 60 <= i[0] <= 69: blue_c += 1 elif 70 <= i[0] <= 79: green_c += 1 print highlight_magenta( ' REPORT ') print red(' red:' + str(red_c)) print blue(' blue:' + str(blue_c)) print green(' green:' + str(green_c)) print highlight_magenta( ' COUNTING COMPLETED ') self.task_str = ""
def diff_all_sequences(self): print(bold(red('Starting sequence analysis.'))) sequences = sorted(self.get_all_sequences()) for sequence in sequences: with Halo(text=f"Analysing sequence {sequence}. " f"[{sequences.index(sequence) + 1}/{len(sequences)}]", spinner='dots') as spinner: result, message = self.diff_sequence(sequence) if result is True: spinner.succeed(f"{sequence} - {message}") elif result is None: spinner.warn(f"{sequence} - {message}") else: spinner.fail(f"{sequence} - {message}") print(bold(green('Sequence analysis complete.')))
def diff_all_sequences(self): print(bold(red('Starting sequence analysis.'))) sequences = sorted(self.get_all_sequences()) failures = 0 for sequence in sequences: status_update = StatusUpdate( f"Analysing sequence {sequence}. " f"[{sequences.index(sequence) + 1}/{len(sequences)}]") result, message = self.diff_sequence(sequence) status_update.complete(result, f"{sequence} - {message}") if result is False: failures += 1 print(bold(green('Sequence analysis complete.'))) if failures > 0: return 1 return 0
def _printNode(self, key, val, padding= '', last=False,maxdepth=None,maxcount=None): from fabulous.color import highlight_blue,red,blue,green,cyan,yellow,bold from tables import Array if isinstance(val,H5Node): val.printTree(padding=padding,last=last,maxdepth=maxdepth,maxcount=maxcount) else: if isinstance(val,Array): val = yellow('Array(%s,__dtype__=%s)'% (','.join(str(i) for i in val.shape),val.dtype)) elif isinstance(val,Table): val = green(val) else: val = red('%s,__dtype__=%s' % (str(val),type(val).__name__)) if last: print '%s `%s [%s]' % (padding[:-1], cyan(key), val ) else: print '%s`%s [%s]' % (padding, cyan(key), val )
def menu(): exit = False while not exit: print(""" 1. Chequear si un número es par ó impar. 2. Salir. """) option = input("") if option == "1": v = read_int() if is_even(v): print(green("El número es par!")) else: print(red("El número es impar!")) elif option == "2": print("👋🏻 Hasta luego Lucas!") exit = True else: print(red_bg("La opción elegida no existe!"))
def diff_all_table_data(self): failures = 0 self.create_aggregate_functions() print(bold(red('Starting table analysis.'))) with warnings.catch_warnings(): warnings.simplefilter("ignore", category=sa_exc.SAWarning) tables = sorted( self.firstinspector.get_table_names(schema="public")) for table in tables: status_update = StatusUpdate( f"Analysing table {table}. " f"[{tables.index(table) + 1}/{len(tables)}]") result, message = self.diff_table_data(table) status_update.complete(result, f"{table} - {message}") if result is False: failures += 1 print(bold(green('Table analysis complete.'))) if failures > 0: return 1 return 0
def diff_all_sequences(self, thread_number): # run just once if thread_number > 0: return 0 print(bold(red('Starting sequence analysis.'))) sequences = sorted(self.get_all_sequences()) failures = 0 for sequence in sequences: with Halo(text=f"Analysing sequence {sequence}. " f"[{sequences.index(sequence) + 1}/{len(sequences)}]", spinner='dots') as spinner: result, message = self.diff_sequence(sequence) if result is True: spinner.succeed(f"{sequence} - {message}") elif result is None: spinner.warn(f"{sequence} - {message}") else: failures += 1 spinner.fail(f"{sequence} - {message}") print(bold(green('Sequence analysis complete.'))) if failures > 0: return 1 return 0
steps = 0 t_r = 0 if (args.RandomTest): env.Set_Randomization(default=False) else: env.incline_deg = args.WedgeIncline env.incline_ori = math.radians(args.WedgeOrientation) env.SetFootFriction(args.FrictionCoeff) env.SetLinkMass(0, args.FrontMass) env.SetLinkMass(11, args.BackMass) env.clips = args.MotorStrength env.pertub_steps = 300 env.y_f = args.PerturbForce state = env.reset() print(bold(blue("\nTest Parameters:\n")), green('\nWedge Inclination:'), red(env.incline_deg), green('\nWedge Orientation:'), red(math.degrees(env.incline_ori)), green('\nCoeff. of friction:'), red(env.friction), green('\nMass of the front half of the body:'), red(env.FrontMass), green('\nMass of the rear half of the body:'), red(env.BackMass), green('\nMotor saturation torque:'), red(env.clips)) log = env._pybullet_client.startStateLogging( fileName="stochsidehill.mp4", loggingType=env._pybullet_client.STATE_LOGGING_VIDEO_MP4) env._pybullet_client.resetDebugVisualizerCamera(1, 90, -20, [1, 0, 0]) for i_step in range(args.EpisodeLength): action = policy.dot(state) # action = [1.0,1.0,1.0,1.0, # 1.0,1.0,1.0,1.0,
def execute_file(filename, contents): print(color.green(filename)) tree = parser.parse(contents) print(tree.pretty()) print(Rockstar().transform(tree))
def home_inspection_smart(self): ''' this scenario lets the drone inspect several objects if failing or functional However, each item influences the objects that will have to be inspected later on. ''' inspection_list = {1} dependency_dict = { "M1": {2, 3}, "M2": {5}, "M3": {}, "M4": {}, "M5": {}, "M6": {}, "M7": {}, "M8": {}, "M9": {}, } print highlight_magenta( ' INSPECTION STARTED ') print magenta('inspecting machines' + str(tuple(inspection_list))) report = [0, 0, 0, 0, 0, 0] print magenta(' fly to machine ' + str(random.choice(tuple(inspection_list)))) while len(inspection_list) > 0: self.events() if [21] in self.ids and [22] in self.ids and 1 in inspection_list: if len(self.ids) == 3: if [1] in self.ids: print magenta(" >>> Machine 1 ok <<< ") inspection_list.discard(1) report[1] = 1 elif [2] in self.ids: print magenta(" >>> Machine 1 not ok <<< ") inspection_list.discard(1) inspection_list = inspection_list.union( dependency_dict["M1"]) report[1] = 2 else: print magenta( " >>> Machine 1 inconclusive <<< ") inspection_list.discard(1) inspection_list = inspection_list.union( dependency_dict["M1"]) report[1] = 3 if len(inspection_list) > 0: print magenta(' machines to inspect' + str(tuple(inspection_list))) print magenta( ' fly to machine ' + str(random.choice(tuple(inspection_list)))) else: print magenta(' fly home') else: print magenta("other marker or not enclosed") if [23] in self.ids and [24] in self.ids and 2 in inspection_list: if len(self.ids) == 3: if [1] in self.ids: print magenta(" >>> Machine 2 ok <<< ") inspection_list.discard(2) report[2] = 1 elif [2] in self.ids: print magenta(" >>> Machine 2 not ok <<< ") inspection_list.discard(2) inspection_list = inspection_list.union( dependency_dict["M2"]) report[2] = 2 else: print magenta( " >>> Machine 2 inconclusive <<< ") inspection_list.discard(2) inspection_list = inspection_list.union( dependency_dict["M2"]) report[2] = 3 if len(inspection_list) > 0: print magenta(' machines to inspect' + str(tuple(inspection_list))) print magenta( ' fly to machine ' + str(random.choice(tuple(inspection_list)))) else: print magenta(' fly home') if [25] in self.ids and [26] in self.ids and 3 in inspection_list: if len(self.ids) == 3: if [1] in self.ids: print magenta(" >>> Machine 3 ok <<< ") inspection_list.discard(3) report[3] = 1 elif [2] in self.ids: print magenta(" >>> Machine 3 not ok <<< ") inspection_list.discard(3) inspection_list = inspection_list.union( dependency_dict["M3"]) report[3] = 2 else: print magenta( " >>> Machine 3 inconclusive <<< ") inspection_list.discard(3) inspection_list = inspection_list.union( dependency_dict["M3"]) report[3] = 3 if len(inspection_list) > 0: print magenta(' machines to inspect' + str(tuple(inspection_list))) print magenta( ' fly to machine ' + str(random.choice(tuple(inspection_list)))) else: print magenta(' fly home') if [27] in self.ids and [28] in self.ids and 4 in inspection_list: if len(self.ids) == 3: if [1] in self.ids: print magenta(" >>> Machine 4 ok <<< ") inspection_list.discard(4) report[4] = 1 elif [2] in self.ids: print magenta(" >>> Machine 4 not ok <<< ") inspection_list.discard(4) inspection_list = inspection_list.union( dependency_dict["M4"]) report[4] = 2 else: print magenta( " >>> Machine 4 inconclusive <<< ") inspection_list.discard(4) inspection_list = inspection_list.union( dependency_dict["M4"]) report[4] = 3 if len(inspection_list) > 0: print magenta(' machines to inspect' + str(tuple(inspection_list))) print magenta( ' fly to machine ' + str(random.choice(tuple(inspection_list)))) else: print magenta(' fly home') if [29] in self.ids and [30] in self.ids and 5 in inspection_list: if len(self.ids) == 3: if [1] in self.ids: print magenta(" >>> Machine 5 ok <<< ") inspection_list.discard(5) report[5] = 1 elif [2] in self.ids: print magenta(" >>> Machine 5 not ok <<< ") inspection_list.discard(5) inspection_list = inspection_list.union( dependency_dict["M5"]) report[5] = 2 else: print magenta( " >>> Machine 5 inconclusive <<< ") inspection_list.discard(5) inspection_list = inspection_list.union( dependency_dict["M5"]) report[5] = 3 if len(inspection_list) > 0: print magenta(' machines to inspect' + str(tuple(inspection_list))) print magenta( ' fly to machine ' + str(random.choice(tuple(inspection_list)))) else: print magenta(' fly home') rospy.sleep(0.5) print highlight_magenta( ' REPORT ') for i in range(len(report)): if report[i] == 1: print green(' MACHINE ' + str(i) + ' OK') elif report[i] == 2: print red(' MACHINE ' + str(i) + ' NOT OK') elif report[i] == 3: print red(' MACHINE ' + str(i) + ' INCONCLUSIVE') print highlight_magenta( ' INSPECTION COMPLETED ') self.task_str = ""
if (args.RandomTest): env.Set_Randomization(default=False) else: env.incline_deg = args.WedgeIncline env.incline_ori = math.radians(args.WedgeOrientation) env.SetFootFriction(args.FrictionCoeff) # env.SetLinkMass(0,args.FrontMass) # env.SetLinkMass(11,args.BackMass) env.clips = args.MotorStrength env.pertub_steps = 300 env.y_f = args.PerturbForce state = env.reset() print( bold(blue("\nTest Parameters:\n")), green('\nWedge Inclination:'), red(env.incline_deg), green('\nWedge Orientation:'), red(math.degrees(env.incline_ori)), green('\nCoeff. of friction:'), red(env.friction), # green('\nMass of the front half of the body:'),red(env.FrontMass), # green('\nMass of the rear half of the body:'),red(env.BackMass), green('\nMotor saturation torque:'), red(env.clips)) # Simulation starts simstep = 1000 plot_data = [] t_r = 0 for i_step in range(simstep):
import subprocess from fabulous.color import bold, blue, green import time import requests import random import mhutils hub_address = mhutils.get_address("keys/hub.pub") co = 100 while True: co += int((random.random() - 0.5) * 10) print(bold("Current CO level:"), green(str(co))) transaction_result = subprocess.check_output([ "python3", "metahash.py", "send-tx", "--net=test", "--pubkey=keys/co.pub", "--privkey=keys/co.priv", "--value=1", "--to={}".format(hub_address), '--data=' + str(co) ]).decode("utf-8") print(transaction_result) time.sleep(5)
""" from fabulous import color as col messagefmt = { None: '{asctime} {module} {levelname} {msg}'.format( asctime=col.highlight_blue('{r.asctime}'), module=col.cyan(('{r.module}')), levelname=col.cyan('{r.levelname}'), msg=col.bold(col.yellow('{r.msg}')), ), 'INFO': '{asctime} {module} {levelname} {msg}'.format( asctime=col.highlight_blue('{r.asctime}'), module=col.cyan(('{r.module}')), levelname=col.green('{r.levelname}'), msg=col.bold(col.yellow('{r.msg}')), ), 'WARNING': '{asctime} {module} {levelname} {msg}'.format( asctime=col.highlight_blue('{r.asctime}'), module=col.cyan(('{r.module}')), levelname=col.bold(col.magenta('{r.levelname}')), msg=col.bold(col.yellow('{r.msg}')), ), 'ERROR': '{asctime} {module} {levelname} {msg}'.format( asctime=col.highlight_blue('{r.asctime}'), module=col.cyan(('{r.module}')), levelname=col.red('{r.levelname}'), msg=col.red('{r.msg}'),
import subprocess from fabulous.color import bold, blue, green import time import random import mhutils hub_address = mhutils.get_address("keys/hub.pub") temp_address = mhutils.get_address("keys/temp.pub") heater_is_on = False while True: last_temp = mhutils.get_last_data_from_address( mhutils.get_history(hub_address), temp_address) print(bold("Current temperature:"), green(bold(last_temp))) if heater_is_on != (float(last_temp) < 20): heater_is_on = float(last_temp) < 20 print(heater_is_on) transaction_result = subprocess.check_output([ "python3", "metahash.py", "send-tx", "--net=test", "--pubkey=keys/heater.pub", "--privkey=keys/heater.priv", "--value=1", "--to={}".format(hub_address), '--data=' + str(heater_is_on) ]).decode("utf-8") print(transaction_result) time.sleep(5)
def green(self): return ansi(c.green(self.txt))
def _colorize(success): if success: return green(" OK ") else: return red(" FAIL ")
downhill=False, stairs=False, seed_value=args.seed, on_rack=False, gait='trot') steps = 0 t_r = 0 if (args.RandomTest): env.Set_Randomization(default=False) else: env.incline_deg = args.WedgeIncline env.incline_ori = math.radians(args.WedgeOrientation) state = env.reset() print(bold(blue("\nTest Parameters:\n")), green('\nWedge Inclination:'), red(env.incline_deg), green('\nWedge Orientation:'), red(math.degrees(args.WedgeOrientation)), green('\nCoeff. of friction:'), red(env.friction), green('\nMotor saturation torque:'), red(env.clips)) for i_step in range(args.EpisodeLength): print('Roll:', math.degrees(env.support_plane_estimated_roll), 'Pitch:', math.degrees(env.support_plane_estimated_pitch)) action = policy.dot(state) # action = [1.0,1.0,1.0,1.0, # 0.0,0.0,0.0,0.0, # -1.0,-1.0,-1.0,-1.0, # -1.0,-1.0,-1.0,-1.0, # 0.0,0.0,0.0,0.0 ] # action = [0.5,0.5,0.5,0.5,
def home_inspection(self): ''' this scenario lets the drone inspect several objects if failing or functional ''' inspection_list = [1, 3, 5] print highlight_magenta( ' INSPECTION STARTED ') print magenta('inspecting machines' + str(inspection_list)) report = [0, 0, 0, 0, 0, 0] inspection_list.append('home') print magenta(' fly to machine ' + str(inspection_list[0])) while len(inspection_list) > 1: self.events() if [21] in self.ids and [22] in self.ids and 1 in inspection_list: if len(self.ids) == 3: if [1] in self.ids: print magenta(" >>> Machine 1 ok <<< ") inspection_list.remove(1) report[1] = 1 elif [2] in self.ids: print magenta(" >>> Machine 1 not ok <<< ") inspection_list.remove(1) report[1] = 2 else: print magenta( " >>> Machine 1 inconclusive <<< ") inspection_list.remove(1) report[1] = 3 print magenta(' fly to machine ' + str(inspection_list[0])) else: print magenta("other marker or not enclosed") if [23] in self.ids and [24] in self.ids and 2 in inspection_list: if len(self.ids) == 3: if [1] in self.ids: print magenta(" >>> Machine 2 ok <<< ") inspection_list.remove(2) report[2] = 1 elif [2] in self.ids: print magenta(" >>> Machine 2 not ok <<< ") inspection_list.remove(2) report[2] = 2 else: print magenta( " >>> Machine 2 inconclusive <<< ") inspection_list.remove(2) report[2] = 3 print magenta(' fly to machine ' + str(inspection_list[0])) else: print magenta("other marker or not enclosed") if [25] in self.ids and [26] in self.ids and 3 in inspection_list: if len(self.ids) == 3: if [1] in self.ids: print magenta(" >>> Machine 3 ok <<< ") inspection_list.remove(3) report[3] = 1 elif [2] in self.ids: print magenta(" >>> Machine 3 not ok <<< ") inspection_list.remove(3) report[3] = 2 else: print magenta( " >>> Machine 3 inconclusive <<< ") inspection_list.remove(3) report[3] = 3 print magenta(' fly to machine ' + str(inspection_list[0])) else: print magenta("other marker or not enclosed") if [27] in self.ids and [28] in self.ids and 4 in inspection_list: if len(self.ids) == 3: if [1] in self.ids: print magenta(" >>> Machine 4 ok <<< ") inspection_list.remove(4) report[4] = 1 elif [2] in self.ids: print magenta(" >>> Machine 4 not ok <<< ") inspection_list.remove(4) report[4] = 2 else: print magenta( " >>> Machine 4 inconclusive <<< ") inspection_list.remove(4) report[4] = 3 print magenta(' fly to machine ' + str(inspection_list[0])) else: print magenta("other marker or not enclosed") if [29] in self.ids and [30] in self.ids and 5 in inspection_list: if len(self.ids) == 3: if [1] in self.ids: print magenta(" >>> Machine 5 ok <<< ") inspection_list.remove(5) report[5] = 1 elif [2] in self.ids: print magenta(" >>> Machine 5 not ok <<< ") inspection_list.remove(5) report[5] = 2 else: print magenta( " >>> Machine 5 inconclusive <<< ") inspection_list.remove(5) report[5] = 3 print magenta(' fly to machine ' + str(inspection_list[0])) else: print magenta("other marker or not enclosed") rospy.sleep(0.5) print highlight_magenta( ' REPORT ') for i in range(len(report)): if report[i] == 1: print green(' MACHINE ' + str(i) + ' OK') elif report[i] == 2: print red(' MACHINE ' + str(i) + ' NOT OK') elif report[i] == 3: print red(' MACHINE ' + str(i) + ' INCONCLUSIVE') print highlight_magenta( ' INSPECTION COMPLETED ') self.task_str = ""
def log(obj): now = datetime.now().strftime("%m/%d/%Y %H:%M:%S") message = f">{now} -- {obj}" print(bold(green(message)))
import sys import os import config from fabulous.color import green, red, fg256 if sys.argv[1] == "open": os.system("picocom /dev/{} -b 115200".format(config.TTY_HANDLER)) elif sys.argv[1] == "deploy": print( fg256( "#e67e22", """ If it hangs on 'Connected to esp8266': - Be sure you are not connected in other session to TTY. If so, disconnect and try it again! - Otherwise, press CTRL-C, reset the NodeMCU by pressing the button on the board and try it again! """)) with open('uconfig.py', 'w') as f: f.write(f'DWEET_THING = "{config.DWEET_THING}"{os.linesep}') f.write(f'WIFI_SSID = "{config.WIFI_SSID}"{os.linesep}') f.write(f'WIFI_PASSWORD = "******"{os.linesep}') files = ";".join(f"put {file}" for file in config.FILES_TO_DEPLOY) error = os.system("mpfshell -n -c 'open {}; {}'".format( config.TTY_HANDLER, files)) if error: print(red("Deploy failed!")) else: print(green("All files were deployed successfully!!")) else: print("⚠️ Unknown option!")
env.Set_Randomization(default=False) else: env.incline_deg = args.WedgeIncline env.incline_ori = math.radians(args.WedgeOrientation) env.SetFootFriction(args.FrictionCoeff) env.SetLinkMass(0,args.FrontMass) env.SetLinkMass(11,args.BackMass) env.clips = args.MotorStrength env.pertub_steps = 300 env.y_f = args.PerturbForce state = env.reset() print ( bold(blue("\nTest Parameters:\n")), green('\nWedge Inclination:'),red(env.incline_deg), green('\nWedge Orientation:'),red(math.degrees(env.incline_ori)), green('\nCoeff. of friction:'),red(env.friction), green('\nMass of the front half of the body:'),red(env.FrontMass), green('\nMass of the rear half of the body:'),red(env.BackMass), green('\nMotor saturation torque:'),red(env.clips)) # Simulation starts t_r = 0 for i_step in range(args.EpisodeLength): action = policy.dot(state) state, r, _, angle = env.step(action) t_r +=r
def configure(self, data): """Configures the motionplanner. Creates omgtools Point2point problem with room, static and dynamic obstacles. Args: data : static_obstacles dyn_obstacles difficult_obst """ mp_configured = False self._obstacles = [] self.n_stat_obst = len(data.static_obstacles) self.n_dyn_obst = len(data.dyn_obstacles) if data.difficult_obst: self.omg_update_time = rospy.get_param( 'controller/omg_update_time_slow', 0.5) safety_margin = rospy.get_param( 'motionplanner/safety_margin_small', 0.1) safety_weight = rospy.get_param('motionplanner/safety_weight_slow', 10.) drone_radius = rospy.get_param('motionplanner/drone_radius_small', 0.20) vmax = rospy.get_param('motionplanner/omg_vmax_low', 0.2) amax = rospy.get_param('motionplanner/omg_amax_low', 0.3) else: self.omg_update_time = rospy.get_param( 'controller/omg_update_time', 0.5) safety_margin = rospy.get_param('motionplanner/safety_margin', 0.2) safety_weight = rospy.get_param('motionplanner/safety_weight', 10.) drone_radius = rospy.get_param('motionplanner/drone_radius', 0.225) vmax = rospy.get_param('motionplanner/omg_vmax', 0.2) amax = rospy.get_param('motionplanner/omg_amax', 0.3) print("amax = " + str(amax) + "vmax =" + str(vmax)) if self.n_dyn_obst: safety_margin = rospy.get_param( 'motionplanner/safety_margin_dyn_obst', 0.2) safety_weight = rospy.get_param( 'motionplanner/safety_weight_dyn_obst', 10.) self._vehicle = omg.Holonomic3D(shapes=omg.Sphere(drone_radius), bounds={ 'vmax': vmax, 'vmin': -vmax, 'amax': amax, 'amin': -amax }) self._vehicle.define_knots(knot_intervals=self.knots) self._vehicle.set_options({ 'safety_distance': safety_margin, 'safety_weight': safety_weight, 'syslimit': 'norm_2' }) self._vehicle.set_initial_conditions([0., 0., 0.]) self._vehicle.set_terminal_conditions([0., 0., 0.]) # Environment. room_width = rospy.get_param('motionplanner/room_width', 1.) room_depth = rospy.get_param('motionplanner/room_depth', 1.) room_height = rospy.get_param('motionplanner/room_height', 1.) room_origin_x = 0. room_origin_y = 0. room_origin_z = room_height / 2 room = { 'shape': omg.Cuboid(room_width, room_depth, room_height), 'position': [room_origin_x, room_origin_y, room_origin_z] } # Static obstacles. for k, obst in enumerate(data.static_obstacles): if obst.obst_type.data == "inf cylinder": # 2D shape is extended infinitely along z. shape = omg.Circle(obst.shape[0]) position = [obst.pose[0], obst.pose[1]] elif obst.obst_type.data == "slalom plate": shape = omg.Beam(obst.shape[1] - 0.1, 0.1, np.pi / 2) position = [obst.pose[0], obst.pose[1]] elif obst.obst_type.data == "hexagon": shape = omg.RegularPrisma(obst.shape[0], obst.shape[1], 6) position = [obst.pose[0], obst.pose[1], obst.pose[2]] elif obst.obst_type.data == "window plate": if (k % 4) <= 1: # Side plates 1 and 2. shape = omg.Beam(obst.shape[1] - 0.1, 0.1, np.pi / 2) position = [obst.pose[0], obst.pose[1]] else: # Upper and lower plates 3 and 4. shape = omg.Plate(shape2d=omg.Rectangle( obst.shape[0], obst.shape[1]), height=obst.shape[2], orientation=[0., np.pi / 2, 0.]) position = [obst.pose[0], 0., obst.pose[2]] elif obst.obst_type.data == "plate": shape = omg.Plate(shape2d=omg.Rectangle( obst.shape[0], obst.shape[1]), height=obst.shape[2], orientation=[0., np.pi / 2, obst.direction]) position = [obst.pose[0], obst.pose[1], obst.pose[2]] else: print highlight_yellow(' Warning: invalid obstacle type ') self._obstacles.append( omg.Obstacle({'position': position}, shape=shape)) # Dynamic obstacles. for obst in data.dyn_obstacles: shape = omg.Circle(obst.shape[0]) position = [obst.pose[0], obst.pose[1]] self._obstacles.append( omg.Obstacle({'position': position}, shape=shape)) # Create the environment as room with obstacles. environment = omg.Environment(room=room) environment.add_obstacle(self._obstacles) # Create problem. problem = omg.Point2point(self._vehicle, environment, freeT=False) problem.set_options({ 'solver_options': { 'ipopt': { 'ipopt.linear_solver': 'ma57', 'ipopt.max_iter': 1000, 'ipopt.print_level': 0, 'ipopt.tol': 1e-4, 'ipopt.warm_start_init_point': 'yes', 'ipopt.warm_start_bound_push': 1e-8, 'ipopt.warm_start_mult_bound_push': 1e-8, 'ipopt.mu_init': 1e-5, 'ipopt.hessian_approximation': 'limited-memory' } } }) if self.n_dyn_obst: problem.set_options({ 'hard_term_con': False, 'horizon_time': self.horizon_time, 'verbose': 1. }) else: problem.set_options({ 'hard_term_con': True, 'horizon_time': self.horizon_time, 'verbose': 1. }) problem.init() # problem.fullstop = True self._deployer = omg.Deployer(problem, self._sample_time, self.omg_update_time) self._deployer.reset() mp_configured = True print green('---- Motionplanner running ----') return ConfigMotionplannerResponse(mp_configured)
args.Downhill = True env = e.HyQEnv(render=True, wedge=WedgePresent, downhill=args.Downhill, stairs = False,seed_value=args.seed, on_rack=False, gait = 'trot') if(args.RandomTest): env.randomize_only_inclines(default=False) else: env.incline_deg = args.WedgeIncline env.incline_ori = math.radians(args.WedgeOrientation) state = env.reset() print ( bold(blue("\nTest Parameters:\n")), green('\nWedge Inclination:'),red(env.incline_deg), green('\nWedge Orientation:'),red(math.degrees(args.WedgeOrientation)), green('\nCoeff. of friction:'),red(env.friction), green('\nMotor saturation torque:'),red(env.clips)) # Simulation starts t_r = 0 for i_step in range(args.EpisodeLength): action = policy.dot(state) state, r, _, angle = env.step(action) t_r +=r print("Total_reward "+ str(t_r))
def start(self): ''' Starts running of bebop_demo node. Runs along the state sequence, sends out the current state and returns to the standby state when task is completed. ''' print green('---- Core running ----') while not rospy.is_shutdown(): if self.new_task: self.new_task = False self.change_state = False self.state_finish = False # Run over sequence of states corresponding to current task. for state in self.state_sequence: self.state = state print cyan(' Core state changed to: ', self.state) self.fsm_state.publish(state) # IRRELEVANT WHEN NOT USING OMGTOOLS # # Omg tools should return to its own standby status # # unless the state_button has been pressed. # if self.state in {"omg standby", "omg fly"}: # self.omg_standby = True # else: # self.omg_standby = False if self.state == "land": self.change_state = True task_final_state = (self.state == self.state_sequence[-1]) # Check if previous state is finished and if allowed to # switch state based on controller input. while not ((self.state_finish and (self.change_state or task_final_state)) or self.new_task or rospy.is_shutdown()): # Remaining in state. Allow state action to continue. rospy.sleep(0.1) self.change_state = False self.state_finish = False # OMG STUFF leave_omg = False # leave_omg = ( # self.state == "omg standby" and not self.omg_standby) # # User forces leaving omg with state_button or other new # # task received --> leave the for loop for the current # # task. if (leave_omg or self.new_task): # print cyan('---- Broke for loop ----') break # # Make sure that omg-tools task is repeated until force quit. # if self.omg_standby: # self.new_task = True # Only publish standby state when task is finished. # Except for repetitive tasks (back to first state in task). if not self.new_task: self.state = "standby" self.fsm_state.publish("standby") print cyan(' Core state changed to: ', "standby") # print 'core sleeping' rospy.sleep(0.1)
def publish_pose_est(self): '''Publishes message that calibration is completed. Starts publishing pose measurements. ''' self.ready.publish(Empty()) print green('---- Vive Localization running ----') while not rospy.is_shutdown(): # ========= # TRACKER # ========= pose_t_in_v = self.get_pose_vive(self.tracked_objects[0]) self.tf_t_in_v = self.pose_to_tf(pose_t_in_v, "tracker") self.broadc.sendTransform(self.tf_t_in_v) self.stbroadc.sendTransform(self.tf_d_in_t) # Wait until transform has been updated tf_d_in_w = TransformStamped() tf_d_in_w.header.stamp = self.tf_t_in_w_timestamp_old rate = rospy.Rate(20. / self.sample_time) while tf_d_in_w.header.stamp == self.tf_t_in_w_timestamp_old and ( not rospy.is_shutdown()): tf_d_in_w = self.get_transform("drone", "world") rate.sleep() self.tf_t_in_w_timestamp_old = tf_d_in_w.header.stamp # Calculate pose of drone in world frame as well as yaw angle. pose_d_in_w = self.tf_to_pose(tf_d_in_w) # Calculate and broadcast the rotating world frame. # - Tf drone in world to euler angles. euler = self.get_euler_angles(tf_d_in_w) # - Get yaw. yaw = euler[2] # - Yaw only (roll and pitch 0.0) to quaternions. quat = tf.transformations.quaternion_from_euler(0., 0., yaw) self.tf_r_in_w.transform.rotation.x = quat[0] self.tf_r_in_w.transform.rotation.y = quat[1] self.tf_r_in_w.transform.rotation.z = quat[2] self.tf_r_in_w.transform.rotation.w = quat[3] self.tf_r_in_w.header.stamp = rospy.Time.now() self.broadc.sendTransform(self.tf_r_in_w) # Wait until transform has been updated tf_r_in_w = TransformStamped() tf_r_in_w.header.stamp = self.tf_r_in_w_timestamp_old rate = rospy.Rate(20. / self.sample_time) while tf_r_in_w.header.stamp == self.tf_r_in_w_timestamp_old and ( not rospy.is_shutdown()): tf_r_in_w = self.get_transform("world_rot", "world") rate.sleep() self.tf_r_in_w_timestamp_old = tf_r_in_w.header.stamp # Publish pose of drone in world frame as well as yaw angle. data = PoseMeas(meas_world=pose_d_in_w, yaw=yaw) self.pos_update.publish(data) # ============= # CONTROLLERS # ============= for i in range(1, len(self.tracked_objects)): # controller_1 (& 2) pose_c_in_v = self.get_pose_vive(self.tracked_objects[i]) pose_c_in_w = self.transform_pose(pose_c_in_v, "vive", "world") # For testing pose_c_in_w.pose.position.x = pose_c_in_w.pose.position.x pose_c_in_w.pose.position.y = pose_c_in_w.pose.position.y # Pose pos_c_in_w = PointStamped() pos_c_in_w.header = pose_c_in_w.header pos_c_in_w.point = pose_c_in_w.pose.position self.c_pos_publishers[2 * i - 2].publish(pose_c_in_w) self.c_pos_publishers[2 * i - 1].publish(pos_c_in_w) # Twist new_vel_x = ( (pos_c_in_w.point.x - self.ctrl_dict["ctrl_" + str(i) + "_old_pos"].x) / self.sample_time) new_vel_y = ( (pos_c_in_w.point.y - self.ctrl_dict["ctrl_" + str(i) + "_old_pos"].y) / self.sample_time) new_vel_z = ( (pos_c_in_w.point.z - self.ctrl_dict["ctrl_" + str(i) + "_old_pos"].z) / self.sample_time) self.ctrl_dict["ctrl_" + str(i) + "_vel"].twist.linear.x = ( new_vel_x * self.alpha + self.ctrl_dict["ctrl_" + str(i) + "_vel"].twist.linear.x * (1.0 - self.alpha)) self.ctrl_dict["ctrl_" + str(i) + "_vel"].twist.linear.y = ( new_vel_y * self.alpha + self.ctrl_dict["ctrl_" + str(i) + "_vel"].twist.linear.y * (1.0 - self.alpha)) self.ctrl_dict["ctrl_" + str(i) + "_vel"].twist.linear.z = ( new_vel_z * self.alpha + self.ctrl_dict["ctrl_" + str(i) + "_vel"].twist.linear.z * (1.0 - self.alpha)) self.ctrl_dict["ctrl_" + str(i) + "_old_pos"] = pos_c_in_w.point self.c_vel_publishers[i - 1].publish( self.ctrl_dict["ctrl_" + str(i) + "_vel"]) self.rate.sleep()
# coding=utf-8 from __future__ import print_function import requests import os import sys from fabulous import text try: from BeautifulSoup import BeautifulSoup except ImportError: from bs4 import BeautifulSoup from humanfriendly.tables import format_pretty_table from fabulous.color import highlight_green, green, red, yellow baku_header = [ highlight_green('Qatar №-si'.decode("utf-8").strip()), green('Bakıdan çıxma'.decode("utf-8").strip()), green('Biləcəriyə çatma'.decode("utf-8").strip()), yellow('Biləcəridən getmə'.decode("utf-8").strip()), yellow('Xırdalana çatma'.decode("utf-8").strip()), red('Xırdalandan getmə'.decode("utf-8").strip()), red('Sumqayıta çatma'.decode("utf-8").strip()) ] sum_header = [ highlight_green('Qatar №-si'.decode("utf-8").strip()), green('Sumqayıtdan çıxma'.decode("utf-8").strip()), green('Xırdalana çatma'.decode("utf-8").strip()), yellow('Xırdalana getmə'.decode("utf-8").strip()), yellow('Biləcəriyə çatma'.decode("utf-8").strip()), red('Biləcəriyə getmə'.decode("utf-8").strip()), red('Bakıya çatma'.decode("utf-8").strip())
import subprocess from fabulous.color import bold, blue, green import time import random import mhutils hub_address = mhutils.get_address("keys/hub.pub") temp = 20 while True: temp += (random.random() - 0.5) print(bold("Current temperature:"), green("{:.1f}".format(temp))) transaction_result = subprocess.check_output([ "python3", "metahash.py", "send-tx", "--net=test", "--pubkey=keys/temp.pub", "--privkey=keys/temp.priv", "--value=1", "--to={}".format(hub_address), '--data=' + "{:.1f}".format(temp) ]).decode("utf-8") print(transaction_result) time.sleep(5)
def start(self): ''' Starts running of bebop_demo node. Runs along the state sequence, sends out the current state and returns to the standby state when task is completed. ''' print green('---- Bebop core running ----') while not rospy.is_shutdown(): if self.task_str == "home inspection": self.home_inspection() elif self.task_str == "home inventory": self.inventory() elif self.task_str == "home count": self.count() elif self.task_str == "home picture": self.picture() elif self.task_str == "home guide": self.guide() elif self.task_str == "home events": self.events() elif self.task_str == "home smart inspection": self.home_inspection_smart() if self.new_task: self.new_task = False self.change_state = False self.state_finish = False # Run over sequence of states corresponding to current task. for state in self.state_sequence: self.state = state print cyan(' Bebop_core state changed to: ', self.state) self.fsm_state.publish(state) # Omg tools should return to its own standby status unless # the controller trackpad has been pressed. if self.state in { "omg standby", "omg fly", "omg fly A", "omg standby A", "omg fly inspection" }: self.omg_standby = True else: self.omg_standby = False if self.state == "land": self.change_state = True task_final_state = (self.state == self.state_sequence[-1]) # Check if previous state is finished and if allowed to # switch state based on controller input. while not ((self.state_finish and (self.change_state or task_final_state)) or self.new_task or rospy.is_shutdown()): # Remaining in state. Allow state action to continue. if self.state not in {"standby", "initialization"}: self.camera_actions() rospy.sleep(0.1) self.change_state = False self.state_finish = False leave_omg = (self.state == "omg standby" and not self.omg_standby) # User forces leaving omg with trackpad or other new task # received --> leave the for loop for the current task. if (leave_omg or self.new_task): # print cyan('---- Broke for loop ----') break # Make sure that omg-tools task is repeated until force quit. if self.omg_standby: self.new_task = True # Only publish standby state when task is finished. # Except for repetitive tasks (back to first state in task). if not self.new_task: self.state = "standby" self.fsm_state.publish("standby") print cyan(' Bebop_core state changed to: ', "standby") rospy.sleep(0.1)