def main(): args = parse_args() headers = fileCollection.getHeaderFiles(args.src) for head in headers: try: cppHeader = CppHeaderParser.CppHeader(head) except CppHeaderParser.CppParseError as e: print(e) sys.exit(1) print CT.boldBlack("Class public methods") if(len(cppHeader.classes) + len(cppHeader.functions) > 0): testerCppPath = os.path.join(args.outDir,head.replace(".hpp", "Tester.cpp")) mkdir_p_forFile(testerCppPath) if os.path.exists(testerCppPath): if args.overWrite: os.remove(testerCppPath) else: print "Skipping", testerCppPath, "it already exist, use --overWrite to replace" continue with open(testerCppPath, "w") as testerFile: testerFile.write("#include <catch.hpp>\n") testerFile.write("#include \"" + "../" + head + "\"\n") for func in cppHeader.functions: testerFile.write(testerBodyTemplate.format(REPLACETHIS=func["name"], REPLACETHIS_DETAILED = getFuncDetailed(func))) for k in cppHeader.classes.keys(): for i in range(len(cppHeader.classes[k]["methods"]["public"])): testerFile.write(testerBodyTemplate.format(REPLACETHIS=cppHeader.classes[k]["methods"]["public"][i]["name"], REPLACETHIS_DETAILED = getFuncDetailed(cppHeader.classes[k]["methods"]["public"][i]))) createTestMain(os.path.join(args.outDir, args.src), args.overWrite) copyMakefile("scripts/cppSetUpFiles/unitTest/Makefile", os.path.join(args.outDir, "Makefile"), args.overWrite) return 0
def main(): args = parse_args() try: cppHeader = CppHeaderParser.CppHeader(args.file) except CppHeaderParser.CppParseError as e: print(e) sys.exit(1) print(CT.boldBlack("Class public methods")) for k in list(cppHeader.classes.keys()): print(CT.boldBlack(k)) for i in range(len(cppHeader.classes[k]["methods"]["public"])): print("\t", cppHeader.classes[k]["methods"]["public"][i]["name"]) print("") print(CT.boldBlack("Includes")) for include in cppHeader.includes: if "//" in include: print("\t" + include[0:include.find("//")].strip()) elif "/*" in include: print("\t" + include[0:include.find("/*")].strip()) else: print("\t" + include) print(("\n" + CT.boldBlack("Free functions are:"))) for func in cppHeader.functions: print(("\t%s" % func["name"]))
def main(): args = parse_args() projectOut = os.path.join(args.dest[0], args.projName[0]) os.mkdir(projectOut) genSrc(projectOut, args.projName[0], ["iostream", "string", "unistd.h", "vector", "cstdint", "cstdio", "cstddef", "utility", "map", "unordered_map", "algorithm"]) CC = genHelper.determineCC(args) CXX = genHelper.determineCXX(args) external = "external" outname = args.projName[0] prefix = "./" installName = args.projName[0] neededLibs = "none" if args.externalLoc: external = os.path.realpath(args.externalLoc[0]) if args.neededLibs: neededLibs = args.neededLibs[0].split(",") genHelper.generateCompfileFull(os.path.join(projectOut, "compfile.mk"), external, CC, CXX, outname, installName, prefix, neededLibs) with open(os.path.join(projectOut, "configure.py"), "w") as configFile: if(args.neededLibs): configFile.write(genHelper.mkConfigFileStr(outname, args.neededLibs[0])) else: configFile.write(genHelper.mkConfigFileStr(outname, "")) os.chmod(os.path.join(projectOut, "configure.py"), stat.S_IXGRP | stat.S_IXOTH | stat.S_IXUSR | stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH | stat.S_IWUSR) exFrom = os.path.abspath(os.path.dirname(__file__)) cpSetUpCmd = exFrom + "/copySetUpFiles.py -from " + exFrom +"/../../ -to " + projectOut print CT.boldBlack(cpSetUpCmd) Utils.run(cpSetUpCmd) cpMakefilesCmd = "cp " + exFrom + "/../cppSetUpFiles/*akefile* " + projectOut print CT.boldBlack(cpMakefilesCmd) Utils.run(cpMakefilesCmd)
def main(): args = parse_args() try: cppHeader = CppHeaderParser.CppHeader(args.file) except CppHeaderParser.CppParseError as e: print(e) sys.exit(1) print(CT.boldBlack("Class public methods")) for k in list(cppHeader.classes.keys()): print(CT.boldBlack(k)) for i in range(len(cppHeader.classes[k]["methods"]["public"])): print("\t",cppHeader.classes[k]["methods"]["public"][i]["name"]) print("") print(CT.boldBlack("Includes")) for include in cppHeader.includes: if "//" in include: print("\t" + include[0:include.find("//")].strip()) elif "/*" in include: print("\t" + include[0:include.find("/*")].strip()) else: print("\t" + include) print(("\n" + CT.boldBlack("Free functions are:"))) for func in cppHeader.functions: print(("\t%s"%func["name"]))
def subscribe(cls, topic, callback, use_prefix=True): topic = MQTT.prefix(topic, use_prefix) ct.print_debug("subscribing topic {}".format(topic)) subscription = cls.subscriptions.get(topic, None) # if we allready are subscribed to this, just add another callback if subscription is not None: callbacks = subscription["callbacks"] if callback in callbacks: ct.print_warning( "Callback allready exists for this topic, doing nothing") else: ct.print_debug( "adding callback to existing subscription {}".format( topic)) subscription["callbacks"].append(callback) return subscription cls.subscriptions[topic] = {"topic": topic, "callbacks": [callback]} ct.print_info("Added subscription for {}".format(topic)) if cls.connected: try: print("~~~ MQTT subscribe on {0}".format(topic)) cls.client.subscribe(topic) except Exception as e: ct.format_exception(e, "subscription failed") cls.set_connected(False) return subscription
def on_input_change(self, signal): if signal == self.start_conversion and self.countdown <= 0: self.countdown = 750 self.interval = -1 Component.scheduler.register(self) self.stable.value = False self.ds.convert_temp() ct.print_debug("converting temperatures")
def start(self, interval_ms): interval_ms = int(interval_ms) self.interval = interval_ms try: self.timer = Timer(-1) self.timer.init(period=interval_ms, mode=Timer.PERIODIC, callback=self.tick) except Exception as e: ct.format_exception(e, "could not initialize timer")
def __setValue(self, val): # no change, no None self.last_value = self.__value if self.__value != val: self.__value = val if self.fanouts: ct.print_debug("setting {} from {} to {}".format(self.name, self.last_value, val)) self.notify_fanouts()
def copyMakefile(self, distDir, overWrite=False): distDir = os.path.join(self.projectDir, distDir) if not os.path.exists(distDir): print(CT.boldGreen(distDir) + CT.boldRed(" doesn't exist skipping")) return if os.path.exists(os.path.join(distDir, "Makefile")) and not overWrite: raise Exception("Error, file " + os.path.join(distDir, "Makefile") + " already exist, use --overWrite overwrite Makefile") shutil.copy(os.path.join(self.setupFrom, "scripts/cppMakefiles/Makefile"), os.path.join(distDir, "Makefile"))
def eval(self): try: val = eval(self.python, self.expr_globals, self.expr_locals) except Exception as e: ct.format_exception(e, "evaluation of expression failed") ct.print_error(str(self.python)) val = 0 self.output.value = val
def on_connect(cls): print("o-o MQTT connected") for topic in cls.subscriptions: ct.print_info("~~~ MQTT subscribe on {0}".format(topic)) try: cls.client.subscribe(topic) except: cls.set_connected(False)
def copySetUp(self, distDir, overWrite=False): if not os.path.exists(distDir): print(CT.boldGreen(distDir) + CT.boldRed(" doesn't exist skipping")) return if os.path.exists(os.path.join(distDir, "setup.py")) and not overWrite: raise Exception("Error, file " + os.path.join(distDir, "setup.py") + " already exist, use --overWrite overwrite setup.py") shutil.copy(os.path.join(self.setupFrom, "setup.py"), os.path.join(distDir, "setup.py")) self.copyDir(os.path.join(self.setupFrom ,"scripts"), os.path.join(distDir,"scripts"), overWrite)
def __init__(self, result_name, expression_string): self.set_name(result_name) matches = Expression.name_re.match(expression_string) self.expr_locals = {} self.python = Expression.name_re.sub(self._replace_in_expr, expression_string) ct.print_info("Expression = {}".format(self.python)) out = Signal.get_by_name(self.name, self) setattr(self, "output", out)
def rmDirsForLib(self,lib): if lib not in self.setUps: print CT.boldBlack( "Unrecognized lib: ") + CT.boldRed(lib) else: p = self.__path(lib) if p.build_dir: print "Removing " + CT.boldBlack(p.build_dir) Utils.rm_rf(p.build_dir) if p.local_dir: print "Removing " + CT.boldBlack(p.local_dir) Utils.rm_rf(p.local_dir)
def main(): args = parse_args() externalIncludes = [] stdLibraryInc = [ "iostream", "string", "unistd.h", "vector", "cstdint", "cstdio", "cstddef", "utility", "map", "unordered_map", "algorithm" ] projectOut = os.path.join(args.dest[0], args.projName[0]) os.mkdir(projectOut) if args.programType == "singleRing": genSrcSingleRingProgram(projectOut, args.projName[0], stdLibraryInc, externalIncludes, args.author) elif args.programType == "oneRing": genSrcWithOneRingProgram(projectOut, args.projName[0], stdLibraryInc, externalIncludes, args.author) elif args.programType == "oneCmd": genSrcWithOneCmdProgram(projectOut, args.projName[0], stdLibraryInc, externalIncludes, args.author) else: raise Exception( "Error, only singleRing, oneRing,oneCmd available for options to programType, was given " + args.programType) CC = genHelper.determineCC(args) CXX = genHelper.determineCXX(args) external = "external" outname = args.projName[0] prefix = "./" installName = args.projName[0] neededLibs = ["bibcppdev"] if args.externalLoc: external = os.path.realpath(args.externalLoc[0]) if args.neededLibs: neededLibs = ["bibcppdev"] + args.neededLibs[0].split(",") genHelper.generateCompfileFull(os.path.join(projectOut, "compfile.mk"), external, CC, CXX, outname, installName, prefix, neededLibs) with open(os.path.join(projectOut, "configure.py"), "w") as configFile: if (args.neededLibs): configFile.write( genHelper.mkConfigFileStr(outname, ",".join(neededLibs))) else: configFile.write(genHelper.mkConfigFileStr(outname, "bibcppdev")) os.chmod( os.path.join(projectOut, "configure.py"), stat.S_IXGRP | stat.S_IXOTH | stat.S_IXUSR | stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH | stat.S_IWUSR) exFrom = os.path.abspath(os.path.dirname(__file__)) cpSetUpCmd = exFrom + "/copySetUpFiles.py -from " + exFrom + "/../../ -to " + projectOut print CT.boldBlack(cpSetUpCmd) Utils.run(cpSetUpCmd) cpMakefilesCmd = "cp " + exFrom + "/../cppSetUpFiles/*akefile* " + projectOut print CT.boldBlack(cpMakefilesCmd) Utils.run(cpMakefilesCmd)
def installRPackageName(self, packageName): i = self.__path("r") for pack in packageName.split(","): if isMac(): cmd = """echo 'install.packages(c(\"{PACKAGENAME}\"), repos=\"http://cran.us.r-project.org\")' | $({local_dir}/R.framework/Resources/bin/R RHOME)/bin/R --slave --vanilla """.format(local_dir=shellquote(i.local_dir).replace(' ', '\ '), PACKAGENAME = pack ) else: cmd = """echo 'install.packages(\"{PACKAGENAME}\", repos=\"http://cran.us.r-project.org\")' | $({local_dir}/bin/R RHOME)/bin/R --slave --vanilla """.format(local_dir=shellquote(i.local_dir).replace(' ', '\ '),PACKAGENAME = pack ) print CT.boldBlack(cmd) cmd = " ".join(cmd.split()) Utils.run(cmd)
def installRPackageSource(self, sourceFile): i = self.__path("r") for pack in sourceFile.split(","): if isMac(): cmd = """echo 'install.packages(\"{SOURCEFILE}\", repos = NULL, type="source")' | $({local_dir}/R.framework/Resources/bin/R RHOME)/bin/R --slave --vanilla """.format(local_dir=shellquote(i.local_dir).replace(' ', '\ '),SOURCEFILE = pack ) else: cmd = """echo 'install.packages(\"{SOURCEFILE}\", repos = NULL, type="source")' | $({local_dir}/bin/R RHOME)/bin/R --slave --vanilla """.format(local_dir=shellquote(i.local_dir).replace(' ', '\ '),SOURCEFILE = pack ) print CT.boldBlack(cmd) cmd = " ".join(cmd.split()) Utils.run(cmd)
def genCppProject(args): projectOut = os.path.join(args.dest, args.projName) if os.path.exists(projectOut): if args.overwrite: shutil.rmtree(projectOut) else: raise Exception("Directory " + str(projectOut) + " already exists, use --overWrite to delete") #create project dir os.mkdir(projectOut) #generate skeleton source code directory genSrc(projectOut, args.projName, [ "iostream", "string", "unistd.h", "vector", "cstdint", "cstdio", "cstddef", "utility", "map", "unordered_map", "algorithm" ]) #determine c++ and c compilers CC = genHelper.determineCC(args) CXX = genHelper.determineCXX(args) external = "external" outname = args.projName prefix = "./" installName = args.projName neededLibs = "none" if args.externalLoc: external = os.path.realpath(args.externalLoc) if args.neededLibs: neededLibs = args.neededLibs.split(",") #generate the compfile genHelper.generateCompfileFull(os.path.join(projectOut, "compfile.mk"), external, CC, CXX, outname, installName, prefix, neededLibs) #generate config file with open(os.path.join(projectOut, "configure.py"), "w") as configFile: if args.neededLibs: configFile.write( genHelper.mkConfigFileStr(outname, args.neededLibs)) else: configFile.write(genHelper.mkConfigFileStr(outname, "")) #make executable os.chmod( os.path.join(projectOut, "configure.py"), stat.S_IXGRP | stat.S_IXOTH | stat.S_IXUSR | stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH | stat.S_IWUSR) #determine this file's location to dtermine where to copy setup and make files to exFrom = os.path.abspath(os.path.dirname(__file__)) cpSetUpCmd = exFrom + "/copySetUpFiles.py -from " + exFrom + "/../../ -to " + projectOut print CT.boldBlack(cpSetUpCmd) Utils.run(cpSetUpCmd) cpMakefilesCmd = "cp " + exFrom + "/../cppMakefiles/Makefile " + projectOut print CT.boldBlack(cpMakefilesCmd) Utils.run(cpMakefilesCmd) #generate README.md genReadme(projectOut, args.projName)
def __setup(self, name, builder_f): if os.path.exists(self.__path(name).local_dir): print name, CT.boldGreen("found at ") + CT.boldBlack(self.__path(name).local_dir) else: print name, CT.boldRed("NOT"), "found; building..." try: builder_f() self.installed.append(name) except Exception as inst: print type(inst) print inst print "failed to install " + name self.failedInstall.append(name)
def copySetUp(self, distDir, overWrite=False): if not os.path.exists(distDir): print( CT.boldGreen(distDir) + CT.boldRed(" doesn't exist skipping")) return if os.path.exists(os.path.join(distDir, "setup.py")) and not overWrite: raise Exception( "Error, file " + os.path.join(distDir, "setup.py") + " already exist, use --overWrite overwrite setup.py") shutil.copy(os.path.join(self.setupFrom, "setup.py"), os.path.join(distDir, "setup.py")) self.copyDir(os.path.join(self.setupFrom, "scripts"), os.path.join(distDir, "scripts"), overWrite)
def read_temp(self, ds): ct.print_debug("reading temperatures from {} for {}".format( self.hex_address(), self.signal.name)) temperature = -272.0 try: temperature = ds.read_temp(self.address) if self.signal is not None: self.signal.value = round(temperature, 2) except Exception as e: ct.format_exception( e, "Exception in ds18x20 update for {}".format(self.signal.name)) return temperature
def copyMakefile(self, distDir, overWrite=False): distDir = os.path.join(self.projectDir, distDir) if not os.path.exists(distDir): print( CT.boldGreen(distDir) + CT.boldRed(" doesn't exist skipping")) return if os.path.exists(os.path.join(distDir, "Makefile")) and not overWrite: raise Exception( "Error, file " + os.path.join(distDir, "Makefile") + " already exist, use --overWrite overwrite Makefile") shutil.copy( os.path.join(self.setupFrom, "scripts/cppMakefiles/Makefile"), os.path.join(distDir, "Makefile"))
def init_ports_from_dict(self, config, names_and_constraints, signal_creation_method, check_mandatory = True): for name in names_and_constraints: (default, minimum, maximum) = names_and_constraints[name] ct.print_debug("{} {} {} {}".format(name, default, minimum, maximum)) line_config = config.pop(name, None) if line_config is None: if default is None: assert not check_mandatory, "mandatory port {} missing".format(name) sig = None else: sig = Signal.constant(default, self) else: sig = signal_creation_method(line_config, self, name) setattr(self, name, sig)
def untar(fnp, d): ''' un pack compressed file, guessing format based on extention ''' if fnp.endswith(".tar.gz"): tar = tarfile.open(fnp, "r:gz") elif fnp.endswith(".tgz"): tar = tarfile.open(fnp, "r:gz") elif fnp.endswith(".tar.bz2"): tar = tarfile.open(fnp, "r:bz2") elif fnp.endswith(".tar"): tar = tarfile.open(fnp, "r") else: raise Exception("invalid file? " + fnp) print "untarring", CT.boldGreen(fnp), "to", CT.boldBlue(d) tar.extractall(d) tar.close()
def subscribe_expression(cls, expression, callback): ct.print_debug("Checkpoint MQTT 0") expr = Expression(expression) ct.print_debug(expr) ct.print_debug("Checkpoint MQTT 1") expr.subscribe(callback) ct.print_debug("Checkpoint MQTT 2") return expr
def untar(fnp, d): """ un pack compressed file, guessing format based on extention """ if fnp.endswith(".tar.gz"): tar = tarfile.open(fnp, "r:gz") elif fnp.endswith(".tgz"): tar = tarfile.open(fnp, "r:gz") elif fnp.endswith(".tar.bz2"): tar = tarfile.open(fnp, "r:bz2") elif fnp.endswith(".tar"): tar = tarfile.open(fnp, "r") else: raise Exception("invalid file? " + fnp) print "untarring", CT.boldGreen(fnp), "to", CT.boldBlue(d) tar.extractall(d) tar.close()
def on_input_change(self, signal): ct.print_debug("updating dff for signal {} with value {}".format( signal.name, signal.value)) if self.reset.value >= 0.5: self.output.value = 0 return if self.set.value >= 0.5: self.output.value = 1 return if self.enable.value < 0.5: return if (signal is self.strobe and signal.has_changed()): self.output.value = self.input.value
def get_file_if_size_diff(url, d): '''only download the file if it's needed, not completely fail proof since it is just a size check but fairly likely not to be the same for a difference ''' fn = url.split('/')[-1] out_fnp = os.path.join(d, fn) net_file_size = int(urllib.urlopen(url).info()['Content-Length']) if os.path.exists(out_fnp): fn_size = os.path.getsize(out_fnp) if fn_size == net_file_size: print "skipping download of", CT.boldGreen(fn) return out_fnp else: print "files sizes differed:", "on disk:", fn_size, "from net:", net_file_size print "retrieving", CT.boldGreen(fn), "from", CT.boldBlue(url) urllib.urlretrieve(url, out_fnp) return out_fnp
def get_file_if_size_diff(url, d): """only download the file if it's needed, not completely fail proof since it is just a size check but fairly likely not to be the same for a difference """ fn = url.split("/")[-1] out_fnp = os.path.join(d, fn) net_file_size = int(urllib.urlopen(url).info()["Content-Length"]) if os.path.exists(out_fnp): fn_size = os.path.getsize(out_fnp) if fn_size == net_file_size: print "skipping download of", CT.boldGreen(fn) return out_fnp else: print "files sizes differed:", "on disk:", fn_size, "from net:", net_file_size print "retrieving", CT.boldGreen(fn), "from", CT.boldBlue(url) urllib.urlretrieve(url, out_fnp) return out_fnp
def genHellos(outFilename, overWrite = False, python = False): if python: if not outFilename.endswith(".py"): outFilename = outFilename + ".py" if os.path.exists(outFilename) and not overWrite: raise Exception(CT.boldRed("File ") + CT.boldBlack(outFilename) + CT.boldRed(" already exists, use --overWrite to over write it")) genPyHello(outFilename) #rwx to user and group, r-x to everyone fd = os.open( outFilename, os.O_RDONLY ) os.fchmod( fd, 0775) os.close( fd ) print (CT.boldGreen("Now run")) print ("./" + outFilename + " ") print (CT.boldGreen("or")) print ("./" + outFilename + " --name Nick") else: if not outFilename.endswith(".cpp"): outFilename = outFilename + ".cpp" if os.path.exists(outFilename) and not overWrite: raise Exception("File " + outFilename + " already exists, use --overWrite to over write it") genCppHello(outFilename) print (CT.boldGreen("Now run")) print ("g++ -std=c++11 " + outFilename + " -o hello #-std=c++11 needed for cstdint include in libstdc++") print ("./hello") print (CT.boldGreen("or run")) #mac if Utils.isMac(): print ("clang++ " + outFilename + " -o hello") else: print ("clang++-3.6 -std=c++11 " + outFilename + " -o hello #-std=c++11 needed for cstdint include in libstdc++") print ("./hello")
def genHellos(outFilename, overWrite = False, python = False): if python: if not outFilename.endswith(".py"): outFilename = outFilename + ".py" if os.path.exists(outFilename) and not overWrite: raise Exception(CT.boldRed("File ") + CT.boldBlack(outFilename) + CT.boldRed(" already exists, use --overWrite to over write it")) genPyHello(outFilename) #rwx to user and group, r-x to everyone fd = os.open( outFilename, os.O_RDONLY ) os.fchmod( fd, 0o775) os.close( fd ) print((CT.boldGreen("Now run"))) print(("./" + outFilename + " ")) print((CT.boldGreen("or"))) print(("./" + outFilename + " --name Nick")) else: if not outFilename.endswith(".cpp"): outFilename = outFilename + ".cpp" if os.path.exists(outFilename) and not overWrite: raise Exception("File " + outFilename + " already exists, use --overWrite to over write it") genCppHello(outFilename) print((CT.boldGreen("Now run"))) print(("g++ -std=c++11 " + outFilename + " -o hello #-std=c++11 needed for cstdint include in libstdc++")) print ("./hello") print((CT.boldGreen("or run"))) #mac if Utils.isMac(): print(("clang++ " + outFilename + " -o hello")) else: print(("clang++-3.6 -std=c++11 " + outFilename + " -o hello #-std=c++11 needed for cstdint include in libstdc++")) print ("./hello")
def on_input_change(self, signal): ct.print_debug("updating counter for signal {} with value {}".format( signal.name, signal.value)) if self.enable.value < 0.5: return if signal.has_changed(): if signal is self.down: self.output.value = self.reload_value.value if self.output.value <= 0 else self.output.value - self.decrement.value return if signal is self.up: self.output.value += self.increment.value return if signal is self.load: self.output.value = self.load_value.value return
def main(): args = parse_args() headers = fileCollection.getHeaderFiles(args.src) for head in headers: try: cppHeader = CppHeaderParser.CppHeader(head) except CppHeaderParser.CppParseError as e: print(e) sys.exit(1) print CT.boldBlack("Class public methods") if (len(cppHeader.classes) + len(cppHeader.functions) > 0): testerCppPath = os.path.join(args.outDir, head.replace(".hpp", "Tester.cpp")) mkdir_p_forFile(testerCppPath) if os.path.exists(testerCppPath): if args.overWrite: os.remove(testerCppPath) else: print "Skipping", testerCppPath, "it already exist, use --overWrite to replace" continue with open(testerCppPath, "w") as testerFile: testerFile.write("#include <catch.hpp>\n") testerFile.write("#include \"" + "../" + head + "\"\n") for func in cppHeader.functions: testerFile.write( testerBodyTemplate.format( REPLACETHIS=func["name"], REPLACETHIS_DETAILED=getFuncDetailed(func))) for k in cppHeader.classes.keys(): for i in range( len(cppHeader.classes[k]["methods"]["public"])): testerFile.write( testerBodyTemplate.format( REPLACETHIS=cppHeader.classes[k]["methods"] ["public"][i]["name"], REPLACETHIS_DETAILED=getFuncDetailed( cppHeader.classes[k]["methods"]["public"] [i]))) createTestMain(os.path.join(args.outDir, args.src), args.overWrite) copyMakefile("scripts/cppMakefiles/unitTest/Makefile", os.path.join(args.outDir, "Makefile"), args.overWrite) return 0
def genCppProject(args): projectOut = os.path.join(args.dest, args.projName) if os.path.exists(projectOut): if args.overwrite: shutil.rmtree(projectOut) else: raise Exception("Directory " + str(projectOut) + " already exists, use --overWrite to delete") #create project dir os.mkdir(projectOut) #generate skeleton source code directory genSrc(projectOut, args.projName, ["iostream", "string", "unistd.h", "vector", "cstdint", "cstdio", "cstddef", "utility", "map", "unordered_map", "algorithm"]) #determine c++ and c compilers CC = genHelper.determineCC(args) CXX = genHelper.determineCXX(args) external = "external" outname = args.projName prefix = "./" installName = args.projName neededLibs = "none" if args.externalLoc: external = os.path.realpath(args.externalLoc) if args.neededLibs: neededLibs = args.neededLibs.split(",") #generate the compfile genHelper.generateCompfileFull(os.path.join(projectOut, "compfile.mk"), external, CC, CXX, outname, installName, prefix, neededLibs) #generate config file with open(os.path.join(projectOut, "configure.py"), "w") as configFile: if args.neededLibs: configFile.write(genHelper.mkConfigFileStr(outname, args.neededLibs)) else: configFile.write(genHelper.mkConfigFileStr(outname, "")) #make executable os.chmod(os.path.join(projectOut, "configure.py"), stat.S_IXGRP | stat.S_IXOTH | stat.S_IXUSR | stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH | stat.S_IWUSR) #determine this file's location to dtermine where to copy setup and make files to exFrom = os.path.abspath(os.path.dirname(__file__)) cpSetUpCmd = exFrom + "/copySetUpFiles.py -from " + exFrom + "/../../ -to " + projectOut print CT.boldBlack(cpSetUpCmd) Utils.run(cpSetUpCmd) cpMakefilesCmd = "cp " + exFrom + "/../cppMakefiles/Makefile " + projectOut print CT.boldBlack(cpMakefilesCmd) Utils.run(cpMakefilesCmd) #generate README.md genReadme(projectOut, args.projName)
def on_mqtt(self, topic, data): mine_before = self.mine self.set_data(data) self.write_cache(data) #comparing jsons is not reliable because the ordering of elements can change. #Therefore we just compare the date the config was published if (mine_before is None) or (self.mine is None): same_date = False else: same_date = (mine_before["published"] == self.mine["published"]) if not same_date: ct.print_warning("Config changed, rebooting") # My config has changed. Reboot. sync() machine.reset() ct.print_info("Received config with identical date {}".format( self.mine["published"]))
def parseForHeaders(args): headers = set() unknowns = [] for arg in args: if arg in objToHeader: headers.add(objToHeader[arg]) elif ("std::" + arg) in objToHeader: headers.add(objToHeader["std::" + arg]) else: unknowns.append(arg) print(CT.boldRed("Unknowns:")) for u in unknowns: print(CT.boldBlack("unknown which header file contains"), CT.boldRed(u)) if headers: print(CT.boldGreen("found headers:")) for h in sorted(headers): print(h)
def __init__(self, board, network, scheduler): self.board = board self.scheduler = scheduler self.parts_initialized = False self.mac = network.mac self.data = {} self.mine = None self.version = "0.8.0" self.listeners = [] self.read_cache() # if (type(self.mine) is dict and "parts" in self.mine): # ct.print_heading("initializing from cache") # Part.init_parts(board, scheduler, self.mine["parts"]) Component.setup_services(board, scheduler) if (type(self.mine) is dict and "components" in self.mine): ct.print_heading("initializing from cache") Component.netlist_from_config(self.mine["components"]) Component.print_netlist() MQTT.subscribe(config_topic_base + self.mac + "/config", self.on_mqtt)
def main(): args = parse_args() externalIncludes = [] stdLibraryInc = ["iostream", "string", "unistd.h", "vector", "cstdint", "cstdio", "cstddef", "utility", "map", "unordered_map", "algorithm"] projectOut = os.path.join(args.dest[0], args.projName[0]) os.mkdir(projectOut) if args.programType == "singleRing": genSrcSingleRingProgram(projectOut, args.projName[0], stdLibraryInc, externalIncludes, args.author) elif args.programType == "oneRing": genSrcWithOneRingProgram(projectOut, args.projName[0], stdLibraryInc, externalIncludes, args.author) elif args.programType == "oneCmd": genSrcWithOneCmdProgram(projectOut, args.projName[0], stdLibraryInc, externalIncludes, args.author) else: raise Exception("Error, only singleRing, oneRing,oneCmd available for options to programType, was given " + args.programType ) CC = genHelper.determineCC(args) CXX = genHelper.determineCXX(args) external = "external" outname = args.projName[0] prefix = "./" installName = args.projName[0] neededLibs = ["njhcppdev"] if args.externalLoc: external = os.path.realpath(args.externalLoc[0]) if args.neededLibs: neededLibs = ["njhcppdev"] + args.neededLibs[0].split(",") genHelper.generateCompfileFull(os.path.join(projectOut, "compfile.mk"), external, CC, CXX, outname, installName, prefix, neededLibs) with open(os.path.join(projectOut, "configure.py"), "w") as configFile: if(args.neededLibs): configFile.write(genHelper.mkConfigFileStr(outname, ",".join(neededLibs))) else: configFile.write(genHelper.mkConfigFileStr(outname, "njhcppdev")) os.chmod(os.path.join(projectOut, "configure.py"), stat.S_IXGRP | stat.S_IXOTH | stat.S_IXUSR | stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH | stat.S_IWUSR) exFrom = os.path.abspath(os.path.dirname(__file__)) cpSetUpCmd = exFrom + "/copySetUpFiles.py -from " + exFrom +"/../../ -to " + projectOut print CT.boldBlack(cpSetUpCmd) Utils.run(cpSetUpCmd) cpMakefilesCmd = "cp " + exFrom + "/../cppSetUpFiles/*akefile* " + projectOut print CT.boldBlack(cpMakefilesCmd) Utils.run(cpMakefilesCmd)
def init_name(self, config): self.pin = Component.board.get_pin(self.name) self.ds = DS18X20(OneWire(self.pin)) addresses = self.ds.scan() self.sensors = [] read_all_sensors = ("ids" in config) or ("temperatures" in config) for address in addresses: hex_address = Sensor.to_hex_address(address) signal_name = None if hex_address in config: sensor = Sensor(address, self, config.pop(hex_address)) self.sensors.append(sensor) elif read_all_sensors: sensor = Sensor(address, self, None) self.sensors.append(sensor) ct.print_info("Found {} DS18x20 sensors.".format(len(self.sensors))) ct.print_debug("\n".join(str(x) for x in self.sensors)) self.countdown = self.interval = -1
def main(): args = parse_args() s = Setup(args) ccWhich = Utils.which(s.CC) cxxWhich = Utils.which(s.CXX) cmakeWhich = Utils.which("cmake") if not ccWhich or not cxxWhich or not cmakeWhich: if not ccWhich: print CT.boldRed("Could not find c compiler " + CT.purple + s.CC) if args.compfile: print "Change CC in " + args.compfile else: print "Can supply another c compiler by using -CC [option] or by defining bash environmental CC " print "" if not cxxWhich: print CT.boldRed("Could not find c++ compiler " + CT.purple + s.CXX) if args.compfile: print "Change CXX in " + args.compfile else: print "Can supply another c++ compiler by using -CXX [option] or by defining bash environmental CXX " print "" if not cmakeWhich: print CT.boldRed("Could not find " + CT.purple + "cmake") if Utils.isMac(): print "If you have brew install via, brew update && brew install cmake, otherwise you can follow instructions from http://www.cmake.org/install/" else: print "On ubuntu to install latest cmake do the following" print "sudo add-apt-repository ppa:george-edison55/cmake-3.x" print "sudo apt-get update" print "sudo apt-get install cmake" return 1 if(args.instRPackageName): s.installRPackageName(args.instRPackageName[0]) return 0 if(args.instRPackageSource): s.installRPackageSource(args.instRPackageSource[0]) return 0 if args.updateBibProjects: projectsSplit = args.updateBibProjects.split(",") s.updateBibProjects(projectsSplit) return 0 if args.printLibs: s.printAvailableSetUps() elif args.addBashCompletion: if(os.path.isdir("./bashCompletes")): cmd = "cat bashCompletes/* >> ~/.bash_completion" Utils.run(cmd) if(os.path.isdir("./bash_completion.d")): cmd = "cat bash_completion.d/* >> ~/.bash_completion" Utils.run(cmd) else: if len(s.setUpsNeeded) == 0: s.printAvailableSetUps() return 1 else: s.setup() return 0
def setup(self): if self.args.forceUpdate: for set in self.setUpsNeeded.keys(): if not set in self.setUps.keys(): print CT.boldBlack( "Unrecognized option ") + CT.boldRed(set) else: self.rmDirsForLib(set) for set in self.setUpsNeeded.keys(): if not set in self.setUps.keys(): print CT.boldBlack( "Unrecognized option ") + CT.boldRed(set) else: self.__setup(set, self.setUps[set]) for p in self.installed: print p, CT.boldGreen("installed") for p in self.failedInstall: print p, CT.boldRed("failed to install")
def _replace_in_expr(self, match): name = match.group(0) ct.print_debug("processing match {}".format(name)) if name in Expression.expr_globals: ct.print_debug("ignoring global function name: {}".format(name)) return name if name in dir(builtins): ct.print_debug("ignoring builtin name: {}".format(name)) return name if name in Expression.keywords: ct.print_debug("ignoring keyword: {}".format(name)) return name assert name not in Expression.reserved_names, "reserved names can't be used in expressions: {}".format(name) sig = Signal.get_by_name(name, None) sig.add_fanout(self) setattr(self, name, sig) self.expr_locals[name] = sig return '{}.value'.format(name)
def main(): args = parse_args() try: cppHeader = CppHeaderParser.CppHeader(args.file) except CppHeaderParser.CppParseError as e: print(e) sys.exit(1) print CT.boldBlack("Class public methods") for k in cppHeader.classes.keys(): print CT.boldBlack(k) for i in range(len(cppHeader.classes[k]["methods"]["public"])): print "\t",cppHeader.classes[k]["methods"]["public"][i]["name"] print "" print CT.boldBlack("Includes") for include in cppHeader.includes: print "\t",include print("\n" + CT.boldBlack("Free functions are:")) for func in cppHeader.functions: print("\t%s"%func["name"])
def create_by_input_string(cls, input_string, component, port): ct.print_debug("analyzing signal assignment {} of type {}".format(input_string, type(input_string))) if not isinstance(input_string, str): ct.print_debug("creating constant") return cls.constant(input_string, component) match = Expression.name_re.match(input_string) # a simple case is a direct assignment of a signal if match is not None and match.group(0) == input_string: ct.print_debug("direct assignment") sig = cls.get_by_name(input_string) sig.add_fanout(component) return sig #otherwise we create an Expression component signal_name = ("_".join((component.name, port))) expr = Expression(signal_name, input_string) Component.by_name[signal_name] = expr expr.output.add_fanout(component) return expr.output
def run_in_dir(cmd, d): # print CT.boldBlack("here") cmd = "cd " + Utils.shellquote(d) + " && " + cmd + " && cd -" # print CT.boldBlack("newcmd") print CT.boldGreen(cmd) Utils.run(cmd)
def update(self, scheduler): ct.print_debug("reading temperatures from pin {}".format(self.name)) # We've waited enough for the sensor(s). Read the temperatures. self.temperatures.value = [s.read_temp(self.ds) for s in self.sensors] self.stable.value = True self.temperatures.notify_fanouts()
def rm_rf(d): """remove directory forcibly""" if os.path.exists(d): print CT.boldText("rm -rf"), CT.boldRed(d) shutil.rmtree(d)
def __init__(self, address, component, signal_name): self.address = address if signal_name is not None: ct.print_debug("mapped sensor {} to {}".format( self.hex_address(), signal_name)) self.signal = Signal.get_by_name(signal_name, component)
def mkdir(d): """mkdir if it doesn't already exist """ if not os.path.exists(d): print CT.boldText("mkdir"), CT.boldGreen(d) os.makedirs(d)
def mkdir(d): '''mkdir if it doesn't already exist ''' if not os.path.exists(d): print(CT.boldText("mkdir"), CT.boldGreen(d)) os.makedirs(d)
def callback(self, topic, msg): ct.print_debug("received topic={}, msg={}".format(topic, msg)) self.output.value = msg self.strobe.value += 1
def rm_rf(d): '''remove directory forcibly''' if os.path.exists(d): print(CT.boldText("rm -rf"), CT.boldRed(d)) shutil.rmtree(d)