def encode_uri(uri, verbose=True): expt = None tokens = uri.strip('/').split('/') if len(tokens) > encode_uri_size: tokens[encode_uri_size - 1] = '/'.join(tokens[encode_uri_size - 1:]) tokens = tokens[:encode_uri_size] expt = Exception('encode_uri error: parts of uri: %s large than %d' % (uri, encode_uri_size)) if verbose: if expt: util.print_out('encode_uri: %s' % tokens, 1) print(expt) # time.sleep(1) else: util.print_out('encode_uri: %s' % tokens) for i in range(len(tokens)): tokens[i] = util.str_to_float(tokens[i]) if len(tokens) <= encode_uri_size: tokens += [0.0] * (encode_uri_size - len(tokens)) return tokens
def __init__(self, *arg, **kwargs): self.name = util.slugify(kwargs.pop('name', 'my-camera')) self.directory = kwargs.pop('directory', path.dirname(path.realpath(__file__))) self.width = kwargs.pop('width', 640) self.height = kwargs.pop('height', 480) self.rotation = kwargs.pop('rotation', 0) self.init_camera() if self.is_working(): util.print_out('CAMERA LOADED', self.full_name()) else: util.print_out('CAMERA FAILD', self.full_name())
def save(self): filename = self.get_fullname() cmd = 'fswebcam -r %dx%d --no-banner --rotate %d %s' % ( self.width, self.height, self.rotation, filename, ) try: result = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT) if result.find('Writing JPEG image to') != -1: util.print_out('SAVED', path.basename(filename)) return True except subprocess.CalledProcessError: pass util.print_out('FAILED', path.basename(filename)) return False
def start_camera(): camera = None try: width = int(args.size.split('x')[0]) height = int(args.size.split('x')[1]) except: raise sys.exit('Wrong size format. e.g. 800x600, 640x480, 320x240...') settings = { 'width': width, 'height': height, 'name': args.name, 'directory': path.join(root, 'feed'), 'rotation': args.rotation, } if args.fswebcam: util.print_out('CAMERA INIT', args.name) camera = FSWebCamera(**settings) elif has_cv: util.print_out('CAMERA INIT', '%s (%d)' % (args.name, args.camera_id)) camera = CVCamera(camera_id=args.camera_id, **settings) elif has_picamera: util.print_out('CAMERA INIT', args.name) camera = PiCamera(**settings) if camera and camera.is_working(): next_capture(camera)
def parse_dir(directory): global upload_queue global last_cache global parsed global last_report if not headers: return all_files = [] for root, dirs, files in os.walk(directory): if files: for filename in files: full_filename = os.path.join(root, filename) if full_filename.endswith('.jpg'): all_files.append(full_filename) if full_filename.endswith('.DS_Store'): os.remove(full_filename) elif not (dirs or files): try: os.rmdir(root) except Exception as e: util.print_out('REMOVE EXCEPTION', os.path.basename(filename)) util.print_out('EXCEPTION', e) all_files.sort(reverse=True) count = 0 for filename in all_files: if filename not in parsed: parsed[filename] = True upload_queue.put(filename) count += 1 if count == args.threads: break count_parsed = len(parsed) counte_all = len(all_files) report = '+%d (%d of %d)' % (count, len(parsed), len(all_files)) if report != last_report: util.print_out('QUEUE', report) last_report = report
def main(): argparser = argparse.ArgumentParser(description=__doc__) argparser.add_argument( '-v', '--version', action='version', version='%(prog)s ' + util.get_resource('version.txt')) argparser.add_argument( '-d', '--debug', action='store_true', help='print debug information') argparser.add_argument( '--targets', action='store_true', help='write out targets (for debugging purposes)') argparser.add_argument( '--hello-world', action='store_true', dest='init_hello_world', help='initialize this folder with a "hello world" project') settings_file_group = argparser.add_argument_group('configuration file') default_settings = util.get_default_settings_file() settings_file_group.add_argument( '-f', metavar='FILE', dest='settings_file', default=default_settings, help='path to an existing config file, defaults to %s' % default_settings) settings_file_group.add_argument( '-g', action='store_true', dest='init_settings_file', help='generate a default %s file' % default_settings) generators_group = argparser.add_argument_group('generators') help_gatherer = HelpGatherer(generators_group) generators_group.add_argument( '--embed', action='store_true', help='embed resources (experimental)') generators_group.add_argument( '--ninja', action='store_true', help='generate build.ninja') generators_group.add_argument( '--makefile', action='store_true', help='generate Makefile') generators_group.add_argument( '--doxyfile', action='store_true', help='generate doxygen\'s Doxyfile') generators_group.add_argument( '--sublime', action='store_true', help='generate Sublime Text project') generators_group.add_argument( '--codeblocks', action='store_true', help='generate CodeBlocks projects (experimental)') args = argparser.parse_args() loglevel = logging.DEBUG if args.debug else logging.WARNING logging.basicConfig(format='%(levelname)s: %(message)s', level=loglevel) try: builtin_open = __builtin__.open def open_hook(*args, **kwargs): logging.debug('Open file: %s', args[0]) try: return builtin_open(*args, **kwargs) except Exception as exception: critical_error(exception) __builtin__.open = open_hook except Exception as exception: logging.warning('Hook to open failed: %s', exception) if args.init_settings_file or args.init_hello_world: print_out('Generate %s.' % args.settings_file) import init init.init_settings_file(args.settings_file) if args.init_hello_world: print_out('Generate "Hello World" code.') init.init_hello_world() args.makefile = True if args.settings_file is None: print_out('Missing settings.') argparser.print_usage() return actions = ['targets', 'embed', 'ninja', 'makefile', 'doxyfile', 'sublime', 'codeblocks'] action_count = sum(getattr(args, x) for x in actions) if action_count == 0: print_out('Nothing to be done.') argparser.print_usage() return Settings.load(args.settings_file) targets = [x for x in iterate_targets(Settings.get('sourcedir'))] logging.info('%i targets found', len(targets)) if args.targets: data = {'targets': [x.raw for x in targets]} targets_file = os.path.join(Settings.get('builddir'), 'targets.json') util.mkdir_p(os.path.dirname(targets_file)) with open(targets_file, 'w+') as out: out.write(json.dumps(data, indent=2)) print_out('Targets saved to %s.' % targets_file) if action_count == 1: return if args.embed: print_out(help_gatherer.command_help['--embed']) import embedder embedder.embed(targets, Settings.get('sourcedir')) print_out("Targets may have changed, re-run configure.pyz to update.") return compiler = Compiler(Settings) if args.doxyfile: print_out(help_gatherer.command_help['--doxyfile']) import doxygen doxygen.generate(Settings) if args.ninja or args.makefile or args.sublime: print_out(help_gatherer.command_help['--ninja']) import ninja ninja_targets = ninja.generate(targets, Settings, compiler, '.') if args.makefile: print_out(help_gatherer.command_help['--makefile']) import makefile this = Path.clean(os.path.relpath(sys.argv[0])) command_call = [this, '-f', args.settings_file] makefile.generate(command_call, ninja_targets, actions, Settings, '.') if args.sublime: print_out(help_gatherer.command_help['--sublime']) import sublime sublime.generate(ninja_targets, Settings) if args.codeblocks: print_out(help_gatherer.command_help['--codeblocks']) import codeblocks codeblocks.generate(targets, Settings, compiler)
def main(): try: # NOTE: Multiple SIGKILLs required to force close. raw_input_async.last_kill_sig = None # Clear the terminal vt100.terminal.reset() # Ahoy print(BANNER) # Initial session mode current_mode = modes.offline # Init terminal init_terminal() register_completer(completer_switcher[current_mode]) # Async output printing thread.start_new_thread(noise, ()) prompts_list = config.settings['ui']['prompts'] get_prompt = lambda: { modes.offline: prompts_list[0], modes.debugging: prompts_list[1] }[current_mode] # Main loop while current_mode != modes.quit: vt100.unlock_keyboard() # FIXME: raw_input_async still is a blocking call. Have found no way to # avoid it. Reason: readline initiates a system call that I have no # clue to get out of. user_input, key_seq = raw_input_async(get_prompt()) # HACK: Temporarily disabled for debugging #vt100.lock_keyboard() ## HACK: Display the user's input #print_out(user_input.encode('string_escape') if user_input else '') # An empty string is a valid empty # If the input was a control signal split might just remove it packed_input = user_input if user_input else key_seq if not packed_input: continue cmd, args = packed_input[0], packed_input[1:] # Run the appropriate mode's processing function cmd_processor_fn = command_handler_switcher.get(current_mode) try: current_mode, update_msg = cmd_processor_fn(cmd, args) register_completer(completer_switcher[current_mode]) if update_msg: print_out(update_msg) except errors.UnknownCommandError as e: print_error( 'Unknown command: {u1}{cmd}{u0}', cmd=repr_str(e.expression) ) except errors.BadArgsError as e: print_error( 'Command "{u1}{cmd}{u0}" cannot be initiated with the arguments provided.\n{msg}', cmd=e.expression, msg=e.message ) except errors.BadConfigError as e: print_error( 'The command encountered errors with the provided arguments.\n{u1}{cmd}{u0}: {msg}', cmd=e.expression, msg=e.message ) except errors.CommandFailedError as e: print_error( 'The command encountered an error and did not run properly.\n{u1}{cmd}{u0}: {msg}', cmd=e.expression, msg=e.message ) except errors.CommandImplementationIncompleteError: print_error( 'The implementation of command "{u1}{cmd}{u0}" is not complete yet.', cmd=cmd ) except KeyboardInterrupt: print_error('Action cancelled by the user.') finally: cleanup_terminal()
def upload_file(filename): global parsed global headers try: image_file = open(filename, 'rb') except Exception as e: util.print_out('OPEN EXCEPTION', os.path.basename(filename)) pop_parsed(filename) return try: req = requests.get(UPLOAD_URL, headers=headers) response = json.loads(req.text) except Exception as e: util.print_out('EXCEPTION GET', e.message) return if response['status'] == 'success': upload_url = response['result'][0]['upload_url'] files = {'file': (os.path.basename(filename), image_file, 'image/jpeg')} util.print_out('UPLOADING', os.path.basename(filename)) try: req_upload = requests.post(upload_url, files=files, headers=headers) json_upload = json.loads(req_upload.text) image_file.close() if json_upload['status'] == 'success': try: os.remove(filename) except Exception as e: util.print_out('REMOVE EXCEPTION', os.path.basename(filename)) util.print_out('EXCEPTION', e) util.print_out('DONE', os.path.basename(filename)) else: util.print_out('ERROR', os.path.basename(filename)) print json.dumps(json_upload, sort_keys=True, indent=2) except Exception as e: util.print_out('UPLOAD EXCEPTION', os.path.basename(filename)) util.print_out('EXCEPTION POST', e.message) pop_parsed(filename) else: headers = None
def save(self): filename = self.get_fullname() self.camera.capture(filename) util.print_out('SAVED', path.basename(filename))
def save(self): retval, image = self.capture.read() filename = self.get_fullname() cv2.imwrite(filename, image) util.print_out('SAVED', path.basename(filename))
def upload_file(filename): global parsed global headers try: image_file = open(filename, 'rb') except Exception as e: util.print_out('OPEN EXCEPTION', os.path.basename(filename)) pop_parsed(filename) return try: req = requests.get(UPLOAD_URL, headers=headers) response = json.loads(req.text) except Exception as e: util.print_out('EXCEPTION GET', e.message) return if response['status'] == 'success': upload_url = response['result'][0]['upload_url'] files = { 'file': (os.path.basename(filename), image_file, 'image/jpeg') } util.print_out('UPLOADING', os.path.basename(filename)) try: req_upload = requests.post(upload_url, files=files, headers=headers) json_upload = json.loads(req_upload.text) image_file.close() if json_upload['status'] == 'success': try: os.remove(filename) except Exception as e: util.print_out('REMOVE EXCEPTION', os.path.basename(filename)) util.print_out('EXCEPTION', e) util.print_out('DONE', os.path.basename(filename)) else: util.print_out('ERROR', os.path.basename(filename)) print json.dumps(json_upload, sort_keys=True, indent=2) except Exception as e: util.print_out('UPLOAD EXCEPTION', os.path.basename(filename)) util.print_out('EXCEPTION POST', e.message) pop_parsed(filename) else: headers = None