class PreserveHeight: def __init__(self, height): self.pidInput = rospy.Publisher('pid_input', controller_msg, queue_size=10) self.height = height rospy.Subscriber('/pid/controller_command', controller_msg, self.HandlePID) rospy.Subscriber('/mavros/global_position/rel_alt', Float64, self.HandleAltitude) self.myNavigator = Navigator() def StartMission(self): print("Beginning Preserve Height Mission") print("Arming") if self.myNavigator.Arm(True): print("Armed") time.sleep(1) def HandlePID(self, data): self.myNavigator.PublishRCMessage(1500, 1500, data.z, 1500) print("PID Fix %s" % data.z) #Callback method for the rel_altitude topic def HandleAltitude(self, data): msg = controller_msg() msg.z = self.height - data.data #only working on alt values for now self.pidInput.publish(msg)
def preproc(self, world, game): print 'world %d x %d' % (world.width, world.height) pprint(map(list, zip(*world.tiles_x_y))) print world.waypoints print '=====================' self.navigator = Navigator(world) self.physics = Physics(world, game)
def __init__(self, height): self.pidInput = rospy.Publisher('pid_input', controller_msg, queue_size=10) self.height = height rospy.Subscriber('/pid/controller_command', controller_msg, self.HandlePID) rospy.Subscriber('/mavros/global_position/rel_alt', Float64, self.HandleAltitude) self.myNavigator = Navigator()
def main(): # read settings from settings file fs.read_settings_file() # run app at homepage App = QApplication(sys.argv) navigator = Navigator() navigator.show_homepage() sys.exit(App.exec())
def simplest(): def print_simplest(list): for elem in list: print(f"Index[{elem.index}] full path : {elem.full_path}") viz = Simplest() nav = Navigator() while viz.update(nav.read_next()): pass list = viz.visualize() print_simplest(list)
class TestBrowser(): def __init__(self): self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.path_selected = None self.navi = Navigator(self.window) self.img = Imager(self.window,400) #self.oper = Operator(self.window) self.gwydata = GwyData() self.channel_img = None # widget self.window.connect("destroy", lambda w: gtk.main_quit()) self.window.set_title("TestBrowser") self.vbox_main = gtk.VBox(False,0) self.vbox_main.pack_start(self.navi.vbox_main,0,1,0) self.vbox_main.pack_start(self.img.vbox_main,1,1,0) #self.vbox_main.pack_start(self.oper.vbox_main,0,1,0) self.window.add(self.vbox_main) self.window.show_all() # Signal handling self.navi.combobox_files.connect('changed',self.update_all,None) self.img.combobox_channels.connect('changed',self.record_channel,None) #self.navi.combobox_files.connect('changed',self.) def update_all(self,widget,data): self.current_data = self.navi.get_full_path() if self.current_data: self.gwydata.load_data(self.current_data) self.img.initialize(self.gwydata,self.channel_img) def record_channel(self,widget,data): self.channel_img = self.img.get_active_channel()
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()
def __init__( self, url, proxy = None): try: self.outputfile = __settings__.getSetting('download_folder') + "/bbcsports.flv" except: print "Output Filename must be set" exit (-1) self.pipeHandle = None if os.name == 'nt': self.outputfile = '\\\\.\\pipe\\bbcsports.flv' # Create the named pipe import win32file, win32pipe self.pipeHandle = win32pipe.CreateNamedPipe(self.outputfile, win32pipe.PIPE_ACCESS_DUPLEX, win32pipe.PIPE_TYPE_BYTE | win32pipe.PIPE_READMODE_BYTE | win32pipe.PIPE_WAIT, 50, 4096, 4096, 10000, None) if self.pipeHandle == win32file.INVALID_HANDLE_VALUE: print "Fatal: Couldn't create named pipe. Exiting." exit (-1) else: # Create the FIFO if os.path.exists(self.outputfile): os.unlink(self.outputfile) os.mkfifo(self.outputfile) self.url = url self.proxy = proxy self.navigator = Navigator( self.proxy ) self.manifestURL = None self.drm = None self.segNum = 1 self.pos = 0 self.boxType = None self.boxSize = None self.fragNum = None self.rename = False self.prevTagSize = 4 self.tagHeaderLen = 11 self.baseTS = False self.prevAudioTS = -1 self.prevVideoTS = -1 self.TIMECODE_DURATION = 8 self.duration = 0 self.audio = False self.video = False self.prevAVC_Header = False self.prevAAC_Header = False self.AVC_HeaderWritten = False self.AAC_HeaderWritten = False self.dataQueue = Queue.Queue(50) self.dataThread = None self.dataThreadKill = False self.dataWritten = False self.needNewBootstrap = False self.flvHeader = bytearray.fromhex(unicode('464c5601050000000900000000')) self.flvHeaderLen = len(self.flvHeader)
def main(stdscr): logging.basicConfig( level=logging.DEBUG, filename='app.log', filemode='w', format='%(name)s - %(levelname)s - [%(filename)s:%(lineno)s - %(funcName)20s() ] - %(message)s') print('Initializing...') display = Display() navigator = Navigator(display) choice_handler = ChoiceHandler(navigator) json_handler = JsonHandler(navigator) data_handler = EcsManager(choice_handler, json_handler) while True: data_handler.update()
def graphwise(): #setup viz = Graphwise() nav = Navigator() grayscale = True DNA_ish = not True wid, hi = 400,400 gif_path = f'result/{"DNA" if DNA_ish else "graphwise"}_{"gray" if grayscale else "rgb"}.gif' gif_duration = 4 #seconds images = [] cv_cvt_format = cv.COLOR_GRAY2RGB if grayscale else cv.COLOR_BGR2RGB def cv_img_to_PIL_img(cv_img): return Image.fromarray(cv.cvtColor(cv_img, cv_cvt_format)) #main logic while viz.update(nav.read_next()): cv_img = viz.visualize(wid, hi, grayscale=grayscale, DNA_ish=DNA_ish) images.append(cv_img_to_PIL_img(cv_img)) pass #view results stat = viz.stat() print(f"[Statistics]") print(f"\tFile count [{stat[0]}]") print(f"\tDirectory count(including root) [{stat[1]}]") print(f"\tMaximum file size : [{stat[2]}bytes]") print(f"\tTotal file size : [{stat[3]}bytes]") if images: print("Creating gif...") images[0].save(gif_path, save_all=True, append_images=images[1:], optimize=True, duration=int((gif_duration*1000)/len(images)), loop=0) print("GIF saving done") cv.imshow("Result", viz.visualize(wid, hi, grayscale=grayscale, DNA_ish=DNA_ish)) cv.waitKey(0)
def extract_news(trending_terms, get_objects=False, dangerous=False, safe=True): # Returns a list of NewsWebsite Objects websites = Navigator.navigate(trending_terms, dangerous, safe) # Returns a list of Link Objects articles = Seeker.seek(websites) links = [] # Writes to file, to be FTP'ed, additionally returns as Link objects if specified if get_objects: for article in articles: link = MaxSubSequence.extract_data(article, get_objects) if link: links.append(link) return links else: for article in articles: MaxSubSequence.extract_data(article, get_objects)
class TestBrowser(): def __init__(self): self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.path_selected = None self.navi = Navigator(self.window) self.mimg = MultiImager(self.window,4) self.gwydata = GwyData() self.channel_img = None # widget self.window.connect("destroy", lambda w: gtk.main_quit()) self.window.set_title("TestBrowser") self.vbox_main = gtk.VBox(False,0) self.vbox_main.pack_start(self.navi.vbox_main,0,1,0) self.vbox_main.pack_start(self.mimg.hbox_main,1,1,0) self.window.add(self.vbox_main) self.window.show_all() # Signal handling self.navi.combobox_files.connect('changed',self.update_all,None) def update_all(self,widget,data): self.current_data = self.navi.get_full_path() if self.current_data: self.mimg.initialize(self.navi.path_selected,self.navi.files,self.navi.get_index()) self.mimg.update_image(widget,None)
def __init__(self): self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.path_selected = None self.navi = Navigator(self.window) self.img = Imager(self.window,400) #self.oper = Operator(self.window) self.gwydata = GwyData() self.channel_img = None # widget self.window.connect("destroy", lambda w: gtk.main_quit()) self.window.set_title("TestBrowser") self.vbox_main = gtk.VBox(False,0) self.vbox_main.pack_start(self.navi.vbox_main,0,1,0) self.vbox_main.pack_start(self.img.vbox_main,1,1,0) #self.vbox_main.pack_start(self.oper.vbox_main,0,1,0) self.window.add(self.vbox_main) self.window.show_all() # Signal handling self.navi.combobox_files.connect('changed',self.update_all,None) self.img.combobox_channels.connect('changed',self.record_channel,None)
def __init_properties(self, document): self.__dict__['__cx'].add_global('window', self) self.__dict__['__cx'].add_global('self' , self) self.__dict__['__cx'].execute("window.window = window;") self.__dict__['__cx'].add_global('document', document) self.__dict__['__cx'].execute("window.document = document;") self.__dict__['__cx'].add_global('location', document.location) self.__dict__['__cx'].execute("window.location = location;") self.__dict__['__cx'].add_global("ActiveXObject", ActiveXObject) self.__dict__['__cx'].add_global("navigator", Navigator()) self.__dict__['__cx'].execute("window.navigator = navigator;") self.__dict__['__cx'].add_global("screen", unknown()) self.__dict__['__cx'].execute("window.screen = screen;") if 'top_window' in self.__dict__['__root'].__dict__: if self.__dict__['__referrer']: top = self.__dict__['__referrer'] else: top = self.__dict__['__root'].top_window else: top = self self.__dict__['__cx'].add_global("top", top) self.__dict__['__cx'].execute("window.top = top;") self.__dict__['__cx'].add_global("parent", top) self.__dict__['__cx'].execute("window.parent = parent;") self.__dict__['__cx'].add_global("history", History(document)) self.__dict__['__cx'].execute("window.history = history;") self.__dict__['__cx'].execute("window.innerWidth = 400;") self.__dict__['__cx'].execute("window.innerHeight = 200;") self.__dict__['__cx'].execute("window.name = '';") self.__init_undefined_properties()
def __init__(self): # Definiton of the variables self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.path_selected = None self.navi = Navigator(self.window) self.info = Infor(self.window) self.oper = Operator(self.window) self.gwydata = GwyData() self.img_1 = Imager(self.window,400) self.img_2 = Imager(self.window,400) self.channel_img_1 = None self.channel_img_2 = None # Definition of the widget self.window.connect("destroy", lambda w: gtk.main_quit()) self.window.set_title("SPMBrowser") # vbox_main self.vbox_main = gtk.VBox(False,0) # hbox_main self.hbox_main = gtk.HBox(False,0) self.vbox_2 = gtk.VBox(False,0) self.hbox_main.pack_start(self.img_1.vbox_main,1,1,0) self.hbox_main.pack_start(self.img_2.vbox_main,1,1,0) self.vbox_2.pack_start(self.info.table_info,0,1,0) self.vbox_2.pack_end(self.oper.vbox_main,0,1,0) self.hbox_main.pack_end(self.vbox_2,0,1,0) # pack self.vbox_main.pack_start(self.navi.vbox_main,0,1,0) self.vbox_main.pack_start(self.hbox_main,0,1,0) self.window.add(self.vbox_main) self.window.show_all() # Signal handling self.navi.combobox_files.connect('changed',self.update_all,None) self.img_1.combobox_channels.connect('changed',self.record_channels,None) self.img_2.combobox_channels.connect('changed',self.record_channels,None) #self.info.entry_ratio.connect('changed',self.update_info,None) self.window.connect('key_press_event',self._key_press_event)
class App( Lifecycle ): def __init__( self, root, dim=None, appName='BreadInterface' ): # init the app components # self.settings = Settings(appName) self.navigator = Navigator( root, dim ) self.appName = appName def cleanup( self ): self.settings.cleanup() self.navigator.cleanup() def start( self ): if not self.navigator.ready: print "Navigator not ready..." return self.navigator.window.set_title( self.appName ) self.navigator.start() def stop( self ): self.navigator.stop()
class App(Lifecycle): def __init__(self, root, dim=None, appName='BreadInterface'): # init the app components # self.settings = Settings(appName) self.navigator = Navigator(root, dim) self.appName = appName def cleanup(self): self.settings.cleanup() self.navigator.cleanup() def start(self): if not self.navigator.ready: print "Navigator not ready..." return self.navigator.window.set_title(self.appName) self.navigator.start() def stop(self): self.navigator.stop()
def __init__(self, fileName): print("i am getting better at oo arch") navi = Navigator.readPickle(fileName) self.words = navi.wordsGenerated
def main(): clearConsole() nav = Navigator() courses = [] major, minor, micro = sys.version_info[:3] message = checkVersion(major, minor, micro) if message != "": print message if "Error" in message: sys.exit(1) username = getpass('PID: ') password = getpass() print "Logging In.. " sys.stdout.flush() while (nav.login(username, password) is False): print "Please Try Again" username = raw_input('PID: ') password = getpass() clearConsole() automate = raw_input("Automate?: ") if automate: errors = "" CRN = "92074" TERM = "09" YEAR = "2013" SUBJ = "CS" CRSE = "2114" else: errors = 1 print "Logged In" print "Please Enter The Following Information:" error_checker = ErrorCheck() while (errors): CRN = raw_input('CRN: ') or "" # or "92083" TERM = raw_input('TERM (F, S, S1, or S2) (F - Default): ' ) or "09" # Default TERM if nothing is given YEAR = raw_input('YEAR (2013 - Default): ' ) or "2013" # Default YEAR if nothing is given SUBJ = raw_input('SUBJ: ') or "" CRSE = raw_input('CRSE: ') or "" print "\nChecking for Errors in Course Information..\n" errors = error_checker.obviousChecks(crn=CRN, subj=SUBJ, crse=CRSE) if (errors): print "Sorry, There Were Some Errors: \n" print "Error(s): " for error in errors: print error print "Please Try Again" clearConsole() print "Everything Looks Good.." print "Searching for Class Information.." if ((SUBJ and CRSE) or CRN): course_info = nav.find(subj=SUBJ, crse=CRSE, term=TERM, year=YEAR, crn=CRN) else: print "Sorry.. You Didn't Enter Enough Information" sys.exit(0) if course_info is None: print "Sorry.. No Sections were Found" answer = raw_input("Try Again..? ") sys.exit(0) else: course_info = Cleaner(course_info) print "Here's What I Found.." print course_info answer = YesNo( raw_input("Do You Wish to Add a Course? Enter (y)es or (n)o: ")) if answer == "Yes": CRN = raw_input("Please Enter the CRN: ") courses.append(CRN) else: sys.exit(0)
from selenium import webdriver from Navigator import Navigator from Course import Course browser = webdriver.Firefox() nav = Navigator(browser) nav.bypassLogin('student_id','student_pass', '00015nkpAHD9RrsJ5Jh3bsPsyhB:14a0b94d8') nav.gotoClassRegistration('ran_num') cpre = Course('CPR E', '288', 'B') coms = Course('COM S', '309') nav.gotoCourseAvailability(cpre) nav.gotoCourseAvailability(coms) nav.gotoClassRegistration() nav.gotoCourseAvailability(cpre)
class BBCDL( object ): def __init__( self, url, proxy = None): try: self.outputfile = __settings__.getSetting('download_folder') + "/bbcsports.flv" except: print "Output Filename must be set" exit (-1) self.pipeHandle = None if os.name == 'nt': self.outputfile = '\\\\.\\pipe\\bbcsports.flv' # Create the named pipe import win32file, win32pipe self.pipeHandle = win32pipe.CreateNamedPipe(self.outputfile, win32pipe.PIPE_ACCESS_DUPLEX, win32pipe.PIPE_TYPE_BYTE | win32pipe.PIPE_READMODE_BYTE | win32pipe.PIPE_WAIT, 50, 4096, 4096, 10000, None) if self.pipeHandle == win32file.INVALID_HANDLE_VALUE: print "Fatal: Couldn't create named pipe. Exiting." exit (-1) else: # Create the FIFO if os.path.exists(self.outputfile): os.unlink(self.outputfile) os.mkfifo(self.outputfile) self.url = url self.proxy = proxy self.navigator = Navigator( self.proxy ) self.manifestURL = None self.drm = None self.segNum = 1 self.pos = 0 self.boxType = None self.boxSize = None self.fragNum = None self.rename = False self.prevTagSize = 4 self.tagHeaderLen = 11 self.baseTS = False self.prevAudioTS = -1 self.prevVideoTS = -1 self.TIMECODE_DURATION = 8 self.duration = 0 self.audio = False self.video = False self.prevAVC_Header = False self.prevAAC_Header = False self.AVC_HeaderWritten = False self.AAC_HeaderWritten = False self.dataQueue = Queue.Queue(50) self.dataThread = None self.dataThreadKill = False self.dataWritten = False self.needNewBootstrap = False self.flvHeader = bytearray.fromhex(unicode('464c5601050000000900000000')) self.flvHeaderLen = len(self.flvHeader) def run(self): print "Started download thread" flv = None self.baseUrl = self.url[0: self.url.rfind("/")] # Get the manifest self.manifest = self.navigator.getFile(self.url) # Parse the manifest self.parseManifest() segNum = self.segNum fragNum = self.fragNum #print segNum #print fragNum #print self.fragCount self.baseFilename = (self.streamid.attrib["streamId"] + "Seg%d" + "-Frag") % (segNum) self.fragUrl = self.baseUrl + "/" + self.streamid.attrib["url"] # Kick off the data fetching thread self.dataThread = threading.Thread(target=self.runDataThread) self.dataThread.start() while not self.dataThreadKill: fragNum, data = self.dataQueue.get() if fragNum is None: # New bootstrap info for us sys.stdout.write("Updating bootstrap info") self.UpdateBootstrapInfoWithData(data) else: sys.stdout.write("Decoding fragment %d of %d\r" % (fragNum, self.fragCount)) # Create the FLV if it doesn't exist if (flv is None): self.start = datetime.datetime.now() flvData = self.DecodeFragment(data, fragNum, None) #flv = self.WriteFlvFile("C:/" + self.baseFilename + ".flv", self.audio, self.video) self.dataWritten = True flv = self.WriteFlvFile(self.outputfile, self.audio, self.video) flv.write(flvData) else: self.DecodeFragment(data, fragNum, flv) self.dataQueue.task_done() if self.pipeHandle: self.pipeHandle.Close() self.pipeHandle = None exit(-1) def runDataThread(self): listeUserAgents = [ 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_5; fr-fr) AppleWebKit/525.18 (KHTML, like Gecko) Version/3.1.2 Safari/525.20.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.186 Safari/535.1', 'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.2.149.27 Safari/525.13', 'Mozilla/5.0 (X11; U; Linux x86_64; en-us) AppleWebKit/528.5+ (KHTML, like Gecko, Safari/528.5+) midori', 'Mozilla/5.0 (Windows NT 6.0) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.107 Safari/535.1', 'Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en-us) AppleWebKit/312.1 (KHTML, like Gecko) Safari/312', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.12 Safari/535.11', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.8 (KHTML, like Gecko) Chrome/17.0.940.0 Safari/535.8' ] # Init curl c = pycurl.Curl() data = CurlData() c.setopt(c.WRITEFUNCTION, data.body_callback) c.setopt(pycurl.TIMEOUT, 30) # Set up user agent c.setopt(c.USERAGENT, random.choice(listeUserAgents)) # And proxy if self.proxy: if self.proxy[0] != socks.PROXY_TYPE_HTTP_NO_TUNNEL: # Set generic options c.setopt(c.PROXY, self.proxy[1]) c.setopt(c.PROXYPORT, self.proxy[2]) c.setopt(c.PROXYUSERPWD, "%s:%s" % (self.proxy[4],self.proxy[5])) if self.proxy[0] == socks.PROXY_TYPE_HTTP: c.setopt(c.PROXYTYPE_HTTP) elif self.proxy[0] == socks.PROXY_TYPE_SOCKS4: c.setopt(c.PROXYTYPE_SOCKS4) elif self.proxy[0] == socks.PROXY_TYPE_SOCKS5: # pycurl doesn't seem to define c.PROXYTYPE_SOCKS5_HOSTNAME, so use the URL prefix method instead c.setopt(c.PROXY, "socks5h://%s" % (self.proxy[1])) #c.setopt(c.PROXYTYPE_SOCKS5) # Set up our fragment vars segNum = self.segNum fragNum = self.fragNum retries = 3 while not self.dataThreadKill: data.reset() if self.needNewBootstrap: # Download a new bit of bootstrap info c.setopt(c.URL, self.urlbootstrap) try: c.perform() self.dataQueue.put((None, data.contents)) self.needNewBootstrap = False except Exception as e: print "Curl failed to fetch new bootstrap data: %s" % e.strerror else: # Download the next fragment fragNum = fragNum + 1 if (self.segNum > 1): if (fragNum > (segNum * self.fragsPerSeg)): segNum = segNum + 1 # Segment change, update bootstrap to get new fragsPerSeg self.needNewBootstrap = True elif (fragNum <= ((segNum - 1) * self.fragsPerSeg)): segNum = segNum - 1 # Segment change, update bootstrap to get new fragsPerSeg self.needNewBootstrap = True filename1 = (self.fragUrl + "Seg%d" + "-Frag%d") % (segNum, fragNum) c.setopt(c.URL, filename1) try: c.perform() if(len(data.contents) < 1000): print "No more data available - waiting a bit." time.sleep(0.5) fragNum = fragNum - 1 continue retries = 3 self.dataQueue.put((fragNum, data.contents)) except Exception as e: retries = retries - 1 if retries > 0: # If we're retrying, roll back the fragNum fragNum = fragNum - 1 else: print "Couldn't download fragment %d" % fragNum c.close() def UpdateBootstrapInfoWithData(self, bootstrapData): bootstrapPos = 0 origFragCount = self.fragCount self.ReadBoxHeader(bootstrapData, bootstrapPos, None, None) bootstrapPos = self.pos if (self.boxType == "abst"): self.ParseBootstrapBox(bootstrapData, bootstrapPos) if origFragCount == self.fragCount: self.needNewBootstrap = True else: print "New fragment count is: %d" % self.fragCount def UpdateBootstrapInfo(self, bootstrapUrl): retries = 0 fragNum = self.fragCount while ((fragNum == self.fragCount) and (retries < 30)): bootstrapPos = 0 try: bootstrapfile = self.navigator.getFile(bootstrapUrl) except: exit(-1) self.ReadBoxHeader(bootstrapfile, bootstrapPos, None, None); #print self.boxType bootstrapPos = self.pos if (self.boxType == "abst"): self.ParseBootstrapBox(bootstrapfile, bootstrapPos); else: exit(-1) if (fragNum == self.fragCount): time.sleep(0.5) retries = retries + 1 if (retries == 30): print "Unable to update Bootstrap Information" exit (-1) def parseManifest( self ): try : tree = xml.etree.ElementTree.fromstring( self.manifest ) # Duration self.duration = float( tree.find( "{http://ns.adobe.com/f4m/1.0}duration" ).text ) self.media = tree.findall( "{http://ns.adobe.com/f4m/1.0}bootstrapInfo" )[ -1 ] self.streamid = tree.findall( "{http://ns.adobe.com/f4m/1.0}media" )[ -1 ] # Bootstrap URL self.urlbootstrap = self.media.attrib[ "url" ] except : print( "Not possible to parse the manifest" ) sys.exit( -1 ) self.urlbootstrap = self.baseUrl + "/" + self.urlbootstrap try : bootstrapfile = self.navigator.getFile(self.urlbootstrap) except : print( "Not possible to get the bootstrap file") sys.exit( -1 ) self.ReadBoxHeader(bootstrapfile, self.pos, self.boxType, self.boxSize) if (self.boxType == "abst"): self.ParseBootstrapBox(bootstrapfile, self.pos) def ReadBoxHeader(self, input_str, pos, boxType, boxSize): if (pos is None): pos = 0 self.boxSize = self.ReadInt32(input_str, pos) boxTypeString = (input_str[pos+4], input_str[pos+5], input_str[pos+6], input_str[pos+7]) self.boxType = string.join(boxTypeString, "") if (self.boxSize == 1): self.boxSize = self.ReadInt64(input_str, pos+8) -16 pos = pos + 16; else: self.boxSize = self.boxSize - 8 pos = pos + 8 self.pos = pos def ParseBootstrapBox(self, bootstrapinfo, pos): version = self.ReadByte(bootstrapinfo, pos) flags = self.ReadInt24(bootstrapinfo, (pos+1)) bootstrapVersion = self.ReadInt32(bootstrapinfo, (pos + 4)) byte = self.ReadByte(bootstrapinfo, (pos + 8)) profile = (byte & 0xC0) >> 6 self.live = (byte & 0x20) >> 5 update = (byte & 0x10) >> 4 timescale = self.ReadInt32(bootstrapinfo, (pos + 9)) currentMediaTime = self.ReadInt64(bootstrapinfo, 13) smpteTimeCodeOffset = self.ReadInt64(bootstrapinfo, 21) pos = pos + 29 movieIdentifier = self.ReadString(bootstrapinfo, pos) pos = self.pos serverEntryCount = self.ReadByte(bootstrapinfo, pos) pos += 1 qualityEntryCount = self.ReadByte(bootstrapinfo, pos) pos += 1 drmData = self.ReadString(bootstrapinfo, pos) pos = self.pos metadata = self.ReadString(bootstrapinfo, pos) pos = self.pos segRunTableCount = self.ReadByte(bootstrapinfo, pos) pos = pos + 1 for i in range(0, segRunTableCount): self.ReadBoxHeader(bootstrapinfo, pos, self.boxType, self.boxSize) i=i+1 if (self.boxType == "asrt"): self.ParseAsrtBox(bootstrapinfo, self.pos) #print "ASRT" pos = self.pos + self.boxSize fragRunTableCount = self.ReadByte(bootstrapinfo, pos) pos = pos + 1 for i in range(0, fragRunTableCount): self.ReadBoxHeader(bootstrapinfo, pos, self.boxType, self.boxSize) i=i+1 if (self.boxType == "afrt"): self.ParseAfrtBox(bootstrapinfo, self.pos) pos = self.pos + self.boxSize self.pos = pos def ReadInt32(self, input_str, pos): int32 = struct.unpack(">I", input_str[pos] + input_str[pos+1] + input_str[pos+2] + input_str[pos+3])[0] return int32 def ReadInt24(self, input_str, pos): int24 = struct.unpack(">I", '\x00' + input_str[pos] + input_str[pos+1] + input_str[pos+2])[0] return int24 def ReadByte(self, input_str, pos): unpacked_int = struct.unpack("B", input_str[pos])[0]; return unpacked_int def ReadInt64(self, input_str, pos): #hi = sprintf("%u", self.ReadInt32(str, pos)) #lo = sprintf("%u", self.ReadInt32(str, pos + 4)) hi = self.ReadInt32(input_str, pos) lo = self.ReadInt32(input_str, pos + 4) int64 = (hi * 4294967296 ) + lo #int64 = bcadd(bcmul(hi, "4294967296"), lo) return int64 def ReadString(self, frag, fragPos): strlen = 0 while (frag[fragPos + strlen] != "\x00"): strlen += 1 str = frag[fragPos: strlen] fragPos += strlen + 1 self.pos = fragPos return str def ParseAsrtBox(self, asrt, pos): version = self.ReadByte(asrt, pos) flags = self.ReadInt24(asrt, (pos + 1)) qualityEntryCount = self.ReadByte(asrt, (pos + 4)) pos = pos + 5 for i in range (0, qualityEntryCount): #qualitySegmentUrlModifiers[i] = self.ReadString(asrt, pos) i = i+1 self.segCount = self.ReadInt32(asrt, pos) self.segTable = dict( ((i,j),None) for i in range(self.segCount) for j in range(2) ) pos = pos + 4 for i in range (0, self.segCount): firstSegment = self.ReadInt32(asrt, pos) fragmentsPerSegment = self.ReadInt32(asrt, (pos + 4)) self.segTable[i, 0] = firstSegment self.segTable[i, 1] = fragmentsPerSegment pos = pos+8 i=i+1 lastSegment = self.segTable[self.segCount-1, 0] self.fragCount = self.segTable[self.segCount-1, 1] if (self.live == 1) and (self.segCount >1): try: secondLastSegment = self.segCount-2 except: pass if self.fragNum is None: self.segNum = lastSegment self.fragsPerSeg = self.segTable[secondLastSegment, 1] self.fragNum = self.segTable[secondLastSegment,0] * self.fragsPerSeg + self.fragCount - 2; self.fragCount = self.segTable[secondLastSegment,0] * self.fragsPerSeg + self.fragCount; else: self.fragCount = self.segTable[secondLastSegment,0] * self.fragsPerSeg + self.fragCount; def ParseAfrtBox(self, afrt, pos): version = self.ReadByte(afrt, pos) flags = self.ReadInt24(afrt, pos + 1) timescale = self.ReadInt32(afrt, pos + 4) qualityEntryCount = self.ReadByte(afrt, pos + 8) pos = pos + 9 self.fragEntries = self.ReadInt32(afrt, pos) self.fragTable = dict( ((i,j),None) for i in range(self.fragEntries) for j in range(4) ) pos = pos + 4 for i in range (0, self.fragEntries): firstFragment = self.ReadInt32(afrt, pos) self.fragTable[i,0] = firstFragment self.fragTable[i,1] = self.ReadInt64(afrt, pos + 4) self.fragTable[i,2] = self.ReadInt32(afrt, pos + 12) self.fragTable[i,3] = "" pos += 16 if self.fragTable[i,2] == 0: self.fragTable[i,3] = self.ReadByte(afrt, pos) pos = pos + 1 i = i + 1 if self.segCount == 1: firstFragment = 0 lastFragment = self.fragEntries if self.live == 1: if self.fragNum is None: self.fragNum = self.fragTable[lastfragment, 0] - 2 self.fragCount = self.fragTable[firstFragment, 0] else: self.fragCount = self.fragTable[lastFragment,0] elif self.fragNum is None: self.fragNum = self.fragTable[firstFragment,0] - 1 def DecodeFragment(self, frag, fragNum, flv): flvData = "" fragLen = 0 fragPos = 0 boxSize = 0 fragLen = len(frag) packetTS = None while (fragPos < fragLen): self.ReadBoxHeader(frag, fragPos, None, None) if (self.boxType == "mdat"): fragPos = self.pos break fragPos = self.pos + self.boxSize while (fragPos < fragLen): packetType = self.ReadByte(frag, fragPos) packetSize = self.ReadInt24(frag, fragPos + 1) packetTS = self.ReadInt24(frag, fragPos + 4) packetTS = (packetTS | (self.ReadByte(frag, fragPos + 7) << 24)) if (packetTS & 0x80000000): packetTS &= 0x7FFFFFFF #self.WriteFlvTimestamp(frag, fragPos, packetTS) if ((self.baseTS is False) and ((packetType == 0x08) or (packetType == 0x09))): self.baseTS = packetTS totalTagLen = self.tagHeaderLen + packetSize + self.prevTagSize if packetType == 0x08: if (packetTS >= self.prevAudioTS - self.TIMECODE_DURATION * 5): FrameInfo = self.ReadByte(frag, fragPos + self.tagHeaderLen) CodecID = (FrameInfo & 0xF0) >> 4 if (CodecID == 0x0A): AAC_PacketType = self.ReadByte(frag, fragPos + self.tagHeaderLen + 1) if (AAC_PacketType == 0x00): if (self.AAC_HeaderWritten is True): #break i = 1 #print "Skipping" else: #print("Writing AAC sequence header") self.AAC_HeaderWritten = True self.prevAAC_Header = True elif (self.AAC_HeaderWritten is False): i = 1 #print("Discarding audio packet received before AAC sequence header",) #break if (packetSize > 0): #Check for packets with non-monotonic audio timestamps and fix them if ((self.prevAAC_Header is False) and (packetTS <= self.prevAudioTS)): #print ("Fixing audio timestamp") packetTS = packetTS + self.TIMECODE_DURATION + (self.prevAudioTS - packetTS) #self.WriteFlvTimestamp(frag, fragPos, packetTS) if ((CodecID == 0x0A) and (AAC_PacketType != 0x00)): self.prevAAC_Header = False if (flv): #pAudioTagPos = flv.tell() if xbmc.Player().isPlaying(): flvData = frag[fragPos: fragPos + totalTagLen] flv.write(flvData) else: self.stop = datetime.datetime.now() elapsed = self.stop - self.start if (elapsed > datetime.timedelta(seconds=25)): self.dataThreadKill = True print "Downloads Killed" exit(-1) else: flvData = frag[fragPos: fragPos + totalTagLen] flv.write(flvData) #flvData = frag[fragPos: fragPos + totalTagLen] #flv.write(flvData) else: #flvData .= substr($frag, $fragPos, $totalTagLen); flvData = flvData + frag[fragPos: fragPos + totalTagLen] self.prevAudioTS = packetTS pAudioTagLen = totalTagLen else: i = 1 #print ("Skipping small sized audio packet") else: i= 1 #print "Test" if (self.audio is False): self.audio = True #break elif packetType == 0x09: if (packetTS >= self.prevVideoTS - self.TIMECODE_DURATION * 5): FrameInfo = self.ReadByte(frag, fragPos + self.tagHeaderLen) FrameType = (FrameInfo & 0xF0) >> 4 CodecID = FrameInfo & 0x0F if (FrameType == 0x05): printf("Skipping video info frame") if (CodecID == 0x07): AVC_PacketType = self.ReadByte(frag, fragPos + self.tagHeaderLen + 1) if (AVC_PacketType == 0x00): if (self.AVC_HeaderWritten is True): i = 1 #print ("Skipping AVC sequence header") else: #print("Writing AVC sequence header") self.AVC_HeaderWritten = True self.prevAVC_Header = True elif (self.AVC_HeaderWritten is False): i = 1 #print ("Discarding video packet received before AVC sequence header") if (packetSize > 0): #Check for packets with non-monotonic video timestamps and fix them if ((self.prevAVC_Header is False) and ((CodecID == 0x07) and (AVC_PacketType != 0x02)) and (packetTS <= self.prevVideoTS)): #print("Fixing video timestamp") packetTS = packetTS + self.TIMECODE_DURATION + (self.prevVideoTS - packetTS) #self.WriteFlvTimestamp(frag, fragPos, packetTS) if ((CodecID == 0x07) and (AVC_PacketType != 0x00)): self.prevAVC_Header = False if (flv): if xbmc.Player().isPlaying(): flvData = frag[fragPos: fragPos + totalTagLen] flv.write(flvData) else: self.stop = datetime.datetime.now() elapsed = self.stop - self.start if (elapsed > datetime.timedelta(seconds=25)): self.dataThreadKill = True print "Downloads Killed" exit(-1) else: flvData = frag[fragPos: fragPos + totalTagLen] flv.write(flvData) #flvData = frag[fragPos: fragPos + totalTagLen] #flv.write(flvData) #exit(-1) #flvData = frag[fragPos: fragPos + totalTagLen] #flv.write(flvData) #pVideoTagPos = flv.tell() #fwrite($flv, substr($frag, $fragPos, $totalTagLen), $totalTagLen) else: #flvData .= substr($frag, $fragPos, $totalTagLen) flvData = flvData + frag[fragPos:fragPos+totalTagLen] self.prevVideoTS = packetTS pVideoTagLen = totalTagLen else: print ("Skipping small sized video packet") if (self.video is False): self.video = True #break elif packetType == 0x12: i = 1
class SimpleViewer(avango.script.Script): SceneGraph = avango.gua.SFSceneGraph() Navigator = Navigator() Viewer = avango.gua.nodes.Viewer() Shell = GuaVE() def __init__(self): self.super(SimpleViewer).__init__() self.window_size = avango.gua.Vec2ui(1920, 1080) # create resolve pass self.res_pass = avango.gua.nodes.ResolvePassDescription() self.res_pass.EnableSSAO.value = True self.res_pass.SSAOIntensity.value = 4.0 self.res_pass.SSAOFalloff.value = 10.0 self.res_pass.SSAORadius.value = 7.0 self.res_pass.EnvironmentLightingColor.value = avango.gua.Color( 0.1, 0.1, 0.1) self.res_pass.ToneMappingMode.value = avango.gua.ToneMappingMode.UNCHARTED self.res_pass.Exposure.value = 1.0 self.res_pass.BackgroundColor.value = avango.gua.Color(0.0, 0.0, 0.0) self.res_pass.BackgroundMode.value = avango.gua.BackgroundMode.COLOR # create anti-aliasing pass self.anti_aliasing = avango.gua.nodes.SSAAPassDescription() # create pipeline description self.pipeline_description = avango.gua.nodes.PipelineDescription( Passes=[ avango.gua.nodes.TriMeshPassDescription(), avango.gua.nodes.LightVisibilityPassDescription(), self.res_pass, self.anti_aliasing ]) # create window self.window = avango.gua.nodes.GlfwWindow( Size=self.window_size, LeftResolution=self.window_size) avango.gua.register_window("window", self.window) def run(self, locals, globals, show_guave_banner=True): self.Shell.start(locals, globals, show_guave_banner) self.Viewer.run() def list_variabels(self): self.Shell.list_variables() def start_navigation(self): self.navigation.Transform.connect_from(self.Navigator.OutTransform) def set_background_image(self, path): self.res_pass.BackgroundMode.value = avango.gua.BackgroundMode.SKYMAP_TEXTURE self.res_pass.BackgroundTexture.value = path @field_has_changed(SceneGraph) def update_scenegraph(self): self.navigation = avango.gua.nodes.TransformNode(Name="navigation") cam = avango.gua.nodes.CameraNode( Name="cam", LeftScreenPath="/navigation/screen", SceneGraph=self.SceneGraph.value.Name.value, Resolution=self.window_size, OutputWindowName="window", Transform=avango.gua.make_trans_mat(0.0, 0.0, 1.0)) cam.PipelineDescription.value = self.pipeline_description screen = avango.gua.nodes.ScreenNode(Name="screen", Width=1.6, Height=1.0) self.navigation.Children.value = [cam, screen] self.SceneGraph.value.Root.value.Children.value.append(self.navigation) self.Navigator.OutTransform.connect_from(cam.Transform) self.Navigator.RotationSpeed.value = 0.2 self.Navigator.MotionSpeed.value = 0.04 self.Viewer.SceneGraphs.value = [self.SceneGraph.value] self.Viewer.Windows.value = [self.window]
#send heartbeat email every time program runs heartbeat = True if delayStartup: delay = random.randint(60,690) #delay between 1 minute and 16 minutes print 'Delaying program: ' + str(delay/60) + ' minutes' time.sleep(delay) browser = webdriver.Firefox() nav = Navigator(browser) parser = WebParser(browser) manager = CourseManager(browser,nav, parser) schedParser = ScheduleParser() notify = EmailNotifier(sender,sender_pass) #if True: try: #parse schedule file schedParser.parseFile('Spring2015.scd') courseList = schedParser.getCourseList() schedules = schedParser.getSchedules()
def demo(): printWelcomeMsg() while True: print('\n================= MAIN MENU =================\n') buildingId = int(input('Please enter building ID: ')) buildingName = algorithms.buildingDict[buildingId] buildingStorey = int(input('Please enter building storey: ')) myMap = algorithms.downloadAndParseMap(buildingId, buildingName, buildingStorey) print( 'Please enter an option:\n 1. Path Finding\n 2. Giving Direction (cumulative)\n 3. Quit Test' ) testType = input() if testType == '1': while True: print('\n=============== NEW TEST CASE ===============\n') srcNodeId = int( input( 'Please enter origin node ID (enter \'0\' to return to the main menu): ' )) if srcNodeId == 0: break destNodeId = int( input( 'Please enter destination node ID (enter \'0\' to return to the main menu): ' )) if destNodeId == 0: break result = algorithms.computeRoute(myMap, srcNodeId, destNodeId) for i in range(len(result) - 1): print(str(result[i]) + ' -> ', end="") print(result[len(result) - 1]) elif testType == '2': srcNodeId = int(input('Please enter origin node ID: ')) destNodeId = int(input('Please enter destination node ID: ')) currentX = int( input('Please enter the x-coordinate of current location: ')) currentY = int( input('Please enter the y-coordinate of current location: ')) currentBearing = int( input( 'Please enter the bearing (w.r.t. geographical north) of current location: ' )) route = algorithms.computeRoute(myMap, srcNodeId, destNodeId) navigator = Navigator(myMap, route, currentX, currentY, currentBearing, 50) while True: print('\n=============== NEW TEST CASE ===============\n') currentX = int( input( 'Please enter the x-coordinate of current location: ')) currentY = int( input( 'Please enter the y-coordinate of current location: ')) currentBearing = int( input( 'Please enter the bearing (w.r.t. geographical north) of current location: ' )) navigator.updateLocation(currentX, currentY, currentBearing) if navigator.clearedRouteIdx == len(navigator.route) - 1: print('You have reached the destination node.') break naviInfo = navigator.getNaviInfo() print('Next node ID is ' + str(navigator.route[navigator.clearedRouteIdx + 1]) + '.') print('Distance from next node is ' + str(naviInfo[0]) + ' centimeters.') bearing = (naviInfo[1] - (currentBearing + myMap.northAt) % 360 + 360) % 360 print('Bearing of next node from current location is ' + str(bearing) + ' degrees.') else: break return
from behave import given, when, then from Navigator import Navigator from getpass import getpass nav = Navigator() nav.clearBrowser() # We will need to clear "br" since br is using mechanize which is a module and can't be instantiated multiple times, only once @given('I am logged in') def impl(context): if (nav.logged_in is False): username = getpass('PID: ') password = getpass() nav.logged_in = nav.login(username, password) assert nav.logged_in is True @given('I enter an incorrect CRN number "{entered_crn}" and my course info is checked') def impl(context, entered_crn): context.response = nav.validCourseInfo(crn=entered_crn, subj="", crse="") context.expected_errors = ["Please enter a valid CRN"] # We are expecting this error @given('I enter a correct CRN number "{entered_crn}" and my course info is checked') def impl(context, entered_crn): context.response = nav.validCourseInfo(crn=entered_crn, subj="", crse="") context.expected_errors = "" @then('I will see "{error_message}"')
class RobotController: model_xml = '/home/student/ssd300.xml' model_bin = '/home/student/ssd300.bin' 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() def remote_move(self, direction): self.navigator.remote_move(direction) def run_event(self, event): if self.standby_mode and len(self.actions.keys()) == 0: self.set_standby(False, justMove=True) for action in event.actions: pid = action["plant_id"] if pid not in self.actions: self.actions[pid] = [] self.actions[pid].append(action["name"]) def thread_remote(self): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) self.sched = Scheduler() self.sched.run_event_cb = self.run_event loop.run_until_complete(self.remote.connect()) def enabled(self): return len(self.actions) > 0 or not self.standby_mode def clean_actions(self): new_actions = {} for key in self.actions: if self.actions[key] != []: new_actions[key] = self.actions[key] self.actions = new_actions def process_visual_data(self, predictions, frame): """ Forwards messages to navigator instance. :param predictions: List of predictions produced by the VPU :return: """ # If the standby is currently undergoing, but standby mode is False, stop standby mode here if self.standby_invoked and not self.standby_mode: self.standby_invoked = False self.random_search_mode = True self.navigator.remote_motor_controller.random() self.standby_invoked = False # If the sensor's last read time is long enough (1 hour), attempt to read the sensor if time.time( ) - self.serial_io.sensor_last_read > 3600 and not self.serial_io.value_reading: threading.Thread(name="serial_read", target=self.serial_io.read_value).start() if self.enabled(): log.info("self.actions: {}, standby_mode: {}".format( self.actions, self.standby_mode)) self.clean_actions() self.received_frame = frame self.navigator.on_new_frame(predictions) else: if self.standby_mode: log.info("\033[0;34m[Pi] Standby mode flag detected") if not self.approach_complete: log.info( "\033[1;37;44m[Pi] Robot approaching, ignoring flag") elif self.retrying_approach: log.info( "\033[1;37;44m[Pi] Robot retrying approach, ignoring flag" ) else: if not self.standby_invoked: self.navigator.remote_motor_controller.stop() log.info("\033[1;37;44m[Pi] Invoking standby mode") # Any other switches to flip? # Reset read QR codes self.current_qr_approached = None self.last_qr_approached = None # Stop the motor self.standby_invoked = True elif len(self.actions) == 0: log.info("\033[0;34m[Pi] Robot has no event left to complete") # Stop immediately? Wait until the jobs to finish to stop? def read_qr_code(self): # Read the QR code tries = 3 qr_codes = self.qr_reader.identify(self.received_frame) while tries > 0: if len(qr_codes) == 0: log.warning("No plant QR found.") tries -= 1 else: for qr in qr_codes: self.current_qr_approached = qr log.info("Plant QR found: {}".format(qr)) break def on_plant_found(self): # Send message to initiate approach command, until instructed to continue if self.current_qr_approached is None: log.warning("No QR found, retrying approach") self.retrying_approach = True self.navigator.remote_motor_controller.retry_approach() elif self.current_qr_approached.startswith("gbpl:"): # Parse the QR plant_id = int(self.current_qr_approached[5:]) if not self.standby_invoked: # If robot is not in standby mode, go forward anyways self.approach_complete = False self.navigator.remote_motor_controller.approached() elif plant_id in self.actions: if len(self.actions[plant_id]) == 0: log.info( "Plant {} has no task left to complete, leaving...". format(str(plant_id))) self.last_qr_approached = self.current_qr_approached self.current_qr_approached = None self.navigator.remote_motor_controller.approach_escape() else: self.approach_complete = False if "PLANT_WATER" in self.actions[ plant_id] or not self.standby_invoked: self.navigator.remote_motor_controller.approached() else: self.navigator.remote_motor_controller.approached( raise_arm=False) else: log.info("Plant {} has no task assigned, leaving...".format( str(plant_id))) self.last_qr_approached = self.current_qr_approached self.current_qr_approached = None self.navigator.remote_motor_controller.approach_escape() else: log.warning("Invalid QR code {}".format( self.current_qr_approached)) self.last_qr_approached = self.current_qr_approached self.current_qr_approached = None self.navigator.remote_motor_controller.approach_escape() def on_approach_complete(self): # Take a picture here plant_id = None if self.current_qr_approached is not None: if self.current_qr_approached.startswith("gbpl:"): plant_id = int(self.current_qr_approached[5:]) if "PLANT_CAPTURE_PHOTO" in self.actions.get( plant_id, []) or not self.standby_invoked: self.remote.plant_capture_photo( int(self.current_qr_approached[5:]), base64.b64encode( cv2.imencode( ".jpg", self.received_frame)[1]).decode("utf-8")) else: log.warning( "[Pi] No QR code found during this approach, photo will not be sent." ) self.last_qr_approached = self.current_qr_approached self.current_qr_approached = None try: if plant_id is not None: if self.watered: self.actions[plant_id].remove("PLANT_WATER") self.watered = False if self.actions[plant_id] == []: self.actions.pop(plant_id, None) self.actions[plant_id].remove("PLANT_CAPTURE_PHOTO") except: pass finally: self.navigator.remote_motor_controller.approach_escape() def on_approach_escape_complete(self): self.navigator.random_search_mode = True # Flip on the random search self.navigator.remote_motor_controller.random_walk() self.clean_actions() self.approach_complete = True def on_retry_complete(self): self.retrying_approach = False self.navigator.approach_frame_counter = 8 def on_plant_seen(self): pass def on_events_received(self, data): events = list(map(Event.from_dict, data)) non_ephemeral = [] for e in events: if e.ephemeral: self.run_event(e) else: non_ephemeral.append(e) self.sched.push_events(non_ephemeral) pass def set_standby(self, mode, justMove=False): if mode: self.standby_mode = True while not hasattr(self, "navigator"): pass self.navigator.remote_motor_controller.stop() return while not hasattr(self, "navigator"): pass # Start random search self.navigator.random_search_mode = True self.navigator.remote_motor_controller.random_walk() if not justMove: # Turn off standby mode self.standby_mode = False def get_state(self): if self.standby_mode: return "Standby Mode" elif self.retrying_approach: return "Retrying approach" elif self.navigator.get_random_search_mode(): return "Random Search Mode" elif self.navigator.get_follow_mode(): return "Follow Mode" elif self.navigator.get_escape_mode(): return "Escape Mode"
#send heartbeat email every time program runs heartbeat = True if delayStartup: delay = random.randint(60,690) #delay between 1 minute and 16 minutes print 'Delaying program: ' + str(delay/60) + ' minutes' time.sleep(delay) browser = webdriver.Firefox() nav = Navigator(browser) parser = WebParser(browser) manager = CourseManager(browser,nav, parser) schedParser = ScheduleParser() notify = EmailNotifier(sender,sender_pass) #if True: try: #parse schedule file schedParser.parseFile(schedule) courseList = schedParser.getCourseList() schedules = schedParser.getSchedules()
from PathHandler import PathHandler from Navigator import Navigator # Settings maxSpeed = 0.5 lookAheadDistance = 0.8 lookAheadSwitchDistance = 0.5 maxTurnRate = 1.2 damperLength = 5 #### Intialize robot = Robot() p = Path("Path-around-table-and-back.json") path = p.getPath() pathHandler = PathHandler() navigator = Navigator(maxSpeed, maxTurnRate, damperLength) robot.setMotion(0, 0) position = robot.getPosition() heading = 0 nextPoint = 0 while (navigator.notGoal(position, nextPoint, path)): ### get current status (position, heading) position = robot.getPosition() heading = navigator.convertToDegree(robot.getHeading()) ### get next point nextPoint = pathHandler.getNextPathPoint(position, path, nextPoint, lookAheadDistance, lookAheadSwitchDistance)
# load a path file #p = Path("Path-around-table.json") p = Path("Path-around-table-and-back.json") #p = Path("Path-from-bed.json") #p = Path("Path-to-bed.json") path = p.getPath() print("Path length = " + str(len(path))) print("First point = " + str(path[0]['X']) + ", " + str(path[0]['Y'])) # make a robot to move around robot = Robot() converter = AngleConverter() pathHandler = PathHandler() navigator = Navigator() goal = Goal() #### Intialize variables position = robot.getPosition() speed = 0.25 heading = 0 nextPoint = 0 dropOut = 0 lookAheadDistance = 0.85 while (goal.notGoal(position, nextPoint, path)): ### get current status (position, heading) position = robot.getPosition() heading = converter.convertToDegree(robot.getHeading())
class MyStrategy: SPEED_HEAP_SIZE = 20 GO_BACK_CD = 100 DEBUG_LR = False def __init__(self): self.tmp = None self.navigator = None self.physics = None self.mycar = None self.go_back_cd = MyStrategy.GO_BACK_CD # need to get positive speed at least 0.75 self.go_back = 0 self.driving_direction_vector = None self.debug = None self.speed_limit_before_turn = None if MyStrategy.DEBUG_LR: try: from debug.debug_client import DebugClient from debug.debug_client import Color except ImportError: pass else: self.debug = DebugClient() self.green = Color(r=0.0, g=1.0, b=0.0) def preproc(self, world, game): print 'world %d x %d' % (world.width, world.height) pprint(map(list, zip(*world.tiles_x_y))) print world.waypoints print '=====================' self.navigator = Navigator(world) self.physics = Physics(world, game) def update(self, me, world, game): if world.tick == 0: self.preproc(world, game) self.mycar = MyCar(me, game.track_tile_size) self.navigator.update_state(self.mycar) if world.tick == 0: pprint(self.navigator.path) print "car.width %d, car.height: %d" % (me.width, me.height) print 'Tick[%d] TILE%s P(%.16f, %.16f)' % ( world.tick, str( self.mycar.cur_tile), self.mycar.base.x, self.mycar.base.y) # print 'Nitro:', me.nitro_charge_count self.driving_direction_vector = tuple( get_vector_by_direction( self.navigator.path[self.navigator.cur_path_idx].direction)) self.speed_limit_before_turn = 23 if self.navigator.ladder_end_point is not None: self.speed_limit_before_turn = 21 if self.navigator.is_turn_180_grad: self.speed_limit_before_turn = 21 # Doesn't make sens. TODO calculate and store in navigator next turn Type def move(self, me, world, game, move): """ @type me: Car @type world: World @type game: Game @type move: Move """ ################## if len(world.players) == 2: print '2x2 Game. Do nothing.' return if me.finished_track: return self.update(me, world, game) anchor_point = self.navigator.get_anchor_point(self.mycar, world, game) is_turning_started = self.navigator.is_turning_started ################## next_turn_idx, dist_to_next_turn = self.navigator.find_next_turn() if self.navigator.anchor_angle is not None and self.mycar.speed > 10.0: angle_to_anchor_point = self.navigator.anchor_angle else: angle_to_anchor_point = me.get_angle_to(anchor_point[0], anchor_point[1]) if self.navigator.bonus_anchor_point is not None: angle_to_anchor_point = me.get_angle_to( self.navigator.bonus_anchor_point[0], self.navigator.bonus_anchor_point[1]) distance_to_anchor_point = me.get_distance_to(anchor_point[0], anchor_point[1]) if self.tmp != me.next_waypoint_index: self.tmp = me.next_waypoint_index print "NEW_WP:", (me.next_waypoint_x, me.next_waypoint_y) print 'V(%.16f, %.16f) V_HYP(%.16f)' % (me.speed_x, me.speed_y, self.mycar.speed) print 'ANG(%.16f) ANG_V(%.16f)' % (me.angle, self.mycar.base.angular_speed) print 'EP(%.16f) WT(%.16f)' % (me.engine_power, me.wheel_turn) print 'ANCH_ANG(%.5f) ANCH_DIST(%.5f)' % (angle_to_anchor_point, distance_to_anchor_point) print 'PRJCT(%d)' % (me.projectile_count) print 'next Anchor:', anchor_point print 'is_on_long_ladder:', self.navigator.is_on_long_ladder if self.debug: self.debug.use_tile_coords(False) with self.debug.post() as dbg: dbg.circle(anchor_point[0], anchor_point[1], 25.0, self.green) dbg.text(me.x, me.y, '%.2f' % self.mycar.speed, (0.0, 0.0, 0.0)) next_wp_tile = world.waypoints[me.next_waypoint_index] next_wp_pos = ((next_wp_tile[0] + 0.5) * game.track_tile_size, (next_wp_tile[1] + 0.5) * game.track_tile_size) dbg.fill_circle(next_wp_pos[0], next_wp_pos[1], 30, (1.0, 0.0, 0.0)) if self.navigator.anchor_angle is not None: vec = np.array([ sin(me.angle - angle_to_anchor_point), cos(me.angle - angle_to_anchor_point) ]) point = np.array([me.x, me.y]) + vec * 200.0 dbg.line(me.x, me.y, point[0], point[1], (1.0, 0.0, 0.0)) if self.go_back: self.go_back -= 1 move.wheel_turn = 0 move.engine_power = -1.0 if self.go_back > 10: move.wheel_turn = -sign(angle_to_anchor_point) return else: self.go_back_cd = max(0, self.go_back_cd - 1) if ((self.navigator.is_turning_started or self.navigator.is_turn_180_grad) and \ world.tick <= game.initial_freeze_duration_ticks + 50) or \ (self.mycar.speed >= 0 and world.tick > game.initial_freeze_duration_ticks + 50): if self.navigator.is_turn_180_grad: move.wheel_turn = sign(angle_to_anchor_point) else: move.wheel_turn = (angle_to_anchor_point * 32.0 / pi) move.engine_power = 1.0 move.use_nitro = self.should_use_nitro(me, world, game, distance_to_anchor_point, angle_to_anchor_point) if not self.go_back_cd and world.tick > game.initial_freeze_duration_ticks + 100 and abs( self.mycar.speed) < 0.12: self.go_back = 90 self.go_back_cd = MyStrategy.GO_BACK_CD print 'Start go BACK' if not is_turning_started and abs( angle_to_anchor_point ) > pi * 3.0 / 18.0 and abs( self.mycar.speed) * abs(angle_to_anchor_point) > 12 * pi / 4: move.brake = True # ((1.6 + (self.mycar.speed - speed_limit_before_turn) / 10) * game.track_tile_size) \ car_state = CarState.from_car(me) car_state.engine_power_lim = move.engine_power car_state.brake = False # TODO find out when ladder ends to start braking if not is_turning_started and (not self.navigator.is_on_turn or self.navigator.ladder_end_point is not None) and \ self.mycar.speed > self.speed_limit_before_turn: tmp1, braking_dist, tmp2 = self.physics.calc_brake_distance( car_state, self.speed_limit_before_turn) print 'braking_dst(%.5f)' % braking_dist if self.navigator.ladder_end_point is not None: dist = me.get_distance_to(self.navigator.ladder_end_point[0], self.navigator.ladder_end_point[1]) move.brake = 100 < dist <= game.track_tile_size + braking_dist elif self.navigator.PRETURN_DISTANCE < distance_to_anchor_point <= self.navigator.PRETURN_DISTANCE + braking_dist: move.brake = True move.throw_projectile = Shooter.should_shoot(self.mycar, world, game) if move.throw_projectile: print 'SHOOT--->' move.spill_oil = self.should_spill_oil(me, world, game) print move_to_str(move) ######################################################################################################################## def should_spill_oil(self, me, world, game): if me.oil_canister_count == 0 or self.mycar.speed < 2.0: return False OIL_SLICK_RADIUS = 150 if self.navigator.is_turning_started and world.tick > game.initial_freeze_duration_ticks + 385: lower_dist = max(me.width, me.height) + 10 + OIL_SLICK_RADIUS / 5.0 for car in world.cars: if not car.teammate and lower_dist < me.get_distance_to_unit(car) < game.track_tile_size * 8.0 \ and abs(me.get_angle_to_unit(car)) > pi / 2: print 'SPILL_OIL: anlg_to_car({}), dist({})'.format(me.get_angle_to_unit(car),\ me.get_distance_to_unit(car)) return True return False def get_increased_cp_idx(self, cp_index): return cp_index + 1 if cp_index + 1 < len(self.check_points) else 0 def should_use_nitro(self, me, world, game, distance_to_anchor_point, angle_to_anchor_point): if me.nitro_charge_count == 0 or me.remaining_nitro_cooldown_ticks > 0: return False # if dist_to_next_turn is not None and world.tick > game.initial_freeze_duration_ticks and dist_to_next_turn > 2: # return True if (not self.navigator.is_on_turn or self.navigator.is_on_long_ladder) and not self.navigator.is_turning_started \ and me.angular_speed < 0.5 and world.tick > game.initial_freeze_duration_ticks: # TODO check that we haven't recently strayed from the path car_state = CarState.from_car(me) car_state.engine_power = game.nitro_engine_power_factor car_state.engine_power_lim = game.nitro_engine_power_factor car_state.brake = False dist_on_nitro, end_nitro_state = self.physics.simulate( car_state, game.nitro_duration_ticks) # TODO find accurate solution ticks_to_bake, braking_dist, tmp2 = self.physics.calc_brake_distance( car_state, self.speed_limit_before_turn) is_pretty_far_from_turn = dist_on_nitro * 0.95 <= ( distance_to_anchor_point - self.navigator.PRETURN_DISTANCE) if self.navigator.is_on_long_ladder: angle_delta = abs(angle_to_anchor_point) angle_threshold = pi / 72.0 else: angle_delta = abs( acos( sum( map(lambda a, b: a * b, self.driving_direction_vector, self.mycar.direction_vector)))) angle_threshold = pi / 18.0 if (is_pretty_far_from_turn or self.navigator.is_on_long_ladder) \ and angle_delta < angle_threshold and me.remaining_oiled_ticks == 0: return True return False
from behave import given, when, then from Navigator import Navigator nav = Navigator() @given('I have Python {version} installed') def impl(context, version): version = version.split(".") # Create a list from the string context.version = version # Save the list @when('I try to check my version') def impl(context): context.actual = str( nav.checkVersion(*context.version)) # Unpack the list arguments @then('I should see "{expected}" in my message') def impl(context, expected): try: if (expected == "Nothing"): assert "" in context.actual # We aren't expecting anything else: assert expected in context.actual except AssertionError as e: e.args += ('Expected: ' + expected + ' Actual: ' + context.actual) raise e.args
def __init__(self, root, dim=None, appName='BreadInterface'): # init the app components # self.settings = Settings(appName) self.navigator = Navigator(root, dim) self.appName = appName
map['x'] = map_x map['y'] = map_y nav_bot_name = str(input("Nav bot name: ")) nav_bot_x = int(input("Nav bot x coordinate: ")) nav_bot_y = int(input("Nav bot y coordinate: ")) nav_bot_dir = str(input("Nav bot direction: ")) nav_bot_inst = str(input("Nav bot movement: ")) fight_bot_name = str(input("Fight bot name: ")) fight_bot_x = int(input("Fight bot x coordinate: ")) fight_bot_y = int(input("Fight bot y coordinate: ")) fight_bot_dir = str(input("Fight bot direction: ")) fight_bot_inst = str(input("Fight bot movement: ")) nav_bot = Navigator(nav_bot_name, nav_bot_x, nav_bot_y, Direction[nav_bot_dir]) for m in [char for char in nav_bot_inst]: nav_bot.navigate() set_movement(m, nav_bot, map) nav_bot.reply("I am robot") fight_bot = Fighter(fight_bot_name, fight_bot_x, fight_bot_y, Direction[fight_bot_dir]) for m in [char for char in fight_bot_inst]: fight_bot.fight() set_movement(m, fight_bot, map) fight_bot.reply() tokota_bot = Tokota("XT009", 0, 0, Direction.N) print(nav_bot.get_x()) print(nav_bot.get_y())
for key,val in coordinates.iteritems(): if key == None: continue coordinates[key] = (val[0]-start[0],val[1]-start[1]) return coordinates init("/dev/tty.Fluke2-07EE-Fluke2") # parser = Parser("CS3630_Lab2_Map1.csv") # parser = Parser("CS3630_Lab2_Map2.csv") parser = Parser("CS3630_Lab2_Map3.csv") graph = Graph(parser.getVertexList1(),parser.getVertexList2()) print "Graph:" graph.printGraph() path = findPath(graph) print "Path:" print path print "Coordinates:" print parser.getCoordinates() c = parser.getCoordinates() relCoordinates = makeRel(c[path[0]], c) print "Rel coordinates" print relCoordinates print path nav = Navigator(path, relCoordinates) nav.execute()
def test_update_state(self): mock_world = MockWorld.create('map04') mock_game = MockGame() navigator = Navigator(mock_world) self.assertFalse(navigator.pathfinder is None) self.assertFalse(navigator.pathfinder.graph is None) self.assertEqual(len(navigator.pathfinder.graph), mock_world.height * mock_world.width) self.assertFalse(navigator.is_on_extra_path) mock_car = MockCar() mock_car.x = 10800 mock_car.y = 12400 mock_car.next_waypoint_index = 1 car = MyCar(mock_car, mock_game.track_tile_size) navigator.update_state(car) anchor_point = navigator.get_anchor_point(car, mock_world, mock_game) self.assertEqual(anchor_point, (600.0, 12600.0)) self.assertEqual(navigator._prev_path_tile_idx, 0) self.assertFalse(navigator.is_on_extra_path) mock_car.x = 10000 mock_car.y = 12400 mock_car.next_waypoint_index = 1 car = MyCar(mock_car, mock_game.track_tile_size) navigator.update_state(car) self.assertEqual(navigator._prev_path_tile_idx, 1) self.assertFalse(navigator.is_on_extra_path) mock_car.x = 9200 mock_car.y = 12400 mock_car.next_waypoint_index = 1 car = MyCar(mock_car, mock_game.track_tile_size) navigator.update_state(car) self.assertEqual(navigator._prev_path_tile_idx, 2) self.assertFalse(navigator.is_on_extra_path) mock_car.x = 2000 mock_car.y = 12400 mock_car.next_waypoint_index = 1 car = MyCar(mock_car, mock_game.track_tile_size) navigator.update_state(car) self.assertEqual(navigator._prev_path_tile_idx, 11) self.assertFalse(navigator.is_on_extra_path) mock_car.x = 1200 mock_car.y = 12400 mock_car.next_waypoint_index = 2 car = MyCar(mock_car, mock_game.track_tile_size) self.assertEqual(car.cur_tile, (1, 15)) navigator.update_state(car) self.assertFalse(navigator.is_on_extra_path) self.assertEqual(navigator._prev_path_tile_idx, 12) mock_car.x = 1200 mock_car.y = 11600 mock_car.next_waypoint_index = 2 car = MyCar(mock_car, mock_game.track_tile_size) self.assertEqual(car.cur_tile, (1, 14)) navigator.update_state(car) self.assertTrue(navigator.is_on_extra_path) self.assertEqual(navigator._prev_path_tile_idx, 13)
class SPMBrowser(): def __init__(self): # Definiton of the variables self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.path_selected = None self.navi = Navigator(self.window) self.info = Infor(self.window) self.oper = Operator(self.window) self.gwydata = GwyData() self.img_1 = Imager(self.window,400) self.img_2 = Imager(self.window,400) self.channel_img_1 = None self.channel_img_2 = None # Definition of the widget self.window.connect("destroy", lambda w: gtk.main_quit()) self.window.set_title("SPMBrowser") # vbox_main self.vbox_main = gtk.VBox(False,0) # hbox_main self.hbox_main = gtk.HBox(False,0) self.vbox_2 = gtk.VBox(False,0) self.hbox_main.pack_start(self.img_1.vbox_main,1,1,0) self.hbox_main.pack_start(self.img_2.vbox_main,1,1,0) self.vbox_2.pack_start(self.info.table_info,0,1,0) self.vbox_2.pack_end(self.oper.vbox_main,0,1,0) self.hbox_main.pack_end(self.vbox_2,0,1,0) # pack self.vbox_main.pack_start(self.navi.vbox_main,0,1,0) self.vbox_main.pack_start(self.hbox_main,0,1,0) self.window.add(self.vbox_main) self.window.show_all() # Signal handling self.navi.combobox_files.connect('changed',self.update_all,None) self.img_1.combobox_channels.connect('changed',self.record_channels,None) self.img_2.combobox_channels.connect('changed',self.record_channels,None) #self.info.entry_ratio.connect('changed',self.update_info,None) self.window.connect('key_press_event',self._key_press_event) def update_all(self,widget,data): self.current_data = self.navi.get_full_path() if self.current_data: self.gwydata.load_data(self.current_data) self.info.initialize(widget,self.gwydata.param) #print self.gwydata.param['channels'] self.img_1.initialize(self.gwydata,self.channel_img_1) self.img_2.initialize(self.gwydata,self.channel_img_2) self.oper.get_current_data(self.gwydata.get_container(),self.gwydata.get_param(),self.navi.get_path2save(),'Z') def record_channels(self,widget,data): self.gwydata.param['im_1_channel'] = self.img_1.channel_id self.gwydata.param['im_2_channel'] = self.img_2.channel_id self.channel_img_1 = self.img_1.get_active_channel() self.channel_img_2 = self.img_2.get_active_channel() self.oper.get_current_data(self.gwydata.get_container(),self.gwydata.get_param(),self.navi.path2save,'Z') #print self.navi.path2save def update_info(self,widget,data): self.info.update() def _key_press_event(self,widget,data): keyval = data.keyval #print keyval if keyval == 110: active = self.navi.combobox_files.get_active() if active >= 0: self.navi.go_forward(widget,data) if keyval == 98: active = self.navi.combobox_files.get_active() if active >= 0: self.navi.go_backward(widget,data)
from selenium import webdriver from Navigator import Navigator from Course import Course from CourseManager import CourseManager from WebParser import WebParser from ScheduleParser import ScheduleParser, Schedule import sys browser = webdriver.Firefox() nav = Navigator(browser) parser = WebParser(browser) manager = CourseManager(browser,nav, parser) schedParser = ScheduleParser() #parse schedule file schedParser.parseFile('Spring2015.scd') courseList = schedParser.getCourseList() schedules = schedParser.getSchedules() #Login to access plus nav.bypassLogin('student_id','student_pass', '0001qV1sH8ILGpkqibRr42x47tc:14a0b94d8') nav.gotoClassRegistration('ran_num') #check the status of the current schedule baseSchedule = manager.checkCurrentSchedule()
from selenium import webdriver from Navigator import Navigator from Course import Course from WebParser import WebParser browser = webdriver.Firefox() nav = Navigator(browser) parser = WebParser(browser) nav.bypassLogin('student_id','student_pass', '0001qV1sH8ILGpkqibRr42x47tc:14a0b94d8') nav.gotoClassRegistration('ran_num') cpre = Course('CPR E', '288', 'B') coms = Course('COM S', '309') nav.gotoCourseAvailability(cpre) nav.showNext20() nav.showNext20() nav.gotoClassRegistration() cpreStatus = parser.parsePageCourses() for cr in cpreStatus: print cr
from Navigator import Navigator if __name__ == '__main__': navigator = Navigator()
def __init__( self, root, dim=None, appName='BreadInterface' ): # init the app components # self.settings = Settings(appName) self.navigator = Navigator( root, dim ) self.appName = appName
if angle_new_sin < 0: angle_new = 2 * pi - angle_new_cos else: angle_new = angle_new_cos theta = angle_new - angle_old print('theta', theta) # calculate linear velocity linear_velocity = distances[ i] / self.time_step * self.converting_factor # calculate angular velocity angular_velocity = theta / self.time_step # add to commands commands.append(angular_velocity) commands.append(linear_velocity) # update old direction old_direction = new_direction return commands if __name__ == '__main__': nav = Navigator() coordinates = nav.actualAStar((300, 290), (575, 215), "markdown_files/library_lower.png") robot = Path_To_Velocity(coordinates, 6) robot.get_velocity_commands(10)
""" For testing the turning of the robot, not actually used. Turns the robot one full rotation. """ output = Twist() output.linear = Vector3(0, 0, 0) output.angular = Vector3(0, 0, 1.0) self.velpub.publish(output) r = rospy.Rate(10) r.sleep() now = rospy.get_time() while (now + 6.28 > rospy.get_time()) and (not rospy.is_shutdown()): self.velpub.publish(output) r.sleep() output = Twist() output.linear = Vector3(0, 0, 0) output.angular = Vector3(0, 0, 0) self.velpub.publish(output) if __name__ == '__main__': nav = Navigator() coordinates = nav.actualAStar( (500, 1050), (434, 918), "Maps/collected_maps_stage/cc3.png") # get the path Converter = Path_To_Velocity(coordinates, 1) commands = Converter.get_velocity_commands( 10) # convert the path to velocities turtle1 = Turtlebot() turtle1.publishVelocities(commands) # publish the velocities to the robot.