mbed os with nrf51 internal bandgap enabled to read battery level

Dependents:   BLE_file_test BLE_Blink ExternalEncoder

Committer:
elessair
Date:
Sun Oct 23 15:10:02 2016 +0000
Revision:
0:f269e3021894
Initial commit

Who changed what in which revision?

UserRevisionLine numberNew contents of line
elessair 0:f269e3021894 1 import json
elessair 0:f269e3021894 2 import os
elessair 0:f269e3021894 3 import stat
elessair 0:f269e3021894 4 import re
elessair 0:f269e3021894 5 from collections import OrderedDict
elessair 0:f269e3021894 6 from subprocess import Popen
elessair 0:f269e3021894 7
elessair 0:f269e3021894 8 git_processes = []
elessair 0:f269e3021894 9
elessair 0:f269e3021894 10 class MyJSONEncoder(json.JSONEncoder):
elessair 0:f269e3021894 11 def __init__(self, *args, **kwargs):
elessair 0:f269e3021894 12 super(MyJSONEncoder, self).__init__(*args, **kwargs)
elessair 0:f269e3021894 13 self.current_indent = 0
elessair 0:f269e3021894 14 self.current_indent_str = ""
elessair 0:f269e3021894 15
elessair 0:f269e3021894 16
elessair 0:f269e3021894 17 def encode(self, o):
elessair 0:f269e3021894 18 #Special Processing for lists
elessair 0:f269e3021894 19 if isinstance(o, (list, tuple)):
elessair 0:f269e3021894 20 primitives_only = True
elessair 0:f269e3021894 21 for item in o:
elessair 0:f269e3021894 22 if isinstance(item, (list, tuple, dict)):
elessair 0:f269e3021894 23 primitives_only = False
elessair 0:f269e3021894 24 break
elessair 0:f269e3021894 25 output = []
elessair 0:f269e3021894 26 if primitives_only:
elessair 0:f269e3021894 27 for item in o:
elessair 0:f269e3021894 28 output.append(json.dumps(item))
elessair 0:f269e3021894 29 return "[" + ", ".join(output) + "]"
elessair 0:f269e3021894 30 else:
elessair 0:f269e3021894 31 self.current_indent += self.indent
elessair 0:f269e3021894 32 self.current_indent_str = " " * self.current_indent
elessair 0:f269e3021894 33 for item in o:
elessair 0:f269e3021894 34 output.append(self.current_indent_str + self.encode(item))
elessair 0:f269e3021894 35 self.current_indent -= self.indent
elessair 0:f269e3021894 36 self.current_indent_str = " " * self.current_indent
elessair 0:f269e3021894 37 return "[\n" + ",\n".join(output) + "\n" + self.current_indent_str + "]"
elessair 0:f269e3021894 38 elif isinstance(o, dict):
elessair 0:f269e3021894 39 primitives_only = True
elessair 0:f269e3021894 40 for item in o.values():
elessair 0:f269e3021894 41 if isinstance(item, (list, tuple, dict)):
elessair 0:f269e3021894 42 primitives_only = False
elessair 0:f269e3021894 43 break
elessair 0:f269e3021894 44 output = []
elessair 0:f269e3021894 45 if primitives_only and len(o) < 3:
elessair 0:f269e3021894 46 for key, value in o.iteritems():
elessair 0:f269e3021894 47 output.append(json.dumps(key) + ": " + self.encode(value))
elessair 0:f269e3021894 48 return "{" + ", ".join(output) + "}"
elessair 0:f269e3021894 49 else:
elessair 0:f269e3021894 50 self.current_indent += self.indent
elessair 0:f269e3021894 51 self.current_indent_str = " " * self.current_indent
elessair 0:f269e3021894 52 for key, value in o.iteritems():
elessair 0:f269e3021894 53 output.append(self.current_indent_str + json.dumps(key) + ": " + self.encode(value))
elessair 0:f269e3021894 54 self.current_indent -= self.indent
elessair 0:f269e3021894 55 self.current_indent_str = " " * self.current_indent
elessair 0:f269e3021894 56 return "{\n" + ",\n".join(output) + "\n" + self.current_indent_str + "}"
elessair 0:f269e3021894 57 else:
elessair 0:f269e3021894 58 return json.dumps(o)
elessair 0:f269e3021894 59
elessair 0:f269e3021894 60 def load(path):
elessair 0:f269e3021894 61 with open(path, 'r') as f :
elessair 0:f269e3021894 62 return json.load(f, object_pairs_hook=OrderedDict)
elessair 0:f269e3021894 63
elessair 0:f269e3021894 64 def dump(path, obj):
elessair 0:f269e3021894 65 with os.fdopen(os.open(path, os.O_WRONLY | os.O_CREAT, stat.S_IRUSR | stat.S_IWUSR), 'w') as f :
elessair 0:f269e3021894 66 os.chmod(path, stat.S_IRUSR | stat.S_IWUSR)
elessair 0:f269e3021894 67 f.write(MyJSONEncoder(indent=4).encode(obj))
elessair 0:f269e3021894 68 f.write(u'\n')
elessair 0:f269e3021894 69 f.truncate()
elessair 0:f269e3021894 70
elessair 0:f269e3021894 71 def find(stem, path) :
elessair 0:f269e3021894 72 for root, directories, files in os.walk(path, followlinks=True) :
elessair 0:f269e3021894 73 [dir for dir in directories if dir[0] != '.']
elessair 0:f269e3021894 74 if (stem_match(stem,os.path.basename(os.path.normpath(root))) and
elessair 0:f269e3021894 75 "device.h" in files) :
elessair 0:f269e3021894 76 return os.path.join(root, "device.h")
elessair 0:f269e3021894 77
elessair 0:f269e3021894 78 def find_all_devices(path, verbose=False) :
elessair 0:f269e3021894 79 for root, directories, files in os.walk(path, followlinks=True) :
elessair 0:f269e3021894 80 [dir for dir in directories if dir[0] != '.']
elessair 0:f269e3021894 81 if "device.h" in files :
elessair 0:f269e3021894 82 if verbose : print("[VERBOSE] found a device.h file in {}".format(root))
elessair 0:f269e3021894 83 yield os.path.join(root, "device.h")
elessair 0:f269e3021894 84
elessair 0:f269e3021894 85 mbed_matcher = re.compile('mbed', re.IGNORECASE)
elessair 0:f269e3021894 86 def stem_match(stem, thing) :
elessair 0:f269e3021894 87 return (stem in thing or
elessair 0:f269e3021894 88 re.sub(mbed_matcher, '', stem) in thing)
elessair 0:f269e3021894 89
elessair 0:f269e3021894 90 attr_matcher = re.compile('^#define\W+DEVICE_(\w+)\W+1.*$')
elessair 0:f269e3021894 91 def parse_attributes(path) :
elessair 0:f269e3021894 92 with open(path) as input :
elessair 0:f269e3021894 93 for line in input :
elessair 0:f269e3021894 94 m = re.match(attr_matcher, line)
elessair 0:f269e3021894 95 if m: yield m.group(1)
elessair 0:f269e3021894 96
elessair 0:f269e3021894 97 remove_matcher = re.compile('^#define\W+DEVICE_(\w+)\W+[10].*$')
elessair 0:f269e3021894 98 def remove_attributes(path) :
elessair 0:f269e3021894 99 with open(path) as input :
elessair 0:f269e3021894 100 remainder = filter(lambda l: not re.match(remove_matcher, l), input)
elessair 0:f269e3021894 101 with open(path,"wb") as output :
elessair 0:f269e3021894 102 output.truncate(0)
elessair 0:f269e3021894 103 output.write("// The 'provides' section in 'target.json' is now used"+
elessair 0:f269e3021894 104 " to create the device's hardware preprocessor switches.\n")
elessair 0:f269e3021894 105 output.write("// Check the 'provides' section of the target description"+
elessair 0:f269e3021894 106 " in 'targets.json' for more details.\n")
elessair 0:f269e3021894 107 output.writelines(remainder)
elessair 0:f269e3021894 108
elessair 0:f269e3021894 109 def user_select(things, message) :
elessair 0:f269e3021894 110 print(message)
elessair 0:f269e3021894 111 for thing, number in zip(things, range(len(things))):
elessair 0:f269e3021894 112 print("{} : {}".format(number, thing))
elessair 0:f269e3021894 113 selection = None
elessair 0:f269e3021894 114 while selection is None :
elessair 0:f269e3021894 115 print("please select an integer [0..{}] or specify all".format(len(things) - 1))
elessair 0:f269e3021894 116 try :
elessair 0:f269e3021894 117 i = raw_input()
elessair 0:f269e3021894 118 if i == "all" :
elessair 0:f269e3021894 119 selection = "all"
elessair 0:f269e3021894 120 else :
elessair 0:f269e3021894 121 selection = int(i)
elessair 0:f269e3021894 122 if (selection > len(things) or
elessair 0:f269e3021894 123 selection < 0) :
elessair 0:f269e3021894 124 print("selection {} out of range".format(selection))
elessair 0:f269e3021894 125 selection = None
elessair 0:f269e3021894 126 except (ValueError, SyntaxError) :
elessair 0:f269e3021894 127 print("selection not understood")
elessair 0:f269e3021894 128 if selection == "all" :
elessair 0:f269e3021894 129 return things
elessair 0:f269e3021894 130 else :
elessair 0:f269e3021894 131 return [things[selection]]
elessair 0:f269e3021894 132
elessair 0:f269e3021894 133 target_matcher = re.compile("TARGET_")
elessair 0:f269e3021894 134 def strip_target(str) :
elessair 0:f269e3021894 135 return re.sub(target_matcher, "", str)
elessair 0:f269e3021894 136
elessair 0:f269e3021894 137 def add_to_targets(targets, device_file, verbose=False, remove=False) :
elessair 0:f269e3021894 138 if verbose : print("[VERBOSE] trying target {}".format(device_file))
elessair 0:f269e3021894 139 device = strip_target(os.path.basename(os.path.normpath(os.path.dirname(device_file))))
elessair 0:f269e3021894 140 if not device :
elessair 0:f269e3021894 141 print("[WARNING] device {} did not have an associated device.h".format(device))
elessair 0:f269e3021894 142 else :
elessair 0:f269e3021894 143 possible_matches = set([key for key in targets.keys() if stem_match(device, key)])
elessair 0:f269e3021894 144 for key, value in targets.iteritems() :
elessair 0:f269e3021894 145 for alt in value['extra_labels'] if 'extra_labels' in value else [] :
elessair 0:f269e3021894 146 if stem_match(device, alt) : possible_matches.add(key)
elessair 0:f269e3021894 147 for alt in value['extra_labels_add'] if 'extra_labels_add' in value else [] :
elessair 0:f269e3021894 148 if stem_match(device, alt) : possible_matches.add(key)
elessair 0:f269e3021894 149 possible_matches = list(possible_matches)
elessair 0:f269e3021894 150 for match in possible_matches :
elessair 0:f269e3021894 151 if device == match : possible_matches = [match]
elessair 0:f269e3021894 152 if not possible_matches :
elessair 0:f269e3021894 153 print("[WARNING] device {} did not have an associated entry in targets.json".format(device))
elessair 0:f269e3021894 154 return None
elessair 0:f269e3021894 155 elif len(possible_matches) > 1 :
elessair 0:f269e3021894 156 message = ("possible matches for file {}".format(device_file))
elessair 0:f269e3021894 157 target = user_select(possible_matches, message)
elessair 0:f269e3021894 158 else :
elessair 0:f269e3021894 159 target = possible_matches
elessair 0:f269e3021894 160 attrs = list(parse_attributes(device_file))
elessair 0:f269e3021894 161 if attrs :
elessair 0:f269e3021894 162 for t in target :
elessair 0:f269e3021894 163 targets[t]["device_has"] = sorted(list(set(targets[t].setdefault("device_has",[]) + attrs)))
elessair 0:f269e3021894 164 if verbose : print("[VERBOSE] target {} now device_has {}".format(t, attrs))
elessair 0:f269e3021894 165 if remove is True:
elessair 0:f269e3021894 166 remove_attributes(device_file)
elessair 0:f269e3021894 167
elessair 0:f269e3021894 168 if __name__ == '__main__' :
elessair 0:f269e3021894 169 import argparse
elessair 0:f269e3021894 170 parser = argparse.ArgumentParser(description='A helpful little script for converting' +
elessair 0:f269e3021894 171 ' device.h files to parts of the targets.json file')
elessair 0:f269e3021894 172 parser.add_argument('-a', '--all', action='store_true',
elessair 0:f269e3021894 173 help='find and convert all available device.h files in the'+
elessair 0:f269e3021894 174 ' directory tree starting at the current directory')
elessair 0:f269e3021894 175 parser.add_argument('-f', '--file', nargs='+', help='specify an individual file to '+
elessair 0:f269e3021894 176 'convert from device.h format to a piece of targets.json')
elessair 0:f269e3021894 177 parser.add_argument('-t', '--target', nargs='+', help='specify an individual target'+
elessair 0:f269e3021894 178 ' to convert from device.h format to a piece of targets.json')
elessair 0:f269e3021894 179 parser.add_argument('-v', '--verbose', action='store_true',
elessair 0:f269e3021894 180 help="print out every target that is updated in the targets.json")
elessair 0:f269e3021894 181 parser.add_argument('-r', '--rm', action='store_true',
elessair 0:f269e3021894 182 help="remove the used attributes from a device.h file")
elessair 0:f269e3021894 183 args = parser.parse_args()
elessair 0:f269e3021894 184 if not args.target and not args.file and not args.all :
elessair 0:f269e3021894 185 print("[WARNING] no action specified; auto-formatting targets.json")
elessair 0:f269e3021894 186
elessair 0:f269e3021894 187 targets_file_name = os.path.join(os.curdir, "hal", "targets.json")
elessair 0:f269e3021894 188 try :
elessair 0:f269e3021894 189 targets = load(targets_file_name)
elessair 0:f269e3021894 190 except OSError :
elessair 0:f269e3021894 191 print("[ERROR] did not find targets.json where I expected it {}".format(targets_file_name))
elessair 0:f269e3021894 192 exit(1)
elessair 0:f269e3021894 193 except ValueError :
elessair 0:f269e3021894 194 print("[ERROR] invalid json found in {}".format(targets_file_name))
elessair 0:f269e3021894 195 exit(2)
elessair 0:f269e3021894 196
elessair 0:f269e3021894 197 if args.target :
elessair 0:f269e3021894 198 for target in args.target :
elessair 0:f269e3021894 199 device_file = find(target, os.curdir)
elessair 0:f269e3021894 200 if device_file :
elessair 0:f269e3021894 201 add_to_targets(targets, device_file, verbose=args.verbose, remove=args.rm)
elessair 0:f269e3021894 202 else :
elessair 0:f269e3021894 203 print("[WARNING] could not locate a device file for target {}".format(target))
elessair 0:f269e3021894 204
elessair 0:f269e3021894 205 if args.file :
elessair 0:f269e3021894 206 for file in args.file :
elessair 0:f269e3021894 207 add_to_targets(targets, file, verbose=args.verbose, remove=args.rm)
elessair 0:f269e3021894 208
elessair 0:f269e3021894 209 if args.all :
elessair 0:f269e3021894 210 for file in find_all_devices(os.curdir, verbose=args.verbose) :
elessair 0:f269e3021894 211 add_to_targets(targets, file, verbose=args.verbose, remove=args.rm)
elessair 0:f269e3021894 212
elessair 0:f269e3021894 213 dump(targets_file_name, targets)
elessair 0:f269e3021894 214
elessair 0:f269e3021894 215 for process in git_processes :
elessair 0:f269e3021894 216 process.wait()