def GenerateGetConfigFunction(self): """Generate GetConfig function source.""" f = lambda p: '{}'.format(c_helpers.CamelToSnake(p.TypeName())) path = self._enum_path variables = [ 'int32_t i_{0} = (int32_t){0};'.format(f(p)) for p in path ] checks = [ '{min} <= i_{name} && i_{name} <= {max}'.format(min=p.min_value, max=p.max_value, name=f(p)) for p in path ] deref = ''.join('[i_{}]'.format(f(p)) for p in path) return textwrap.dedent("""\ {prototype} {{ // Avoid "always true" compiler warnings. {variables} if ({checks}) {{ return &kRevisionMap{deref}; }} return NULL; }} """).format(prototype=self.GenerateGetConfigPrototype(), variables='\n '.join(variables), checks='\n && '.join(checks), deref=deref)
def GenerateDefines(self): """Generate helpful #defines for monitoring C code.""" max_devices = max([ len(r['devices_by_address'].keys()) for r in self._revision_by_path.values() ]) return textwrap.dedent("""\ #define MAX_{name_upper}_DEVICES {max_devices} """).format(name_upper=c_helpers.CamelToSnake( self._name_prefix).upper(), max_devices=max_devices)
def HardwareIdentityMenu(self): """Ask the user to select a hardware identity of select_node. The menu options are derived from identity_types.h. Returns: Selected hardware identity or None if the user cancelled. """ default = 'aio' node_prefix = self.select_node.snake_name.partition('_')[0] hardware_types = [ c_helpers.CamelToSnake(camel) for camel in generate_image.hardware_type_helper.ShortNames() ] hardware_types.remove('unknown') if (node_prefix in hardware_types and not self.HasCarrierBoard()): default = node_prefix rc, hardware_type = self.dialog_ui.Menu('Select hardware type:', zip(hardware_types, hardware_types), default_item=default) if rc: return hardware_type
def ParseArguments(argv): """Parse the arguments and do sanity checks.""" targets = [ c_helpers.CamelToSnake(node) for node in aio.aio_node_helper.ShortNames() ] hardware_types = ['aio', 'motor', 'cs'] flags = gflags.FLAGS gflags.DEFINE_bool('application', False, 'Flash an application bin.') gflags.DEFINE_bool('bootloader', False, 'Flash a bootloader bin.') gflags.DEFINE_bool('calib', False, 'Flash calibration parameters.') gflags.DEFINE_bool('config', False, 'Flash configuration parameters.') gflags.DEFINE_bool('erase', False, 'Erase all flash memory.') gflags.DEFINE_bool('serial', False, 'Flash a serial bin file.') gflags.DEFINE_integer('speed', 4000, 'JTAG Speed (kHz).') gflags.DEFINE_enum('hardware_type', None, hardware_types, 'Hardware type.') gflags.DEFINE_enum('target', None, targets, 'Target node to program') gflags.DEFINE_integer('retry', 3, 'How many retries to attempt during failures.') gflags.DEFINE_string('file', None, 'The file.') try: argv = flags(argv) if (flags.application or flags.bootloader or flags.calib or flags.config or flags.serial): if not flags.file: raise gflags.FlagsError( 'You must specify --file with --application, ' '--bootloader, --calib, --config or --serial.') if _ValidFileArg(flags.file, '.elf'): file_type = 'elf' elif _ValidFileArg(flags.file, '.bin'): file_type = 'bin' else: raise gflags.FlagsError( 'Unknown file type: "{}", expected .bin or .elf'.format( flags.file)) elif not flags.erase: raise gflags.FlagsError( 'Invalid argument combination! Pick one of: ' '--application, --bootloader, --calib, --config ' '--erase or --serial') if flags.bootloader or flags.application: if file_type == 'elf': if not flags.target: raise gflags.FlagsError( 'You must specify --target when using ' '--bootloader or --application with .elf ' 'files.') if not flags.hardware_type: raise gflags.FlagsError( 'You must specify a hardware_type.') elif flags.calib or flags.config or flags.serial: if file_type != 'bin': raise gflags.FlagsError( 'You must specify a bin file for this action.') except gflags.FlagsError, e: print e, flags sys.exit(1)
def testBasicCases(self): for c in self._cases: self.assertEqual(c_helpers.CamelToSnake(c[0]), c[1])
def AddEnum(self, enum): value_map_str = '' c_value_map_str = '' name_map_str = '' constants_str = '' for value in sorted(enum.body.value_map.keys()): name = enum.body.value_map[value] const_name = c_helpers.CamelToSnake(name).upper() c_name = 'k' + enum.name + name value_map_str += " {value}: '{name}',\n".format(name=name, value=value) c_value_map_str += " {value}: '{c_name}',\n".format( c_name=c_name, value=value) name_map_str += " '{name}': {value},\n".format(name=name, value=value) constants_str += ( '{type_name}.{const_name} = {type_name}({value})\n'.format( const_name=const_name, value=value, type_name=enum.name)) max_value = max(enum.body.value_map.keys()) min_value = min(enum.body.value_map.keys()) # Strip trailing newline from above generated code. value_map_str = value_map_str[:-1] name_map_str = name_map_str[:-1] constants_str = constants_str[:-1] header_path = self.c_header_path self.source_string += textwrap.dedent("""\ class {type_name}(ctypes._SimpleCData, py_types.PackableCType): _type_ = '{type_code}' _value_map = {{ {value_map} }} _c_value_map = {{ {c_value_map} }} _name_map = {{ {name_map} }} max_value = {max_value} min_value = {min_value} def __init__(self, value=0): super(self.__class__, self).__init__() self.__setstate__(value) def __setstate__(self, state): if isinstance(state, basestring): self.value = self._name_map[state] elif isinstance(state, self.__class__): self.value = state.value else: self.value = state def __repr__(self): return self._value_map[self.value] def __hash__(self): return self.value def __eq__(self, other): if isinstance(other, basestring): return self.value == self._name_map[other] elif isinstance(other, self.__class__): return self.value == other.value else: return self.value == other def __ne__(self, other): return not self.__eq__(other) def CName(self): return self._c_value_map[self.value] @classmethod def Names(cls): return [{type_name}(v) for v in cls._value_map.keys()] @classmethod def iteritems(cls): return cls._name_map.iteritems() @classmethod def HeaderFile(cls): return "{output_c_header}" @classmethod def TypeName(cls): return "{type_name}" {constants} """).format(type_name=enum.name, type_code=self._enum_type_map[enum.width], value_map=value_map_str, c_value_map=c_value_map_str, name_map=name_map_str, max_value=max_value, min_value=min_value, output_c_header=header_path, constants=constants_str)
def _GenerateHeader(info_map, header_file): """Generate output header file as a string.""" guard = re.sub('[/.]', '_', header_file).upper() + '_' parts = [ textwrap.dedent("""\ #ifndef {guard} #define {guard} #include <stddef.h> #include <stdint.h> """).format(guard=guard) ] includes = aio_message.GetHeaderFilesFromMessageInfoMap(info_map) includes += ['avionics/common/aio_header.h'] includes += ['avionics/network/message_type.h'] parts += ['#include "%s"' % f for f in sorted(includes)] parts.append( textwrap.dedent(""" #ifdef __cplusplus extern "C" { #endif """)) parts.append( textwrap.dedent("""\ typedef size_t (* const PackAioMessageFunction)( const void *in, size_t num, uint8_t *out); typedef size_t (* const UnpackAioMessageFunction)( const uint8_t *in, size_t num, void *out); typedef struct { const char *name; const char *short_name; PackAioMessageFunction pack_func; UnpackAioMessageFunction unpack_func; int32_t pack_size; int32_t unpack_size; } AioMessageInfo; """)) parts.append('typedef union {') for message in sorted(info_map.keys(), key=lambda m: m.name): info = info_map[message] if info: parts.append(' {struct_name} {var};'.format( struct_name=info.struct_name, var=c_helpers.CamelToSnake(message.name))) parts.append('} AioMessageData;') parts.append( textwrap.dedent(""" typedef struct { AioHeader header; AioMessageData u; // Union of all possible data types. } AioMessage; """)) parts.append( textwrap.dedent("""\ extern const AioMessageInfo kAioMessageInfo[kNumMessageTypes]; size_t PackAioMessageData(MessageType type, const void *in, uint8_t *out); size_t UnpackAioMessageData(MessageType type, const uint8_t *in, void *out); #ifdef __cplusplus }} // extern "C" #endif #endif /* {guard} */ """).format(guard=guard)) return '\n'.join(parts)
def GenerateGetConfigPrototype(self): """Generate GetConfig function prototype.""" f = lambda p: p.TypeName() + ' ' + c_helpers.CamelToSnake(p.TypeName()) args = ', '.join(f(p) for p in self._enum_path) return 'const {name}Monitors *{prefix}GetConfig({args})'.format( name=self._type_prefix, prefix=self._name_prefix, args=args)