def take_picture(channel): lcd.lcd_clear() camera.start_preview() camera.annotate_text_size = 150 for i in range(5): camera.annotate_text = "Ready %d" % (5-i) output_lcd("#### READY! ####", " %d" % (5-i)) MY_CYCLE = colorschemes.RoundAndRound(num_led=NUM_LED, pause_value=1/NUM_LED, num_steps_per_cycle=NUM_LED, num_cycles=1) MY_CYCLE.start() # sleep(1) thread1 = flash.Flash(2,70) thread1.start() output_lcd("##### SMIL! #####", "################") camera.annotate_text = "" filename = '/home/pi/Desktop/capture.jpg' camera.capture(filename) camera.stop_preview() output_lcd(" Uploader... ", "-!-!-!-!-!-!-!-!") res = upload(filename) if res: output_lcd(" Billede klar!", "---------------") else: output_lcd("!!!!! FEJL !!!!!", "!!!!!!!!!!!!!!!!") sleep(2) output_lcd(" - Photobooth - ", "Tryk pa knappen")
def _create_ftl(self): if self.conf['ftl_type'] == 'dftldes': return dftldes.Ftl(self.conf, self.recorder, self.flash_controller, self.env) elif self.conf['ftl_type'] == 'nkftl2': print 'we will use nkftl2' simpleflash = flash.Flash(recorder=self.recorder, confobj=self.conf) return nkftl2.Ftl(self.conf, self.recorder, simpleflash, self.env, self.flash_controller)
def main(): led_flash = flash.Flash() led_flash.on() print('Initializing camera') with picamera.PiCamera() as camera: camera.resolution = (WIDTH, HEIGHT) camera.framerate = FRAMERATE sleep(1) # camera warm-up time print('Initializing websockets server on port %d' % WS_PORT) websocket_server = make_server( '', WS_PORT, server_class=WSGIServer, handler_class=WebSocketWSGIRequestHandler, app=WebSocketWSGIApplication(handler_cls=StreamingWebSocket)) websocket_server.initialize_websockets_manager() websocket_thread = Thread(target=websocket_server.serve_forever) print('Initializing HTTP server on port %d' % HTTP_PORT) output = BroadcastOutput(camera) http_server = StreamingHttpServer(camera, output, led_flash) http_thread = Thread(target=http_server.serve_forever) print('Initializing broadcast thread') broadcast_thread = BroadcastThread(output.converter, websocket_server) print('Starting recording') #camera.start_recording(output, 'yuv') try: print('Starting websockets thread') websocket_thread.start() print('Starting HTTP server thread') http_thread.start() print('Starting broadcast thread') broadcast_thread.start() while True: #camera.wait_recording(1) pass except KeyboardInterrupt: pass finally: print('Turning off flash') led_flash.off() print('Stopping recording') camera.stop_recording() print('Waiting for broadcast thread to finish') broadcast_thread.join() print('Shutting down HTTP server') http_server.shutdown() print('Shutting down websockets server') websocket_server.shutdown() print('Waiting for HTTP server thread to finish') http_thread.join() print('Waiting for websockets thread to finish') websocket_thread.join()
def main(): """ Get configuration, get driver, and build handler and start it. """ args = get_args() port = args.port[0] baud = args.baud[0] use_ftdi = args.ftdi use_m25 = args.m25 use_stm = args.stm erase = args.erase # Driver with context with serial_link.get_driver(use_ftdi, port, baud) as driver: # Handler with context with Handler(driver.read, driver.write) as link: link.start() link.send(SBP_MSG_RESET, "") time.sleep(0.2) link.add_callback(serial_link.printer, SBP_MSG_PRINT) # Tell Bootloader we want to write to the flash. with Bootloader(link) as piksi_bootloader: print "Waiting for bootloader handshake message from Piksi ...", sys.stdout.flush() try: piksi_bootloader.wait_for_handshake() except KeyboardInterrupt: return piksi_bootloader.reply_handshake() print "received." print "Piksi Onboard Bootloader Version:", piksi_bootloader.version # Catch all other errors and exit cleanly. try: import flash with flash.Flash(link, flash_type=("STM" if use_stm else "M25")) as piksi_flash: if erase: for s in range(1, 12): print "\rErasing STM Sector", s, sys.stdout.flush() piksi_flash.erase_sector(s) print from intelhex import IntelHex ihx = IntelHex(args.file) piksi_flash.write_ihx(ihx, sys.stdout, mod_print=0x10) print "Bootloader jumping to application" piksi_bootloader.jump_to_app() except: import traceback traceback.print_exc()
def __init__(self, conf, event_iter): super(SimulatorNonDES, self).__init__(conf, event_iter) if self.conf['ftl_type'] == 'dftlext': ftl_class = dftlext.Dftl elif self.conf['ftl_type'] == 'nkftl2': ftl_class = nkftl2.Ftl elif self.conf['ftl_type'] == 'ftlcounter': ftl_class = ftlcounter.Ftl else: raise ValueError("ftl_type {} is not defined"\ .format(self.conf['ftl_type'])) self.ftl = ftl_class( self.conf, self.recorder, flash.Flash(recorder=self.recorder, confobj=self.conf))
def update_firmware(self, ihx, flash_type): # Reset device if the application is running to put into bootloader mode. self.link.send_message(ids.RESET, '') self.write("\n") piksi_bootloader = bootload.Bootloader(self.link) self.write("Waiting for bootloader handshake message from Piksi ...\n") piksi_bootloader.wait_for_handshake() piksi_bootloader.reply_handshake() self.write("received bootloader handshake message.\n") self.write("Piksi Onboard Bootloader Version: " + piksi_bootloader.version + "\n") piksi_flash = flash.Flash(self.link, flash_type) piksi_flash.write_ihx(ihx, self.output, mod_print = 0x10) piksi_flash.stop() piksi_bootloader.stop() self.write("\n")
def __init__(self, port=serial_link.DEFAULT_PORT): self.console_output = OutputStream() self.link = serial_link.SerialLink(port) self.link.add_callback(serial_link.MSG_PRINT, self.print_message_callback) self.tracking_view = TrackingView(self.link) self.almanac_view = AlmanacView(self.link) self.solution_view = SolutionView(self.link) self.flash = flash.Flash(self.link) self.flash.start() self.python_console_env = { 'send_message': self.link.send_message, 'link': self.link, 'flash': self.flash } self.python_console_env.update(self.tracking_view.python_console_cmds) self.python_console_env.update(self.almanac_view.python_console_cmds) self.python_console_env.update(self.solution_view.python_console_cmds)
def create_flash(self, flash_type): # Reset device if the application is running to put into bootloader mode. self.link.send_message(ids.RESET, '') self.pk_boot = bootload.Bootloader(self.link) self._write("Waiting for bootloader handshake message from Piksi ...") reset_prompt = None handshake_received = self.pk_boot.wait_for_handshake(1) # Prompt user to reset Piksi if we don't receive the handshake message # within a reasonable amount of tiime (firmware might be corrupted). while not handshake_received: reset_prompt = \ prompt.CallbackPrompt( title="Please Reset Piksi", actions=[prompt.close_button], ) reset_prompt.text = \ "You must press the reset button on your Piksi in order\n" + \ "to update your firmware.\n\n" + \ "Please press it now.\n\n" reset_prompt.run(block=False) while not reset_prompt.closed and not handshake_received: handshake_received = self.pk_boot.wait_for_handshake(1) reset_prompt.kill() reset_prompt.wait() self.pk_boot.reply_handshake() self._write("received bootloader handshake message.") self._write("Piksi Onboard Bootloader Version: " + self.pk_boot.version) self.pk_flash = flash.Flash(self.link, flash_type)
def drawKeyFlash(self, key): self.flashImg = pygame.Surface((70, 70)) self.flashImg.fill(colors.white) self.keyFlash = flash.Flash(self.flashDict[key], 30, 15) (x, y) = self.flashDict[key]
# Tell Bootloader we want to change flash data piksi_bootloader = Bootloader(link) print "Waiting for bootloader handshake message from Piksi ...", sys.stdout.flush() try: piksi_bootloader.wait_for_handshake() except KeyboardInterrupt: # Clean up and exit link.close() sys.exit() piksi_bootloader.reply_handshake() print "received." print "Piksi Onboard Bootloader Version:", piksi_bootloader.version if args.stm: piksi_flash = flash.Flash(link, flash_type="STM") elif args.m25: piksi_flash = flash.Flash(link, flash_type="M25") piksi_flash.write_ihx(ihx, sys.stdout, mod_print=0x10) print "Bootloader jumping to application" piksi_bootloader.jump_to_app() piksi_flash.stop() piksi_bootloader.stop() # Wait for ctrl+C until we exit try: while (1): time.sleep(0.5)
def __init__(self, cookie_path=DEFAULT_COOKIE_PATH, cookie_name=COOKIE_NAME, session_expire_time=SESSION_EXPIRE_TIME, clean_check_percent=CLEAN_CHECK_PERCENT, integrate_flash=INTEGRATE_FLASH, check_ip=CHECK_IP, check_user_agent=CHECK_USER_AGENT, set_cookie_expires=SET_COOKIE_EXPIRES, session_token_ttl=SESSION_TOKEN_TTL): """ Initializer Args: cookie_name: The name for the session cookie stored in the browser. session_expire_time: The amount of time between requests before the session expires. clean_check_percent: The percentage of requests the will fire off a cleaning routine that deletes stale session data. integrate_flash: If appengine-utilities flash utility should be integrated into the session object. check_ip: If browser IP should be used for session validation check_user_agent: If the browser user agent should be used for sessoin validation. set_cookie_expires: True adds an expires field to the cookie so it saves even if the browser is closed. session_token_ttl: Number of sessions a session token is valid for before it should be regenerated. """ self.cookie_path = cookie_path self.cookie_name = cookie_name self.session_expire_time = session_expire_time self.clean_check_percent = clean_check_percent self.integrate_flash = integrate_flash self.check_user_agent = check_user_agent self.check_ip = check_ip self.set_cookie_expires = set_cookie_expires self.session_token_ttl = session_token_ttl """ Check the cookie and, if necessary, create a new one. """ self.cache = {} self.sid = None string_cookie = os.environ.get('HTTP_COOKIE', '') self.cookie = Cookie.SimpleCookie() self.cookie.load(string_cookie) # check for existing cookie if self.cookie.get(cookie_name): self.sid = self.cookie[cookie_name].value # If there isn't a valid session for the cookie sid, # start a new session. self.session = self._get_session() if self.session is None: self.sid = self.new_sid() self.session = _AppEngineUtilities_Session() self.session.ua = os.environ['HTTP_USER_AGENT'] self.session.ip = os.environ['REMOTE_ADDR'] self.session.sid = [self.sid] self.cookie[cookie_name] = self.sid self.cookie[cookie_name]['path'] = cookie_path if set_cookie_expires: self.cookie[cookie_name]['expires'] = \ self.session_expire_time else: # check the age of the token to determine if a new one # is required duration = datetime.timedelta(seconds=self.session_token_ttl) session_age_limit = datetime.datetime.now() - duration if self.session.last_activity < session_age_limit: self.sid = self.new_sid() if len(self.session.sid) > 2: self.session.sid.remove(self.session.sid[0]) self.session.sid.append(self.sid) else: self.sid = self.session.sid[-1] self.cookie[cookie_name] = self.sid self.cookie[cookie_name]['path'] = cookie_path if set_cookie_expires: self.cookie[cookie_name]['expires'] = \ self.session_expire_time else: self.sid = self.new_sid() self.session = _AppEngineUtilities_Session() self.session.ua = os.environ['HTTP_USER_AGENT'] self.session.ip = os.environ['REMOTE_ADDR'] self.session.sid = [self.sid] self.cookie[cookie_name] = self.sid self.cookie[cookie_name]['path'] = cookie_path if set_cookie_expires: self.cookie[cookie_name]['expires'] = self.session_expire_time self.cache['sid'] = pickle.dumps(self.sid) # update the last_activity field in the datastore every time that # the session is accessed. This also handles the write for all # session data above. self.session.put() print self.cookie # fire up a Flash object if integration is enabled if self.integrate_flash: import flash self.flash = flash.Flash(cookie=self.cookie) # randomly delete old stale sessions in the datastore (see # CLEAN_CHECK_PERCENT variable) if random.randint(1, 100) < CLEAN_CHECK_PERCENT: self._clean_old_sessions()
def __call__(self, f): # make sure the page is not cached in the browser print self.no_cache_headers() # cache object is used to store write items as the session is processed. # This avoids multiple calls to the datastore or cookie processing if # session variable has already been accessed. self.cache = {} # Check the cookie and, if necessary, create a new one. string_cookie = os.environ.get(u"HTTP_COOKIE", u"") self.cookie = Cookie.SimpleCookie() self.output_cookie = Cookie.SimpleCookie() if string_cookie == "": self.cookie_vals = {} else: self.cookie.load(string_cookie) try: self.cookie_vals = \ simplejson.loads(self.cookie["%s_data" % (self.cookie_name)].value) # sync self.cache and self.cookie_vals which will make those # values available for all gets immediately. for k in self.cookie_vals: self.cache[k] = self.cookie_vals[k] # sync the input cookie with the output cookie self.output_cookie["%s_data" % (self.cookie_name)] = \ simplejson.dumps(self.cookie_vals) #self.cookie["%s_data" % (self.cookie_name)] except Exception: self.cookie_vals = {} if self.writer == "cookie": pass else: # write_cache and del_cache are used for batch write operations # after the request has been processed for datastore sessions. # Objects may also exist in self.cache meaning the value is stored # in multiple locations in memory, however session data should be # small so this should not create much overhead in most use cases. self.write_cache = {} self.del_cache = [] self.sid = None new_session = True # do_put is used to determine if a datastore write should # happen on this request. do_put = False # check for existing cookie if self.cookie.get(cookie_name): self.sid = self.cookie[cookie_name].value # The following will return None if the sid has expired. self.session = _AppEngineUtilities_Session.get_session(self) if self.session: new_session = False if new_session: # start a new session self.session = _AppEngineUtilities_Session() self.session.put() self.sid = self.new_sid() if u"HTTP_USER_AGENT" in os.environ: self.session.ua = os.environ[u"HTTP_USER_AGENT"] else: self.session.ua = None if u"REMOTE_ADDR" in os.environ: self.session.ip = os.environ["REMOTE_ADDR"] else: self.session.ip = None self.session.sid = [self.sid] # do put() here to get the session key self.session.put() else: # check the age of the token to determine if a new one # is required duration = datetime.timedelta(seconds=self.session_token_ttl) session_age_limit = datetime.datetime.now() - duration if self.session.last_activity < session_age_limit: self.sid = self.new_sid() if len(self.session.sid) > 2: self.session.sid.remove(self.session.sid[0]) self.session.sid.append(self.sid) do_put = True else: self.sid = self.session.sid[-1] # check if last_activity needs updated ula = datetime.timedelta(seconds=self.last_activity_update) if datetime.datetime.now() > self.session.last_activity + \ ula: do_put = True self.output_cookie[cookie_name] = self.sid self.output_cookie[cookie_name]["path"] = self.cookie_path if self.cookie_domain: self.output_cookie[cookie_name]["domain"] = self.cookie_domain if self.set_cookie_expires: self.output_cookie[cookie_name]["expires"] = \ self.session_expire_time self.cache[u"sid"] = self.sid #TODO See if this write can deferred. Since the cookie token # is being set in the headers, it may not be the case. Need to # at lease validate self.put() still does this write once I # am done making changes. # # It's a result of the security created by rotating tokens that # requires this write on requests where the session token changes. if do_put: if self.sid != None or self.sid != u"": self.session.put() # Only set the "_data" cookie if there is actual data if self.output_cookie.has_key("%s_data" % (cookie_name)): # Set the path of the "_data" cookie self.output_cookie["%s_data" % (cookie_name)]["path"] = cookie_path if self.set_cookie_expires: self.output_cookie["%s_data" % (cookie_name)]["expires"] = \ self.session_expire_time print self.output_cookie.output() # fire up a Flash object if integration is enabled if self.integrate_flash: import flash self.flash = flash.Flash(cookie=self.cookie) # Run the request f.gaeusession = self f() # randomly delete old stale sessions in the datastore (see # CLEAN_CHECK_PERCENT variable) if random.randint(1, 100) < clean_check_percent: self._clean_old_sessions()
class Session(object): """ Sessions are used to maintain user presence between requests. Sessions can either be stored server side in the datastore/memcache, or be kept entirely as cookies. This is set either with the settings file or on initialization, using the writer argument/setting field. Valid values are "datastore" or "cookie". Session can be used as a standard dictionary object. session = appengine_utilities.sessions.Session() session["keyname"] = "value" # sets keyname to value print session["keyname"] # will print value Datastore Writer: The datastore writer was written with the focus being on security, reliability, and performance. In that order. It is based off of a session token system. All data is stored server side in the datastore and memcache. A token is given to the browser, and stored server side. Optionally (and on by default), user agent and ip checking is enabled. Tokens have a configurable time to live (TTL), which defaults to 5 seconds. The current token, plus the previous 2, are valid for any request. This is done in order to manage ajax enabled sites which may have more than on request happening at a time. This means any token is valid for 15 seconds. A request with a token who's TTL has passed will have a new token generated. In order to take advantage of the token system for an authentication system, you will want to tie sessions to accounts, and make sure only one session is valid for an account. You can do this by setting a db.ReferenceProperty(_AppEngineUtilities_Session) attribute on your user Model, and use the get_ds_entity() method on a valid session to populate it on login. Note that even with this complex system, sessions can still be hijacked and it will take the user logging in to retrieve the account. In the future an ssl only cookie option may be implemented for the datastore writer, which would further protect the session token from being sniffed, however it would be restricted to using cookies on the .appspot.com domain, and ssl requests are a finite resource. This is why such a thing is not currently implemented. Session data objects are stored in the datastore pickled, so any python object is valid for storage. Cookie Writer: Sessions using the cookie writer are stored entirely in the browser and no interaction with the datastore is required. This creates a drastic improvement in performance, but provides no security for session hijack. This is useful for requests where identity is not important, but you wish to keep state between requests. Information is stored in a json format, as pickled data from the server is unreliable. Note: There is no checksum validation of session data on this method, it's streamlined for pure performance. If you need to make sure data is not tampered with, use the datastore writer which stores the data server side. django-middleware: Included with the GAEUtilties project is a django-middleware.middleware.SessionMiddleware which can be included in your settings file. This uses the cookie writer for anonymous requests, and you can switch to the datastore writer on user login. This will require an extra set in your login process of calling request.session.save() once you validated the user information. This will convert the cookie writer based session to a datastore writer. """ # cookie name declaration for class methods COOKIE_NAME = settings.session["COOKIE_NAME"] def __init__(self, cookie_path=settings.session["DEFAULT_COOKIE_PATH"], cookie_domain=settings.session["DEFAULT_COOKIE_DOMAIN"], cookie_name=settings.session["COOKIE_NAME"], session_expire_time=settings.session["SESSION_EXPIRE_TIME"], clean_check_percent=settings.session["CLEAN_CHECK_PERCENT"], integrate_flash=settings.session["INTEGRATE_FLASH"], check_ip=settings.session["CHECK_IP"], check_user_agent=settings.session["CHECK_USER_AGENT"], set_cookie_expires=settings.session["SET_COOKIE_EXPIRES"], session_token_ttl=settings.session["SESSION_TOKEN_TTL"], last_activity_update=settings.session["UPDATE_LAST_ACTIVITY"], writer=settings.session["WRITER"]): """ Initializer Args: cookie_path: The path setting for the cookie. cookie_domain: The domain setting for the cookie. (Set to False to not use) cookie_name: The name for the session cookie stored in the browser. session_expire_time: The amount of time between requests before the session expires. clean_check_percent: The percentage of requests the will fire off a cleaning routine that deletes stale session data. integrate_flash: If appengine-utilities flash utility should be integrated into the session object. check_ip: If browser IP should be used for session validation check_user_agent: If the browser user agent should be used for sessoin validation. set_cookie_expires: True adds an expires field to the cookie so it saves even if the browser is closed. session_token_ttl: Number of sessions a session token is valid for before it should be regenerated. """ self.cookie_path = cookie_path self.cookie_domain = cookie_domain self.cookie_name = cookie_name self.session_expire_time = session_expire_time self.integrate_flash = integrate_flash self.check_user_agent = check_user_agent self.check_ip = check_ip self.set_cookie_expires = set_cookie_expires self.session_token_ttl = session_token_ttl self.last_activity_update = last_activity_update self.writer = writer # make sure the page is not cached in the browser print self.no_cache_headers() # Check the cookie and, if necessary, create a new one. self.cache = {} string_cookie = os.environ.get(u"HTTP_COOKIE", u"") self.cookie = Cookie.SimpleCookie() self.output_cookie = Cookie.SimpleCookie() if string_cookie == "": self.cookie_vals = {} else: self.cookie.load(string_cookie) try: self.cookie_vals = \ simplejson.loads(self.cookie["%s_data" % (self.cookie_name)].value) # sync self.cache and self.cookie_vals which will make those # values available for all gets immediately. for k in self.cookie_vals: self.cache[k] = self.cookie_vals[k] # sync the input cookie with the output cookie self.output_cookie["%s_data" % (self.cookie_name)] = \ simplejson.dumps(self.cookie_vals) #self.cookie["%s_data" % (self.cookie_name)] except Exception, e: self.cookie_vals = {} if writer == "cookie": pass else: self.sid = None new_session = True # do_put is used to determine if a datastore write should # happen on this request. do_put = False # check for existing cookie if self.cookie.get(cookie_name): self.sid = self.cookie[cookie_name].value # The following will return None if the sid has expired. self.session = _AppEngineUtilities_Session.get_session(self) if self.session: new_session = False if new_session: # start a new session self.session = _AppEngineUtilities_Session() self.session.put() self.sid = self.new_sid() if u"HTTP_USER_AGENT" in os.environ: self.session.ua = os.environ[u"HTTP_USER_AGENT"] else: self.session.ua = None if u"REMOTE_ADDR" in os.environ: self.session.ip = os.environ["REMOTE_ADDR"] else: self.session.ip = None self.session.sid = [self.sid] # do put() here to get the session key self.session.put() else: # check the age of the token to determine if a new one # is required duration = datetime.timedelta(seconds=self.session_token_ttl) session_age_limit = datetime.datetime.now() - duration if self.session.last_activity < session_age_limit: self.sid = self.new_sid() if len(self.session.sid) > 2: self.session.sid.remove(self.session.sid[0]) self.session.sid.append(self.sid) do_put = True else: self.sid = self.session.sid[-1] # check if last_activity needs updated ula = datetime.timedelta(seconds=self.last_activity_update) if datetime.datetime.now() > self.session.last_activity + \ ula: do_put = True self.output_cookie[cookie_name] = self.sid self.output_cookie[cookie_name]["path"] = self.cookie_path if self.cookie_domain: self.output_cookie[cookie_name]["domain"] = self.cookie_domain if self.set_cookie_expires: self.output_cookie[cookie_name]["expires"] = \ self.session_expire_time self.cache[u"sid"] = self.sid if do_put: if self.sid != None or self.sid != u"": self.session.put() if self.set_cookie_expires: if not self.output_cookie.has_key("%s_data" % (cookie_name)): self.output_cookie["%s_data" % (cookie_name)] = u"" self.output_cookie["%s_data" % (cookie_name)]["expires"] = \ self.session_expire_time print self.output_cookie.output() # fire up a Flash object if integration is enabled if self.integrate_flash: import flash self.flash = flash.Flash(cookie=self.cookie) # randomly delete old stale sessions in the datastore (see # CLEAN_CHECK_PERCENT variable) if random.randint(1, 100) < clean_check_percent: self._clean_old_sessions()
#!/usr/bin/env python import flash import sys def Help(): print "Usage: upload.py <kernel>" sys.exit(-1) if __name__ == "__main__": k = "bzImage" if sys.argv[1:]: k = sys.argv[1] p = flash.Flash("test") print "Programming" p.FlashKernel(k) p.Close()
def main(): """ Get configuration, get driver, and build handler and start it. """ args = get_args() port = args.port[0] baud = args.baud[0] use_ftdi = args.ftdi use_m25 = args.m25 use_stm = args.stm erase = args.erase # Driver with context with serial_link.get_driver(use_ftdi, port, baud) as driver: # Handler with context with Handler(Framer(driver.read, driver.write)) as link: link.add_callback(serial_link.log_printer, SBP_MSG_LOG) link.add_callback(serial_link.printer, SBP_MSG_PRINT_DEP) # Tell Bootloader we want to write to the flash. with Bootloader(link) as piksi_bootloader: print "Waiting for bootloader handshake message from Piksi ...", sys.stdout.flush() try: handshake_received = piksi_bootloader.handshake( args.timeout[0]) except KeyboardInterrupt: return if not (handshake_received and piksi_bootloader.handshake_received): print "No handshake received." sys.exit(1) print "received." print "Piksi Onboard Bootloader Version:", piksi_bootloader.version if piksi_bootloader.sbp_version > (0, 0): print "Piksi Onboard SBP Protocol Version:", piksi_bootloader.sbp_version # Catch all other errors and exit cleanly. try: import flash with flash.Flash( link, flash_type=("STM" if use_stm else "M25"), sbp_version=piksi_bootloader.sbp_version, max_queued_ops=int( args.max_queued_ops[0])) as piksi_flash: if erase: for s in range(1, 12): print "\rErasing STM Sector", s, sys.stdout.flush() piksi_flash.erase_sector(s) print from intelhex import IntelHex ihx = IntelHex(args.file) piksi_flash.write_ihx(ihx, sys.stdout, mod_print=0x10) print "Bootloader jumping to application" piksi_bootloader.jump_to_app() except: import traceback traceback.print_exc()
def onVelocity(msg): receive(msg, 'velocity') client.powerControl(powerValue) def onRoundPassed(msg): receive(msg, 'round') client.powerControl(powerValue) def onRaceStop(msg): receive(msg, 'stop') client.disconnect() import flash from imp import reload reload(flash) flash_pilot = flash.Flash(client) client.onRaceStart(flash_pilot.on_race_start) client.onVelocity(flash_pilot.on_velocity) client.onSensor(flash_pilot.on_sensor) client.onPenalty(flash_pilot.on_penalty) client.onRoundPassed(flash_pilot.on_round_passed) client.onRaceStop(flash_pilot.on_race_stop) client.connect(RABBIT_HOST) client.announce()
def __init__(self, cookie_path=DEFAULT_COOKIE_PATH, cookie_name=COOKIE_NAME, session_expire_time=SESSION_EXPIRE_TIME, clean_check_percent=CLEAN_CHECK_PERCENT, integrate_flash=INTEGRATE_FLASH, check_ip=CHECK_IP, check_user_agent=CHECK_USER_AGENT, set_cookie_expires=SET_COOKIE_EXPIRES, session_token_ttl=SESSION_TOKEN_TTL, last_activity_update=UPDATE_LAST_ACTIVITY, writer=WRITER): """ Initializer Args: cookie_name: The name for the session cookie stored in the browser. session_expire_time: The amount of time between requests before the session expires. clean_check_percent: The percentage of requests the will fire off a cleaning routine that deletes stale session data. integrate_flash: If appengine-utilities flash utility should be integrated into the session object. check_ip: If browser IP should be used for session validation check_user_agent: If the browser user agent should be used for sessoin validation. set_cookie_expires: True adds an expires field to the cookie so it saves even if the browser is closed. session_token_ttl: Number of sessions a session token is valid for before it should be regenerated. """ self.cookie_path = cookie_path self.cookie_name = cookie_name self.session_expire_time = session_expire_time self.integrate_flash = integrate_flash self.check_user_agent = check_user_agent self.check_ip = check_ip self.set_cookie_expires = set_cookie_expires self.session_token_ttl = session_token_ttl self.last_activity_update = last_activity_update self.writer = writer # make sure the page is not cached in the browser self.no_cache_headers() # Check the cookie and, if necessary, create a new one. self.cache = {} string_cookie = os.environ.get('HTTP_COOKIE', '') self.cookie = Cookie.SimpleCookie() self.output_cookie = Cookie.SimpleCookie() self.cookie.load(string_cookie) try: self.cookie_vals = \ simplejson.loads(self.cookie[self.cookie_name + '_data'].value) # sync self.cache and self.cookie_vals which will make those # values available for all gets immediately. for k in self.cookie_vals: self.cache[k] = self.cookie_vals[k] self.output_cookie[self.cookie_name + '_data'] = self.cookie[self.cookie_name + '_data'] # sync the input cookie with the output cookie except: self.cookie_vals = {} if writer == "cookie": pass else: self.sid = None new_session = True # do_put is used to determine if a datastore write should # happen on this request. do_put = False # check for existing cookie if self.cookie.get(cookie_name): self.sid = self.cookie[cookie_name].value self.session = self._get_session() # will return None if # sid expired if self.session: new_session = False if new_session: # start a new session self.session = _AppEngineUtilities_Session() self.session.put() self.sid = self.new_sid() if 'HTTP_USER_AGENT' in os.environ: self.session.ua = os.environ['HTTP_USER_AGENT'] else: self.session.ua = None if 'REMOTE_ADDR' in os.environ: self.session.ip = os.environ['REMOTE_ADDR'] else: self.session.ip = None self.session.sid = [self.sid] # do put() here to get the session key key = self.session.put() else: # check the age of the token to determine if a new one # is required duration = datetime.timedelta(seconds=self.session_token_ttl) session_age_limit = datetime.datetime.now() - duration if self.session.last_activity < session_age_limit: self.sid = self.new_sid() if len(self.session.sid) > 2: self.session.sid.remove(self.session.sid[0]) self.session.sid.append(self.sid) do_put = True else: self.sid = self.session.sid[-1] # check if last_activity needs updated ula = datetime.timedelta(seconds=self.last_activity_update) if datetime.datetime.now( ) > self.session.last_activity + ula: do_put = True self.output_cookie[cookie_name] = self.sid self.output_cookie[cookie_name]['path'] = cookie_path # UNPICKLING CACHE self.cache['sid'] = pickle.dumps(self.sid) self.cache['sid'] = self.sid if do_put: if self.sid != None or self.sid != "": self.session.put() if self.set_cookie_expires: if not self.output_cookie.has_key(cookie_name + '_data'): self.output_cookie[cookie_name + '_data'] = "" self.output_cookie[cookie_name + '_data']['expires'] = \ self.session_expire_time print self.output_cookie.output() # fire up a Flash object if integration is enabled if self.integrate_flash: import flash self.flash = flash.Flash(cookie=self.cookie) # randomly delete old stale sessions in the datastore (see # CLEAN_CHECK_PERCENT variable) if random.randint(1, 100) < clean_check_percent: self._clean_old_sessions()
or use macros or inline functions from this project, or you compile this file and link it with other works to produce a work based on this file, this file does not by itself cause the resulting work to be covered by the GNU General Public License. However the source code for this file must still be made available in accordance with section (3) of the GNU General Public License. This exception does not invalidate any other reasons why a work based on this file might be covered by the GNU General Public License. """ # CAUTION: EXAMPLE CODE ONLY! # This file could be the starting point for a unit test for the flash module, # or a command-line version of labman. It needs some work, however. import flash def print_progress(flash, step, of): print "%d of %d" % (step, of) def print_messages(flash, message): print message x = flash.Flash('/dev/hda', '/mnt', print_progress, print_messages) x.make_partition() x.make_filesystem() x.mount() x.extract_moe('/home/moe/moe-2.0.0rc58.tgz') x.make_bootrecord() x.extract_packages('','') x.umount()