From 5efa5d47d319c9832fb4aa5c2b3d7604d3ae9c44 Mon Sep 17 00:00:00 2001 From: Sean Vig Date: Sun, 4 Oct 2015 13:24:59 -0500 Subject: [PATCH 01/21] Use Python 2/3 compatible scripts Almost entirely fixing print statements, but also a couple importing changes, wrapped in try/excepts, and one case where dict.keys() not being a list would be a problem. Also reverts e41139a397f0905f6db96caee693896887f896f7 The real fix for #1907 --- radio/util/add-issue-links.py | 3 ++- radio/util/addtr.py | 6 +++-- radio/util/codecs.py | 6 +++-- radio/util/copyright.py | 8 ++++--- radio/util/dsm2.py | 8 ++++--- radio/util/fat12.py | 14 +++++++----- radio/util/img2lbm.py | 9 ++++---- radio/util/include-guard.py | 4 +++- radio/util/luaexport.py | 27 ++++++++++++----------- radio/util/parse.py | 8 ++++--- radio/util/sinus.py | 12 +++++----- radio/util/sport-parse.py | 41 ++++++++++++++++++----------------- radio/util/translate.py | 2 +- radio/util/tts.py | 27 ++++++++++++++++------- 14 files changed, 103 insertions(+), 72 deletions(-) diff --git a/radio/util/add-issue-links.py b/radio/util/add-issue-links.py index e66ad56a7..d2682bce3 100755 --- a/radio/util/add-issue-links.py +++ b/radio/util/add-issue-links.py @@ -1,6 +1,7 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- +from __future__ import print_function import sys import os @@ -43,7 +44,7 @@ while True: links = "(" + ", ".join(issue_links) + ")" line = "
  • " + line + " " + links + "
  • " - print line + print(line) inp.close() diff --git a/radio/util/addtr.py b/radio/util/addtr.py index 3a3b30e52..4794b8905 100755 --- a/radio/util/addtr.py +++ b/radio/util/addtr.py @@ -1,9 +1,11 @@ #!/bin/env python +from __future__ import print_function + import sys, glob def addLine(filename, newline, after): - print filename, newline + print(filename, newline) lines = file(filename, 'r').readlines() for i, line in enumerate(lines): if after in line: @@ -14,7 +16,7 @@ def addLine(filename, newline, after): def modifyTranslations(constant, translation, after): for filename in glob.glob('translations/*.h.txt'): newline = "#define " + constant + " "*max(1, 23-len(constant)) + '"' + translation + '"' - addLine(filename, newline, after+" ") + addLine(filename, newline, after+" ") def modifyDeclaration(constant, after): newline = "extern const pm_char S" + constant + "[];" diff --git a/radio/util/codecs.py b/radio/util/codecs.py index 4c75a6ed6..55698b81a 100755 --- a/radio/util/codecs.py +++ b/radio/util/codecs.py @@ -1,5 +1,7 @@ #!/bin/env python +from __future__ import print_function + SIGN_BIT = (0x80) # Sign bit for a A-law byte. QUANT_MASK = (0xf) # Quantization field mask. SEG_SHIFT = (4) # Left shift for segment number. @@ -47,5 +49,5 @@ def tableToString(name, table): result += ' };' return result -print tableToString('alawTable', pcmTable(alaw2linear)) -print tableToString('ulawTable', pcmTable(ulaw2linear)) +print(tableToString('alawTable', pcmTable(alaw2linear))) +print(tableToString('ulawTable', pcmTable(ulaw2linear))) diff --git a/radio/util/copyright.py b/radio/util/copyright.py index 9a12c285d..3e075d08f 100755 --- a/radio/util/copyright.py +++ b/radio/util/copyright.py @@ -1,5 +1,7 @@ #!/usr/bin/env python +from __future__ import print_function + import os import re import sys @@ -38,9 +40,9 @@ def writeheader(filename,header): f = open(filename,'w') f.writelines(output) f.close() - print "added header to %s" %filename - except IOError,err: - print "something went wrong trying to add header to %s: %s" % (filename,err) + print("added header to %s" %filename) + except IOError as err: + print("something went wrong trying to add header to %s: %s" % (filename,err)) def main(args=sys.argv): headerfile = open(args[1]) diff --git a/radio/util/dsm2.py b/radio/util/dsm2.py index 1d1d77006..7c5e4097a 100755 --- a/radio/util/dsm2.py +++ b/radio/util/dsm2.py @@ -1,7 +1,9 @@ +from __future__ import print_function + BITLEN_DSM2 = 16 def sendByteDsm2(b): - print "%02x:" % b, + print("%02x:" % b, end=' ') lev = 0 len = BITLEN_DSM2 for i in range(9): @@ -9,13 +11,13 @@ def sendByteDsm2(b): if (lev == nlev): len += BITLEN_DSM2 else: - print len, + print(len, end=' ') # _send_1(nlev ? len-5 : len+3); len = BITLEN_DSM2 lev = nlev b = (b>>1) | 0x80 # _send_1(len+BITLEN_DSM2+3); // 2 stop bits - print len+BITLEN_DSM2 + print(len+BITLEN_DSM2) sendByteDsm2(24) sendByteDsm2(17) diff --git a/radio/util/fat12.py b/radio/util/fat12.py index 13889f3c7..fdc81d235 100755 --- a/radio/util/fat12.py +++ b/radio/util/fat12.py @@ -1,5 +1,7 @@ #!/bin/env python +from __future__ import division, print_function + curr = 0 idx = 0 byte = 0 @@ -10,12 +12,12 @@ def push4bits(val): curr += val << idx idx += 4 if idx == 8: - print "0x%02X," % curr, + print("0x%02X," % curr, end=' ') idx = 0 curr = 0 byte += 1 if byte % 16 == 0: - print + print() cluster = 0 @@ -27,8 +29,8 @@ def pushCluster(val): cluster += 1 def pushFile(size): - sectors = size / 512 - count = sectors / 8 + sectors = size // 512 + count = sectors // 8 for i in range(count-1): pushCluster(cluster+1) pushCluster(0xFFF) @@ -36,14 +38,14 @@ def pushFile(size): def pushDisk(eeprom, flash): global curr, idx, byte, cluster curr = idx = byte = cluster = 0 - print "Disk with %dk EEPROM and %dk FLASH:" % (eeprom, flash) + print("Disk with %dk EEPROM and %dk FLASH:" % (eeprom, flash)) pushCluster(0xFF8) pushCluster(0xFFF) pushFile(eeprom*1024) pushFile(flash*1024) while byte < 512: push4bits(0) - print + print() pushDisk(32, 512) pushDisk(64, 512) diff --git a/radio/util/img2lbm.py b/radio/util/img2lbm.py index e02ac7a25..58e12e32c 100755 --- a/radio/util/img2lbm.py +++ b/radio/util/img2lbm.py @@ -1,5 +1,7 @@ #!/usr/bin/env python +from __future__ import division, print_function + import sys from PyQt4 import Qt, QtGui @@ -19,7 +21,7 @@ else: def writeSize(f, width, height): if lcdwidth > 255: - f.write("%d,%d,%d,%d,\n" % (width%256, width/256, height%256, height/256)) + f.write("%d,%d,%d,%d,\n" % (width%256, width//256, height%256, height//256)) else: f.write("%d,%d,\n" % (width, height)) @@ -27,7 +29,7 @@ if what == "1bit": rows = 1 if len(sys.argv) > 5: rows = int(sys.argv[5]) - writeSize(f, width, height/rows) + writeSize(f, width, height//rows) for y in range(0, height, 8): for x in range(width): value = 0 @@ -42,7 +44,7 @@ elif what == "4/4/4/4": for y in range(height): for x in range(width): pixel = image.pixel(x, y) - f.write("0x%1x%1x%1x%1x," % (Qt.qAlpha(pixel)/16, Qt.qRed(pixel)/16, Qt.qGreen(pixel)/16, Qt.qBlue(pixel)/16)) + f.write("0x%1x%1x%1x%1x," % (Qt.qAlpha(pixel)//16, Qt.qRed(pixel)//16, Qt.qGreen(pixel)//16, Qt.qBlue(pixel)//16)) f.write("\n") elif what == "5/6/5/8": colors = [] @@ -148,4 +150,3 @@ elif what == "22x38": f.write("\n") else: print("wrong argument", sys.argv[4]) - diff --git a/radio/util/include-guard.py b/radio/util/include-guard.py index 53d3bdb9e..77e80bed0 100755 --- a/radio/util/include-guard.py +++ b/radio/util/include-guard.py @@ -1,5 +1,7 @@ #!/usr/bin/env python +from __future__ import print_function + import sys, os for filename in sys.argv[1:]: @@ -14,7 +16,7 @@ for filename in sys.argv[1:]: if line.startswith("#ifndef "): guard = line[8:] if lines[i+1].strip() == "#define %s" % guard: - print filename, ":", guard, "=>", newguard + print(filename, ":", guard, "=>", newguard) lines[i] = "#ifndef %s\n" % newguard lines[i+1] = "#define %s\n" % newguard end = -1 diff --git a/radio/util/luaexport.py b/radio/util/luaexport.py index 5b785e8bb..e000454ec 100755 --- a/radio/util/luaexport.py +++ b/radio/util/luaexport.py @@ -1,6 +1,7 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- +from __future__ import print_function import sys import os @@ -24,11 +25,11 @@ error = None def checkName(name): global warning if name in dups_name: - print "WARNING: Duplicate name %s found for constant %s" % (name, CONSTANT_VALUE) + print("WARNING: Duplicate name %s found for constant %s" % (name, CONSTANT_VALUE)) warning = True dups_name.append(name) if name != name.lower(): - print "WARNING: Name not in lower case %s found for constant %s" % (name, CONSTANT_VALUE) + print("WARNING: Name not in lower case %s found for constant %s" % (name, CONSTANT_VALUE)) warning = True @@ -46,9 +47,9 @@ def LEXP_MULTIPLE(nameFormat, descriptionFormat, valuesCount): exports_multiple.append( (CONSTANT_VALUE, nameFormat, descriptionFormat, valuesCount) ) if len(sys.argv) < 3: - print "Error: not enough arguments!" - print "Usage:" - print " luaexport.py []" + print("Error: not enough arguments!") + print("Usage:") + print(" luaexport.py []") version = sys.argv[1] inputFile = sys.argv[2] @@ -56,11 +57,11 @@ outputFile = sys.argv[3] docFile = None if len(sys.argv) >= 4: docFile = sys.argv[4] -print "Version %s" % version -print "Input file %s" % inputFile -print "Output file %s" % outputFile +print("Version %s" % version) +print("Input file %s" % inputFile) +print("Output file %s" % outputFile) if docFile: - print "Documentation file %s" % docFile + print("Documentation file %s" % docFile) inp = open(inputFile, "r") @@ -75,7 +76,7 @@ while True: parts = line.split('LEXP') #print parts if len(parts) != 2: - print "Wrong line: %s" % line + print("Wrong line: %s" % line) continue cmd = 'LEXP' + parts[1] cnst = parts[0].rstrip(', ') @@ -93,7 +94,7 @@ while True: # print cmd eval(cmd) except: - print "ERROR: problem with the definition: %s" % line + print("ERROR: problem with the definition: %s" % line) traceback.print_exc() error = True @@ -130,7 +131,7 @@ exports.sort(key = lambda x: x[1]) #sort by name data = [" {%s, \"%s\", \"%s\"}" % export for export in exports] out.write(",\n".join(data)) out.write("\n};\n\n") -print "Generated %d items in luaFields[]" % len(exports) +print("Generated %d items in luaFields[]" % len(exports)) out.write(""" // The list of Lua fields that have a range of values @@ -139,7 +140,7 @@ const LuaMultipleField luaMultipleFields[] = { data = [" {%s, \"%s\", \"%s\", %d}" % export for export in exports_multiple] out.write(",\n".join(data)) out.write("\n};\n\n") -print "Generated %d items in luaMultipleFields[]" % len(exports_multiple) +print("Generated %d items in luaMultipleFields[]" % len(exports_multiple)) out.close() if docFile: diff --git a/radio/util/parse.py b/radio/util/parse.py index 5d0faac96..cb75901bc 100755 --- a/radio/util/parse.py +++ b/radio/util/parse.py @@ -1,9 +1,11 @@ #!/usr/bin/env python +from __future__ import print_function + import sys filename = sys.argv[1] -print filename +print(filename) fr = open(filename) fw = open(filename+".new", "w") ew = open(filename+".en", "w") @@ -46,10 +48,10 @@ for line in fr.readlines(): if str_rep in replacements.keys(): if replacements[str_rep] != str: - print "!!!!! NON !!!!!" + print("!!!!! NON !!!!!") else: replacements[str_rep] = str - print glob_str, "=>", str, str_rep + print(glob_str, "=>", str, str_rep) ew.write("#define " + str_rep[1:] + " "*(17-len(str_rep)) + '"%s"\n' % str) hw.write("extern const PROGMEM char %s[];\n" % str_rep) cw.write("const prog_char APM %s[] = %s;\n" % (str_rep, str_rep[1:])) diff --git a/radio/util/sinus.py b/radio/util/sinus.py index 727090e49..bea4b3fc0 100755 --- a/radio/util/sinus.py +++ b/radio/util/sinus.py @@ -1,5 +1,7 @@ #!/bin/env python +from __future__ import print_function + import math samples = 1024 @@ -17,13 +19,13 @@ for i in range(samples): max = sample elif sample < min: min = sample - print "%d," % sample, + print("%d," % sample, end=' ') if i % 10 == 9: - print + print() -print -print 'Range is:', min, max +print() +print('Range is:', min, max) if max > 32767 or min < -32768: - print "Invalid range!" + print("Invalid range!") diff --git a/radio/util/sport-parse.py b/radio/util/sport-parse.py index 58c041de5..c11f66a44 100755 --- a/radio/util/sport-parse.py +++ b/radio/util/sport-parse.py @@ -3,6 +3,7 @@ # This program parses sport.log files +from __future__ import division, print_function import os import sys @@ -28,28 +29,28 @@ quiet = False def ParseFlVSS(packet, dataId, prim, appId, data, crc): # if dataId != 0xa1: # return - print "packet: %s (%4d)" % (dump(packet), lineNumber) , + print("packet: %s (%4d)" % (dump(packet), lineNumber), end=' ') cells = (data & 0xF0) >> 4 battnumber = data & 0xF; - voltage1 = ((data & 0x000FFF00) >> 8) / 5 - voltage2 = ((data & 0xFFF00000) >> 20) / 5 - print " FLVSS: no cells: %d, cell: %d: voltages: %0.2f %0.2f" % (cells, battnumber, voltage1/100.0, voltage2/100.0) + voltage1 = ((data & 0x000FFF00) >> 8) // 5 + voltage2 = ((data & 0xFFF00000) >> 20) // 5 + print(" FLVSS: no cells: %d, cell: %d: voltages: %0.2f %0.2f" % (cells, battnumber, voltage1/100., voltage2/100.)) def ParseRSSI(packet, dataId, prim, appId, data, crc): - print "packet: %s (%4d)" % (dump(packet), lineNumber) , - print " RSSI: %d" % (data & 0xFF) + print("packet: %s (%4d)" % (dump(packet), lineNumber), end=' ') + print(" RSSI: %d" % (data & 0xFF)) def ParseAdc(packet, dataId, prim, appId, data, crc): - print "packet: %s (%4d)" % (dump(packet), lineNumber) , - print " A%d: %d" % (dataId - 0xf102, data & 0xFF) + print("packet: %s (%4d)" % (dump(packet), lineNumber), end=' ') + print(" A%d: %d" % (dataId - 0xf102, data & 0xFF)) def ParseBatt(packet, dataId, prim, appId, data, crc): - print "packet: %s (%4d)" % (dump(packet), lineNumber) , - print " Batt: %d" % (data & 0xFF) + print("packet: %s (%4d)" % (dump(packet), lineNumber), end=' ') + print(" Batt: %d" % (data & 0xFF)) def ParseSWR(packet, dataId, prim, appId, data, crc): - print "packet: %s (%4d)" % (dump(packet), lineNumber) , - print " SWR: %d" % (data & 0xFF) + print("packet: %s (%4d)" % (dump(packet), lineNumber), end=' ') + print(" SWR: %d" % (data & 0xFF)) def ParseAirSpeed(packet, dataId, prim, appId, data, crc): print "packet: %s (%4d)" % (dump(packet), lineNumber) , @@ -77,7 +78,7 @@ def ParseSportPacket(packet): (dataId, prim, appId, data, crc) = struct.unpack('= firstId and appId <= lastId: @@ -85,8 +86,8 @@ def ParseSportPacket(packet): return #no parser found if not quiet: - print "\tdataId:%02x, prim:%02x, appId:%04x, data:%08x, crc:%02x)" % (dataId, prim, appId, data, crc) - print "\tparser for appId %02x not implemented" % appId + print("\tdataId:%02x, prim:%02x, appId:%04x, data:%08x, crc:%02x)" % (dataId, prim, appId, data, crc)) + print("\tparser for appId %02x not implemented" % appId) def ParsePacket(packet): global lineNumber @@ -104,7 +105,7 @@ def ParsePacket(packet): #print "buff after unstuff %s" % dump(packet, 20) else: #missin data, wait for more data - print "unstuff missing data" + print("unstuff missing data") return #print "packet: %s" % dump(packet, 10) @@ -113,11 +114,11 @@ def ParsePacket(packet): #print "\npacket: %s @%d" % (dump(packet), lineNumber) #check crc if not CheckSportCrc(packet): - print "error: wrong CRC for packet %s at line %d" % (dump(packet), lineNumber) + print("error: wrong CRC for packet %s at line %d" % (dump(packet), lineNumber)) ParseSportPacket(packet) else: if len(packet) > 1: - print "warning: wrong length %s for packet %s at line %d" % (len(packet), dump(packet, 10), lineNumber) + print("warning: wrong length %s for packet %s at line %d" % (len(packet), dump(packet, 10), lineNumber)) def ParseSportData(data): @@ -169,8 +170,8 @@ while True: #print line parts = line.split(': ') if len(parts) < 2: - print "weird data: \"%s\" at line %d" % (line, lineNumber) + print("weird data: \"%s\" at line %d" % (line, lineNumber)) continue sportData = parts[1].strip() # print "sd: %s" % sportData - ParseSportData(sportData) \ No newline at end of file + ParseSportData(sportData) diff --git a/radio/util/translate.py b/radio/util/translate.py index d0a6f7958..d2ff4cb86 100755 --- a/radio/util/translate.py +++ b/radio/util/translate.py @@ -127,7 +127,7 @@ parser.add_argument("--reverse", help="Reversed char conversion (from number to args = parser.parse_args() if args.language not in translations: - parser.error(args.language + ' is not a supported language. Try one of the supported ones: ' + str(translations.keys())) + parser.error(args.language + ' is not a supported language. Try one of the supported ones: ' + str(list(translations.keys()))) system.exit() if args.reverse: diff --git a/radio/util/tts.py b/radio/util/tts.py index d8eecfc81..6a9c02cf5 100755 --- a/radio/util/tts.py +++ b/radio/util/tts.py @@ -26,7 +26,18 @@ # Portuguese : Romolo Manfredini # Spanish : Romolo Manfredini (With the help of Jose Moreno) -import os, sys, shutil, platform, subprocess, wave, zipfile, httplib, urllib +from __future__ import print_function + +import os, sys, shutil, platform, subprocess, wave, zipfile + +try: + # Python 3 + from http.client import HTTPConnection + from urllib.parse import urlencode +except ImportError: + # Python 2 + from httplib import HTTPConnection + from urllib import urlencode NO_ALTERNATE = 1024 @@ -53,7 +64,7 @@ def wavstrip(filename): def generate(str, filename): - print filename, str + print(filename, str) if not str: str = " !" #this is so blank wav files never exist! @@ -67,7 +78,7 @@ def generate(str, filename): "speak not implemented with google tts engine" exit() else: - print "which speach engine?" + print("which speach engine?") exit() else: if "sapi" in sys.argv: @@ -82,8 +93,8 @@ def generate(str, filename): elif "google" in sys.argv: ttsmp3 = "ttsfile.mp3" ttsfilename = "ttsfile.wav" - conn = httplib.HTTPConnection("translate.google.com") - params = urllib.urlencode({'ie': "UTF-8", 'tl': directory, 'q': str.encode("utf-8")}) + conn = HTTPConnection("translate.google.com") + params = urlencode({'ie': "UTF-8", 'tl': directory, 'q': str.encode("utf-8")}) headers = {"User-Agent": "Mozilla"} conn.request("GET", u"/translate_tts?%s" % params, headers=headers) # conn.request("GET", "/translate_tts?ie=UTF-8&tl=%s&q=%s" % (directory, urllib.urlencode(str)), headers={"User-Agent": "Mozilla"}) @@ -93,7 +104,7 @@ def generate(str, filename): conn.close() else: - print "which speach engine?" + print("which speach engine?") exit() wavstrip(ttsfilename) @@ -771,7 +782,7 @@ if __name__ == "__main__": # tts.Volume = 40 # tts.SetRate(1) if "list" in sys.argv: - print tts.GetVoiceNames() + print(tts.GetVoiceNames()) exit() if "mulaw" in sys.argv: @@ -887,7 +898,7 @@ if __name__ == "__main__": systemSounds, sounds = ttsCz() else: - print "which language?" + print("which language?") exit() if "csv" in sys.argv: From b8800ed30ee06a7bcabb7cea27d61091401d3cc1 Mon Sep 17 00:00:00 2001 From: Sean Vig Date: Mon, 7 Dec 2015 08:51:04 -0600 Subject: [PATCH 02/21] Update Makefile to allow Python 3 We no longer must enforce Python 2, so let Python 3 be run if that is the system Python --- radio/src/Makefile | 25 +++++++++---------------- 1 file changed, 9 insertions(+), 16 deletions(-) diff --git a/radio/src/Makefile b/radio/src/Makefile index 04019da69..88ef5c2fc 100644 --- a/radio/src/Makefile +++ b/radio/src/Makefile @@ -388,21 +388,14 @@ LUA_COMPILER = NO # Define programs and commands. SHELL = sh -# Make sure python is Python 2 -ifeq ($(findstring Python 2,$(shell python --version 2>&1)), Python 2) - PYTHON := python -else - PYTHON := python2 -endif - -IMG2LBM = -$(PYTHON) ../util/img2lbm.py -BIN2LBM = -$(PYTHON) ../util/bin2lbm.py +IMG2LBM = -python ../util/img2lbm.py +BIN2LBM = -python ../util/bin2lbm.py ifeq ($(OS), Windows_NT) - FONT2PNG = -$(PYTHON) ../util/font2png.py + FONT2PNG = -python ../util/font2png.py else - FONT2PNG = -xvfb-run --server-args="-screen 0 1024x768x24" $(PYTHON) ../util/font2png.py + FONT2PNG = -xvfb-run --server-args="-screen 0 1024x768x24" python ../util/font2png.py endif -TRANSLATE = -$(PYTHON) ../util/translate.py +TRANSLATE = -python ../util/translate.py VERSION_MAJOR = 2 VERSION_MINOR = 2 @@ -1953,28 +1946,28 @@ lua/lua_exports_taranis.inc: myeeprom.h ../util/luaexport.py @echo "Generating a list of Lua exported constants in lua/lua_exports_taranis.txt" @$(PARSER) -DEXPORT -DPCBTARANIS -DLUA -DVIRTUALINPUTS myeeprom.h | grep LEXP > lua/lua_exports_taranis.txt @echo "Parsing and generating C Lua exports in lua/lua_exports_taranis.inc" - @$(PYTHON) ../util/luaexport.py $(VERSION) lua/lua_exports_taranis.txt lua/lua_exports_taranis.inc lua/lua_fields_taranis.txt + @python ../util/luaexport.py $(VERSION) lua/lua_exports_taranis.txt lua/lua_exports_taranis.inc lua/lua_fields_taranis.txt @rm lua/lua_exports_taranis.txt lua/lua_exports_taranis_x9e.inc: myeeprom.h ../util/luaexport.py @echo "Generating a list of Lua exported constants in lua/lua_exports_taranis_x9e.txt" @$(PARSER) -DEXPORT -DPCBTARANIS -DREVPLUS -DREV9E -DLUA -DVIRTUALINPUTS myeeprom.h | grep LEXP > lua/lua_exports_taranis_x9e.txt @echo "Parsing and generating C Lua exports in lua/lua_exports_taranis_x9e.inc" - @$(PYTHON) ../util/luaexport.py $(VERSION) lua/lua_exports_taranis_x9e.txt lua/lua_exports_taranis_x9e.inc lua/lua_fields_taranis_x9e.txt + @python ../util/luaexport.py $(VERSION) lua/lua_exports_taranis_x9e.txt lua/lua_exports_taranis_x9e.inc lua/lua_fields_taranis_x9e.txt @rm lua/lua_exports_taranis_x9e.txt lua/lua_exports_horus.inc: myeeprom.h ../util/luaexport.py @echo "Generating a list of Lua exported constants in lua/lua_exports_horus.txt" @$(PARSER) -DEXPORT -DPCBHORUS -DLUA -DVIRTUALINPUTS myeeprom.h | grep LEXP > lua/lua_exports_horus.txt @echo "Parsing and generating C Lua exports in lua/lua_exports_horus.inc" - @$(PYTHON) ../util/luaexport.py $(VERSION) lua/lua_exports_horus.txt lua/lua_exports_horus.inc lua/lua_fields_horus.txt + @python ../util/luaexport.py $(VERSION) lua/lua_exports_horus.txt lua/lua_exports_horus.inc lua/lua_fields_horus.txt @rm lua/lua_exports_horus.txt lua/lua_exports_flamenco.inc: myeeprom.h ../util/luaexport.py @echo "Generating a list of Lua exported constants in lua/lua_exports_flamenco.txt" @$(PARSER) -DEXPORT -DPCBFLAMENCO -DLUA -DVIRTUALINPUTS myeeprom.h | grep LEXP > lua/lua_exports_flamenco.txt @echo "Parsing and generating C Lua exports in lua/lua_exports_flamenco.inc" - @$(PYTHON) ../util/luaexport.py $(VERSION) lua/lua_exports_flamenco.txt lua/lua_exports_flamenco.inc lua/lua_fields_flamenco.txt + @python ../util/luaexport.py $(VERSION) lua/lua_exports_flamenco.txt lua/lua_exports_flamenco.inc lua/lua_fields_flamenco.txt @rm lua/lua_exports_flamenco.txt # Eye candy. From 50d8e2153395befcd5fec36af71f3ec5bbc16d58 Mon Sep 17 00:00:00 2001 From: Sean Vig Date: Thu, 8 Oct 2015 23:31:49 -0500 Subject: [PATCH 03/21] PEP8 radio/util/add-issue-links.py Remove unused imports, fix indentation --- radio/util/add-issue-links.py | 56 ++++++++++++++++------------------- 1 file changed, 26 insertions(+), 30 deletions(-) diff --git a/radio/util/add-issue-links.py b/radio/util/add-issue-links.py index d2682bce3..582809885 100755 --- a/radio/util/add-issue-links.py +++ b/radio/util/add-issue-links.py @@ -4,47 +4,43 @@ from __future__ import print_function import sys -import os -import traceback -import time -import re import re if len(sys.argv) > 1: - inputFile = sys.argv[1] - inp = open(inputFile, "r") + inputFile = sys.argv[1] + inp = open(inputFile, "r") else: - inp = sys.stdin + inp = sys.stdin pattern = re.compile("#\d+") while True: - skip = False - line = inp.readline() - if len(line) == 0: - break - line = line.strip('\r\n') + skip = False + line = inp.readline() + if len(line) == 0: + break + line = line.strip('\r\n') - if len(line) == 0: - skip = True - if line.startswith("<"): - skip = True - if line.startswith("["): - skip = True + if len(line) == 0: + skip = True + if line.startswith("<"): + skip = True + if line.startswith("["): + skip = True - if not skip: - #line = line.strip() - #print "line: %s" % line - found = re.findall(pattern, line) - if len(found) > 0: - for issue in found: - line = line.replace(issue, '') - #add issues - issue_links = ["#%d" % (int(issue[1:]), int(issue[1:])) for issue in found] - links = "(" + ", ".join(issue_links) + ")" - line = "
  • " + line + " " + links + "
  • " + if not skip: + # line = line.strip() + # print("line: %s" % line) + found = re.findall(pattern, line) + if len(found) > 0: + for issue in found: + line = line.replace(issue, '') + # add issues + issue_links = ["#%d" % (int(issue[1:]), int(issue[1:])) for issue in found] + links = "(" + ", ".join(issue_links) + ")" + line = "
  • " + line + " " + links + "
  • " - print(line) + print(line) inp.close() From a0f6b0e9131c3fa13b5192a58ddb24e5cbc9cf29 Mon Sep 17 00:00:00 2001 From: Sean Vig Date: Thu, 8 Oct 2015 23:32:56 -0500 Subject: [PATCH 04/21] PEP8 radio/util/addtr.py Split imports, fix indentation --- radio/util/addtr.py | 50 ++++++++++++++++++++++++--------------------- 1 file changed, 27 insertions(+), 23 deletions(-) diff --git a/radio/util/addtr.py b/radio/util/addtr.py index 4794b8905..9081a6235 100755 --- a/radio/util/addtr.py +++ b/radio/util/addtr.py @@ -2,38 +2,42 @@ from __future__ import print_function -import sys, glob +import sys +import glob + def addLine(filename, newline, after): - print(filename, newline) - lines = file(filename, 'r').readlines() - for i, line in enumerate(lines): - if after in line: - lines.insert(i+1, newline + '\n') - break - file(filename, 'w').writelines(lines) + print(filename, newline) + lines = file(filename, 'r').readlines() + for i, line in enumerate(lines): + if after in line: + lines.insert(i + 1, newline + '\n') + break + file(filename, 'w').writelines(lines) + def modifyTranslations(constant, translation, after): - for filename in glob.glob('translations/*.h.txt'): - newline = "#define " + constant + " "*max(1, 23-len(constant)) + '"' + translation + '"' - addLine(filename, newline, after+" ") + for filename in glob.glob('translations/*.h.txt'): + newline = "#define " + constant + " " * max(1, 23 - len(constant)) + '"' + translation + '"' + addLine(filename, newline, after + " ") + def modifyDeclaration(constant, after): - newline = "extern const pm_char S" + constant + "[];" - filename = "translations.h" - addLine(filename, newline, after+"[];") + newline = "extern const pm_char S" + constant + "[];" + filename = "translations.h" + addLine(filename, newline, after + "[];") + def modifyDefinition(constant, after): - newline = "const pm_char S" + constant + "[] PROGMEM = " + constant + ";" - filename = "translations.cpp" - addLine(filename, newline, after+"[] ") + newline = "const pm_char S" + constant + "[] PROGMEM = " + constant + ";" + filename = "translations.cpp" + addLine(filename, newline, after + "[] ") after = sys.argv[-1] for arg in sys.argv[1:-1]: - constant, translation = arg.split("=") - modifyTranslations(constant, translation, after) - modifyDeclaration(constant, after) - modifyDefinition(constant, after) - after = constant - + constant, translation = arg.split("=") + modifyTranslations(constant, translation, after) + modifyDeclaration(constant, after) + modifyDefinition(constant, after) + after = constant From 3d6533c88bce0c9d0d16a18255b3f6eb70cb5bc9 Mon Sep 17 00:00:00 2001 From: Sean Vig Date: Thu, 8 Oct 2015 23:35:34 -0500 Subject: [PATCH 05/21] PEP8 radio/util/bin2lbm.py Fix indentation --- radio/util/bin2lbm.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/radio/util/bin2lbm.py b/radio/util/bin2lbm.py index 19b3bf0cf..c86e51c21 100755 --- a/radio/util/bin2lbm.py +++ b/radio/util/bin2lbm.py @@ -11,10 +11,12 @@ fw = open(fileout, "w") st = fr.read(16) while st: - for b in st: - fw.write("0x%02x," % ord(b)) - fw.write("\n") - st = fr.read(16) + for b in st: + fw.write("0x%02x," % ord(b)) + fw.write("\n") + st = fr.read(16) + +fw.write("\n") -fw.write("\n") fw.close() +fr.close() From 054952edcbf06f57d8159630962d1a50fb00d08d Mon Sep 17 00:00:00 2001 From: Sean Vig Date: Thu, 8 Oct 2015 23:39:16 -0500 Subject: [PATCH 06/21] PEP8 radio/util/capitalize.py Split imports, fix indentation --- radio/util/capitalize.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/radio/util/capitalize.py b/radio/util/capitalize.py index 941cafb6b..ac087168d 100755 --- a/radio/util/capitalize.py +++ b/radio/util/capitalize.py @@ -1,8 +1,9 @@ #!/usr/bin/env python -import glob, os +import glob +import os for f in glob.glob("*.bmp") + glob.glob("*.BMP"): - t = f.title() - if f != t: - os.rename(f, t) + t = f.title() + if f != t: + os.rename(f, t) From be154140b38e6966e2c7712a5c0633d754844a03 Mon Sep 17 00:00:00 2001 From: Sean Vig Date: Thu, 8 Oct 2015 23:39:54 -0500 Subject: [PATCH 07/21] PEP8 radio/util/codecs.py Fix white space --- radio/util/codecs.py | 35 ++++++++++++++++++++--------------- 1 file changed, 20 insertions(+), 15 deletions(-) diff --git a/radio/util/codecs.py b/radio/util/codecs.py index 55698b81a..fdc88f4fe 100755 --- a/radio/util/codecs.py +++ b/radio/util/codecs.py @@ -2,52 +2,57 @@ from __future__ import print_function -SIGN_BIT = (0x80) # Sign bit for a A-law byte. -QUANT_MASK = (0xf) # Quantization field mask. -SEG_SHIFT = (4) # Left shift for segment number. -SEG_MASK = (0x70) # Segment field mask. -BIAS = (0x84) # Bias for linear code. +SIGN_BIT = (0x80) # Sign bit for a A-law byte. +QUANT_MASK = (0xf) # Quantization field mask. +SEG_SHIFT = (4) # Left shift for segment number. +SEG_MASK = (0x70) # Segment field mask. +BIAS = (0x84) # Bias for linear code. + def alaw2linear(a_val): a_val ^= 0x55 - + t = a_val & QUANT_MASK seg = (a_val & SEG_MASK) >> SEG_SHIFT if (seg): t = (t + t + 1 + 32) << (seg + 2) else: - t = (t + t + 1 ) << 3 - + t = (t + t + 1) << 3 + if a_val & SIGN_BIT: return t else: return -t -def ulaw2linear(u_val): + +def ulaw2linear(u_val): # Complement to obtain normal u-law value. u_val = ~u_val - + # Extract and bias the quantization bits. Then # shift up by the segment number and subtract out the bias. t = ((u_val & QUANT_MASK) << 3) + BIAS t <<= (u_val & SEG_MASK) >> SEG_SHIFT - + if u_val & SIGN_BIT: return (BIAS - t) else: return (t - BIAS) + def pcmTable(fn): result = [] for i in range(256): result.append(fn(i)) return result -def tableToString(name, table): - result = 'const int16_t ' + name + '[256] = { ' - result += ', '.join([str(i) for i in table]) + +def tableToString(name, table): + result = 'const int16_t ' + name + '[256] = { ' + result += ', '.join(str(i) for i in table) result += ' };' return result - + + print(tableToString('alawTable', pcmTable(alaw2linear))) print(tableToString('ulawTable', pcmTable(ulaw2linear))) From 9d13484291f84751ba7f197173544ae8df8be4b3 Mon Sep 17 00:00:00 2001 From: Sean Vig Date: Thu, 8 Oct 2015 23:40:59 -0500 Subject: [PATCH 08/21] PEP8 radio/util/copyright.py Remove unused imports, fix whitespace, fix comments --- radio/util/copyright.py | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/radio/util/copyright.py b/radio/util/copyright.py index 3e075d08f..4a2c0643f 100755 --- a/radio/util/copyright.py +++ b/radio/util/copyright.py @@ -2,13 +2,12 @@ from __future__ import print_function -import os -import re import sys -def writeheader(filename,header): + +def writeheader(filename, header): """ - write a header to filename, + write a header to filename, skip files where first line after optional shebang matches the skip regex filename should be the name of the file to write to header should be a list of strings @@ -19,30 +18,31 @@ def writeheader(filename,header): f.close() output = [] - #comment out the next 3 lines if you don't wish to preserve shebangs - if len(inpt) > 0 and inpt[0].startswith("#!"): + # comment out the next 3 lines if you don't wish to preserve shebangs + if len(inpt) > 0 and inpt[0].startswith("#!"): output.append(inpt[0]) inpt = inpt[1:] if inpt[0].strip().startswith("/*"): for i, line in enumerate(inpt): if line.strip().endswith("*/"): - inpt = inpt[i+1:] + inpt = inpt[i + 1:] break while not inpt[0].strip(): inpt = inpt[1:] - output.extend(header) #add the header + output.extend(header) # add the header for line in inpt: output.append(line) try: f = open(filename,'w') f.writelines(output) f.close() - print("added header to %s" %filename) + print("added header to %s" % filename) except IOError as err: - print("something went wrong trying to add header to %s: %s" % (filename,err)) + print("something went wrong trying to add header to %s: %s" % (filename, err)) + def main(args=sys.argv): headerfile = open(args[1]) @@ -50,5 +50,7 @@ def main(args=sys.argv): headerfile.close() writeheader(args[2], header) -#call the main method -main() + +if __name__ == '__main__': + # call the main method + main() From 7dcd96d258061d97ecde01966a20d99193fd343e Mon Sep 17 00:00:00 2001 From: Sean Vig Date: Fri, 9 Oct 2015 00:32:28 -0500 Subject: [PATCH 09/21] PEP8 radio/util/dsm2.py Fix indentation and whitespace --- radio/util/dsm2.py | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/radio/util/dsm2.py b/radio/util/dsm2.py index 7c5e4097a..ede556211 100755 --- a/radio/util/dsm2.py +++ b/radio/util/dsm2.py @@ -2,22 +2,24 @@ from __future__ import print_function BITLEN_DSM2 = 16 + def sendByteDsm2(b): print("%02x:" % b, end=' ') lev = 0 len = BITLEN_DSM2 for i in range(9): nlev = b & 1 - if (lev == nlev): - len += BITLEN_DSM2 + if lev == nlev: + len += BITLEN_DSM2 else: - print(len, end=' ') - # _send_1(nlev ? len-5 : len+3); - len = BITLEN_DSM2 - lev = nlev - b = (b>>1) | 0x80 + print(len, end=' ') + # _send_1(nlev ? len-5 : len+3); + len = BITLEN_DSM2 + lev = nlev + b = (b >> 1) | 0x80 # _send_1(len+BITLEN_DSM2+3); // 2 stop bits - print(len+BITLEN_DSM2) + print(len + BITLEN_DSM2) + sendByteDsm2(24) sendByteDsm2(17) From 73f9dac12000a0c6a656765ee665a645a6a090e0 Mon Sep 17 00:00:00 2001 From: Sean Vig Date: Sun, 11 Oct 2015 23:28:15 -0500 Subject: [PATCH 10/21] PEP8 radio/util/fat12.py Fix indentation and whitespace --- radio/util/fat12.py | 69 ++++++++++++++++++++++++--------------------- 1 file changed, 37 insertions(+), 32 deletions(-) diff --git a/radio/util/fat12.py b/radio/util/fat12.py index fdc81d235..9c83a7baa 100755 --- a/radio/util/fat12.py +++ b/radio/util/fat12.py @@ -6,47 +6,52 @@ curr = 0 idx = 0 byte = 0 + def push4bits(val): - global curr, idx, byte - val = val & 0x0f - curr += val << idx - idx += 4 - if idx == 8: - print("0x%02X," % curr, end=' ') - idx = 0 - curr = 0 - byte += 1 - if byte % 16 == 0: - print() + global curr, idx, byte + val = val & 0x0f + curr += val << idx + idx += 4 + if idx == 8: + print("0x%02X," % curr, end=' ') + idx = 0 + curr = 0 + byte += 1 + if byte % 16 == 0: + print() + cluster = 0 + def pushCluster(val): - global cluster - push4bits(val) - push4bits(val >> 4) - push4bits(val >> 8) - cluster += 1 + global cluster + push4bits(val) + push4bits(val >> 4) + push4bits(val >> 8) + cluster += 1 + def pushFile(size): - sectors = size // 512 - count = sectors // 8 - for i in range(count-1): - pushCluster(cluster+1) - pushCluster(0xFFF) + sectors = size // 512 + count = sectors // 8 + for i in range(count - 1): + pushCluster(cluster + 1) + pushCluster(0xFFF) + def pushDisk(eeprom, flash): - global curr, idx, byte, cluster - curr = idx = byte = cluster = 0 - print("Disk with %dk EEPROM and %dk FLASH:" % (eeprom, flash)) - pushCluster(0xFF8) - pushCluster(0xFFF) - pushFile(eeprom*1024) - pushFile(flash*1024) - while byte < 512: - push4bits(0) - print() + global curr, idx, byte, cluster + curr = idx = byte = cluster = 0 + print("Disk with %dk EEPROM and %dk FLASH:" % (eeprom, flash)) + pushCluster(0xFF8) + pushCluster(0xFFF) + pushFile(eeprom * 1024) + pushFile(flash * 1024) + while byte < 512: + push4bits(0) + print() + pushDisk(32, 512) pushDisk(64, 512) - From 710482e821276813ab27d89d960f4a0f03430c96 Mon Sep 17 00:00:00 2001 From: Sean Vig Date: Fri, 9 Oct 2015 00:34:12 -0500 Subject: [PATCH 11/21] PEP8 radio/util/font2png.py Fix whitespace and indentations, remove semicolons --- radio/util/font2png.py | 50 +++++++++++++++++++++++------------------- 1 file changed, 27 insertions(+), 23 deletions(-) diff --git a/radio/util/font2png.py b/radio/util/font2png.py index a07a02a05..dd18d5875 100755 --- a/radio/util/font2png.py +++ b/radio/util/font2png.py @@ -12,6 +12,7 @@ for f in glob.glob("fonts/*.ttf"): chars = u""" !"#$%&'()*+,-./0123456789:;<=>?°ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz~ ≥→←↑↓↗↘↙↖△""" + def getCharWidth(fontsize, metrics, index): if index == 0: return 4 @@ -24,39 +25,42 @@ def getCharWidth(fontsize, metrics, index): else: return rect.width() + 1 + def getFontTopBottom(fontsize, metrics): top, bottom = 0, 0 for i, c in enumerate(chars): - rect = metrics.boundingRect(chars[i]) - top = min(top, rect.top()) - bottom = max(bottom, rect.bottom()) + rect = metrics.boundingRect(chars[i]) + top = min(top, rect.top()) + bottom = max(bottom, rect.bottom()) return top, bottom + def getFontWidth(fontsize, metrics): width = 0 for i, c in enumerate(chars): width += getCharWidth(fontsize, metrics, i) return width - + + def createFontBitmap(filename, fontname, fontsize, fontbold, foreground, background, coordsfile=True): - coords = [ ] + coords = [] font = QtGui.QFont(fontname) font.setPixelSize(fontsize) font.setBold(fontbold) font.setHintingPreference(QtGui.QFont.PreferNoHinting) font.setStyleStrategy(QtGui.QFont.PreferAntialias) metrics = QtGui.QFontMetrics(font) - + width = getFontWidth(fontsize, metrics) top, bottom = getFontTopBottom(fontsize, metrics) extraFilename = "fonts/extra_%dpx.png" % fontsize extraImage = QtGui.QImage(extraFilename) if extraImage.isNull(): - print "No extra font file", extraFilename + print("No extra font file", extraFilename) extraWidth = 0 else: extraWidth = extraImage.size().width() - image = QtGui.QImage(width + extraWidth, fontsize+2, QtGui.QImage.Format_RGB32) + image = QtGui.QImage(width + extraWidth, fontsize + 2, QtGui.QImage.Format_RGB32) image.fill(background) painter = QtGui.QPainter() painter.begin(image) @@ -69,31 +73,31 @@ def createFontBitmap(filename, fontname, fontsize, fontbold, foreground, backgro if i == 0: pass elif i == 14 and fontsize <= 8: - painter.drawPoint(width, fontsize); + painter.drawPoint(width, fontsize) else: rect = metrics.boundingRect(c) if fontsize >= 24: - painter.drawText(width-rect.left()+1, fontsize-2, c) # fontsize-bottom+1 -17 / 7 + painter.drawText(width - rect.left() + 1, fontsize - 2, c) # fontsize-bottom+1 -17 / 7 else: - painter.drawText(width-rect.left(), fontsize-1, c) # fontsize-bottom+1 -17 / 7 + painter.drawText(width - rect.left(), fontsize - 1, c) # fontsize-bottom+1 -17 / 7 width += getCharWidth(fontsize, metrics, i) if extraWidth: - painter.drawImage(QtCore.QPoint(width, 0), extraImage) - + painter.drawImage(QtCore.QPoint(width, 0), extraImage) + coords.append(width) painter.end() image.save(filename + ".png") if coordsfile: - f = file(filename + ".specs", "w") - f.write("{ ") - f.write(",".join(str(tmp) for tmp in coords)) - if extraWidth: - for i in range(1, 14): - f.write(", %d" % (int(coords[-1])+i*(extraWidth/12))) - # f.write(file("fonts/extra_%dpx.specs" % fontsize).read()) - f.write(" }") - f.close() + f = file(filename + ".specs", "w") + f.write("{ ") + f.write(",".join(str(tmp) for tmp in coords)) + if extraWidth: + for i in range(1, 14): + f.write(", %d" % (int(coords[-1]) + i * (extraWidth / 12))) + # f.write(file("fonts/extra_%dpx.specs" % fontsize).read()) + f.write(" }") + f.close() return coords if __name__ == "__main__": - createFontBitmap(sys.argv[4], sys.argv[1], float(sys.argv[2]), sys.argv[3] == "True", QtGui.QColor(0x00, 0x00, 0x00), QtGui.QColor(0xFF, 0xFF, 0xFF)) + createFontBitmap(sys.argv[4], sys.argv[1], float(sys.argv[2]), sys.argv[3] == "True", QtGui.QColor(0x00, 0x00, 0x00), QtGui.QColor(0xFF, 0xFF, 0xFF)) From 39ee31719077be030d0213be07f9a76bda4dba9f Mon Sep 17 00:00:00 2001 From: Sean Vig Date: Sun, 11 Oct 2015 23:22:11 -0500 Subject: [PATCH 12/21] PEP8 radio/util/img2lbm.py Fix whitespace --- radio/util/img2lbm.py | 63 ++++++++++++++++++++++--------------------- 1 file changed, 33 insertions(+), 30 deletions(-) diff --git a/radio/util/img2lbm.py b/radio/util/img2lbm.py index 58e12e32c..0e4d5f39e 100755 --- a/radio/util/img2lbm.py +++ b/radio/util/img2lbm.py @@ -8,34 +8,37 @@ from PyQt4 import Qt, QtGui image = QtGui.QImage(sys.argv[1]) width, height = image.size().width(), image.size().height() + +def writeSize(f, width, height): + if lcdwidth > 255: + f.write("%d,%d,%d,%d,\n" % (width % 256, width // 256, height % 256, height // 256)) + else: + f.write("%d,%d,\n" % (width, height)) + + f = open(sys.argv[2], "w") + lcdwidth = int(sys.argv[3]) if len(sys.argv) > 4: - what = sys.argv[4] + what = sys.argv[4] else: for s in ("03x05", "04x06", "05x07", "08x10", "10x14", "22x38"): if s in sys.argv[2]: what = s break -def writeSize(f, width, height): - if lcdwidth > 255: - f.write("%d,%d,%d,%d,\n" % (width%256, width//256, height%256, height//256)) - else: - f.write("%d,%d,\n" % (width, height)) - if what == "1bit": rows = 1 if len(sys.argv) > 5: rows = int(sys.argv[5]) - writeSize(f, width, height//rows) + writeSize(f, width, height // rows) for y in range(0, height, 8): for x in range(width): value = 0 for z in range(8): - if y+z < height and image.pixel(x, y+z) == Qt.qRgb(0, 0, 0): - value += 1 << z + if y + z < height and image.pixel(x, y + z) == Qt.qRgb(0, 0, 0): + value += 1 << z f.write("0x%02x," % value) f.write("\n") elif what == "4/4/4/4": @@ -44,7 +47,7 @@ elif what == "4/4/4/4": for y in range(height): for x in range(width): pixel = image.pixel(x, y) - f.write("0x%1x%1x%1x%1x," % (Qt.qAlpha(pixel)//16, Qt.qRed(pixel)//16, Qt.qGreen(pixel)//16, Qt.qBlue(pixel)//16)) + f.write("0x%1x%1x%1x%1x," % (Qt.qAlpha(pixel) // 16, Qt.qRed(pixel) // 16, Qt.qGreen(pixel) // 16, Qt.qBlue(pixel) // 16)) f.write("\n") elif what == "5/6/5/8": colors = [] @@ -54,31 +57,31 @@ elif what == "5/6/5/8": pixel = image.pixel(x, y) val = ((Qt.qRed(pixel) >> 3) << 11) + ((Qt.qGreen(pixel) >> 2) << 5) + ((Qt.qBlue(pixel) >> 3) << 0) # f.write("%d,%d,%d," % (val%256, val/256, Qt.qAlpha(pixel) >> 4)) - f.write("%d,%d," % (val%256, val/256)) + f.write("%d,%d," % (val % 256, val // 256)) f.write("\n") elif what == "4bits": colors = [] writeSize(f, width, height) for y in range(0, height, 2): for x in range(width): - value = 0xFF; + value = 0xFF gray1 = Qt.qGray(image.pixel(x, y)) - if y+1 < height: - gray2 = Qt.qGray(image.pixel(x, y+1)) + if y + 1 < height: + gray2 = Qt.qGray(image.pixel(x, y + 1)) else: gray2 = Qt.qRgb(255, 255, 255) for i in range(4): - if (gray1 & (1<<(4+i))): - value -= 1<> 4) f.write("0x%02x," % value) @@ -88,27 +91,27 @@ elif what == "03x05": for x in range(width): value = 0 for z in range(5): - if image.pixel(x, y+z) == Qt.qRgb(0, 0, 0): + if image.pixel(x, y + z) == Qt.qRgb(0, 0, 0): value += 1 << z f.write("0x%02x," % value) - f.write("\n") + f.write("\n") elif what == "04x06": for y in range(0, height, 7): for x in range(width): value = 0 for z in range(7): - if image.pixel(x, y+z) == Qt.qRgb(0, 0, 0): + if image.pixel(x, y + z) == Qt.qRgb(0, 0, 0): value += 1 << z if value == 0x7f: value = 0xff f.write("0x%02x," % value) - f.write("\n") + f.write("\n") elif what == "05x07": for y in range(0, height, 8): for x in range(width): value = 0 for z in range(8): - if image.pixel(x, y+z) == Qt.qRgb(0, 0, 0): + if image.pixel(x, y + z) == Qt.qRgb(0, 0, 0): value += 1 << z f.write("0x%02x," % value) f.write("\n") @@ -119,12 +122,12 @@ elif what == "08x10": for l in range(0, 12, 8): value = 0 for z in range(8): - if l+z < 12: - if image.pixel(x, y+l+z) == Qt.qRgb(0, 0, 0): + if l + z < 12: + if image.pixel(x, y + l + z) == Qt.qRgb(0, 0, 0): value += 1 << z else: skip = False - if skip and l==8: + if skip and l == 8: value = 0xff f.write("0x%02x," % value) f.write("\n") @@ -134,7 +137,7 @@ elif what == "10x14": for l in range(0, 16, 8): value = 0 for z in range(8): - if image.pixel(x, y+l+z) == Qt.qRgb(0, 0, 0): + if image.pixel(x, y + l + z) == Qt.qRgb(0, 0, 0): value += 1 << z f.write("0x%02x," % value) f.write("\n") @@ -144,7 +147,7 @@ elif what == "22x38": for l in range(0, 40, 8): value = 0 for z in range(8): - if image.pixel(x, y+l+z) == Qt.qRgb(0, 0, 0): + if image.pixel(x, y + l + z) == Qt.qRgb(0, 0, 0): value += 1 << z f.write("0x%02x," % value) f.write("\n") From 2968b25cfa596792c7fdb3710606e6c759c2607a Mon Sep 17 00:00:00 2001 From: Sean Vig Date: Fri, 9 Oct 2015 01:02:20 -0500 Subject: [PATCH 13/21] PEP8 radio/util/include-guard.py Split imports, fix whitespace --- radio/util/include-guard.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/radio/util/include-guard.py b/radio/util/include-guard.py index 77e80bed0..428edbfc0 100755 --- a/radio/util/include-guard.py +++ b/radio/util/include-guard.py @@ -2,7 +2,8 @@ from __future__ import print_function -import sys, os +import sys +import os for filename in sys.argv[1:]: f = file(filename, "r") @@ -15,10 +16,10 @@ for filename in sys.argv[1:]: line = line.strip() if line.startswith("#ifndef "): guard = line[8:] - if lines[i+1].strip() == "#define %s" % guard: + if lines[i + 1].strip() == "#define %s" % guard: print(filename, ":", guard, "=>", newguard) lines[i] = "#ifndef %s\n" % newguard - lines[i+1] = "#define %s\n" % newguard + lines[i + 1] = "#define %s\n" % newguard end = -1 while not lines[end].strip().startswith("#endif"): end -= 1 @@ -26,5 +27,4 @@ for filename in sys.argv[1:]: f = file(filename, "w") f.write("".join(lines)) f.close() - break - + break From fa0ded50fe27619bf970162664ec460608dcf800 Mon Sep 17 00:00:00 2001 From: Sean Vig Date: Fri, 9 Oct 2015 01:03:30 -0500 Subject: [PATCH 14/21] PEP8 radio/util/luaexport.py Fix indentation --- radio/util/luaexport.py | 182 ++++++++++++++++++++-------------------- 1 file changed, 93 insertions(+), 89 deletions(-) diff --git a/radio/util/luaexport.py b/radio/util/luaexport.py index e000454ec..512d7cf19 100755 --- a/radio/util/luaexport.py +++ b/radio/util/luaexport.py @@ -22,101 +22,104 @@ exports_script_outputs = [] warning = None error = None + def checkName(name): - global warning - if name in dups_name: - print("WARNING: Duplicate name %s found for constant %s" % (name, CONSTANT_VALUE)) - warning = True - dups_name.append(name) - if name != name.lower(): - print("WARNING: Name not in lower case %s found for constant %s" % (name, CONSTANT_VALUE)) - warning = True + global warning + if name in dups_name: + print("WARNING: Duplicate name %s found for constant %s" % (name, CONSTANT_VALUE)) + warning = True + dups_name.append(name) + if name != name.lower(): + print("WARNING: Name not in lower case %s found for constant %s" % (name, CONSTANT_VALUE)) + warning = True def LEXP(name, description): - # print "LEXP %s, %s" % (name, description) - checkName(name) - exports.append( (CONSTANT_VALUE, name, description) ) + # print "LEXP %s, %s" % (name, description) + checkName(name) + exports.append((CONSTANT_VALUE, name, description)) + def LEXP_MULTIPLE(nameFormat, descriptionFormat, valuesCount): - # print "LEXP_MULTIPLE %s, %s, %s" % (nameFormat, descriptionFormat, valuesCount) - for v in range(valuesCount): - name = nameFormat + str(v) - # print name - checkName(name) - exports_multiple.append( (CONSTANT_VALUE, nameFormat, descriptionFormat, valuesCount) ) + # print "LEXP_MULTIPLE %s, %s, %s" % (nameFormat, descriptionFormat, valuesCount) + for v in range(valuesCount): + name = nameFormat + str(v) + # print name + checkName(name) + exports_multiple.append((CONSTANT_VALUE, nameFormat, descriptionFormat, valuesCount)) + if len(sys.argv) < 3: - print("Error: not enough arguments!") - print("Usage:") - print(" luaexport.py []") + print("Error: not enough arguments!") + print("Usage:") + print(" luaexport.py []") version = sys.argv[1] inputFile = sys.argv[2] outputFile = sys.argv[3] docFile = None if len(sys.argv) >= 4: - docFile = sys.argv[4] + docFile = sys.argv[4] print("Version %s" % version) print("Input file %s" % inputFile) print("Output file %s" % outputFile) if docFile: - print("Documentation file %s" % docFile) + print("Documentation file %s" % docFile) -inp = open(inputFile, "r") +np = open(inputFile, "r") while True: - line = inp.readline() - if len(line) == 0: - break - line = line.strip('\r\n') - line = line.strip() - #print "line: %s" % line + line = inp.readline() + if len(line) == 0: + break + line = line.strip('\r\n') + line = line.strip() + # print "line: %s" % line - parts = line.split('LEXP') - #print parts - if len(parts) != 2: - print("Wrong line: %s" % line) - continue - cmd = 'LEXP' + parts[1] - cnst = parts[0].rstrip(', ') - if cnst.find('=') != -1: - # constant contains = - cnst = cnst.split('=')[0].strip() - #print "Found constant %s with command: %s" % (cnst, cmd) - try: - CONSTANT_VALUE = cnst - # if CONSTANT_VALUE in dups_cnst: - # print "WARNING: Duplicate CONSTANT_VALUE found: %s" % CONSTANT_VALUE - # warning = True - # continue - # dups_cnst.append(CONSTANT_VALUE) - # print cmd - eval(cmd) - except: - print("ERROR: problem with the definition: %s" % line) - traceback.print_exc() - error = True + parts = line.split('LEXP') + # print parts + if len(parts) != 2: + print("Wrong line: %s" % line) + continue + cmd = 'LEXP' + parts[1] + cnst = parts[0].rstrip(', ') + if cnst.find('=') != -1: + # constant contains = + cnst = cnst.split('=')[0].strip() + # print "Found constant %s with command: %s" % (cnst, cmd) + try: + CONSTANT_VALUE = cnst + # if CONSTANT_VALUE in dups_cnst: + # print "WARNING: Duplicate CONSTANT_VALUE found: %s" % CONSTANT_VALUE + # warning = True + # continue + # dups_cnst.append(CONSTANT_VALUE) + # print cmd + eval(cmd) + except: + print("ERROR: problem with the definition: %s" % line) + traceback.print_exc() + error = True inp.close() out = open(outputFile, "w") -out.write("//This file was generated by luaexport.py script on %s for OpenTX version %s\n\n\n" - % ( time.asctime(), version)) +out.write("//This file was generated by luaexport.py script on %s for OpenTX version %s\n\n\n" + % (time.asctime(), version)) header = """ struct LuaSingleField { - uint16_t id; - const char * name; - const char * desc; + uint16_t id; + const char * name; + const char * desc; }; struct LuaMultipleField { - uint16_t id; - const char * name; - const char * desc; - uint8_t count; + uint16_t id; + const char * name; + const char * desc; + uint8_t count; }; """ @@ -125,10 +128,10 @@ out.write(header) out.write(""" // The list of Lua fields // this aray is alphabetically sorted by the second field (name) -const LuaSingleField luaSingleFields[] = { +const LuaSingleField luaSingleFields[] = { """) -exports.sort(key = lambda x: x[1]) #sort by name -data = [" {%s, \"%s\", \"%s\"}" % export for export in exports] +exports.sort(key=lambda x: x[1]) # sort by name +data = [" {%s, \"%s\", \"%s\"}" % export for export in exports] out.write(",\n".join(data)) out.write("\n};\n\n") print("Generated %d items in luaFields[]" % len(exports)) @@ -137,39 +140,40 @@ out.write(""" // The list of Lua fields that have a range of values const LuaMultipleField luaMultipleFields[] = { """) -data = [" {%s, \"%s\", \"%s\", %d}" % export for export in exports_multiple] +data = [" {%s, \"%s\", \"%s\", %d}" % export for export in exports_multiple] out.write(",\n".join(data)) out.write("\n};\n\n") print("Generated %d items in luaMultipleFields[]" % len(exports_multiple)) + out.close() if docFile: - #prepare fields - all_exports = [(name, desc) for (id, name, desc) in exports] - for (id, nameFormat, descriptionFormat, valuesCount) in exports_multiple: - for v in range(1, valuesCount + 1): - name = nameFormat + str(v) - desc = descriptionFormat % v - all_exports.append( (name, desc) ) - #natural sort by field name - convert = lambda text: int(text) if text.isdigit() else text - alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key[0]) ] - all_exports.sort(key = alphanum_key) + # prepare fields + all_exports = [(name, desc) for (id, name, desc) in exports] + for (id, nameFormat, descriptionFormat, valuesCount) in exports_multiple: + for v in range(1, valuesCount + 1): + name = nameFormat + str(v) + desc = descriptionFormat % v + all_exports.append((name, desc)) + # natural sort by field name + convert = lambda text: int(text) if text.isdigit() else text + alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key[0])] + all_exports.sort(key=alphanum_key) - out = open(docFile, "w") - out.write("Alphabetical list of Lua fields for OpenTX version %s\n\n\n" % version) - FIELD_NAME_WIDTH = 25 - out.write("Field name%sField description\n" % (' '*(FIELD_NAME_WIDTH-len('Field name')))) - out.write("----------------------------------------------\n") - data = ["%s%s%s" % (name, ' '*(FIELD_NAME_WIDTH-len(name)) , desc) for (name, desc) in all_exports] - out.write("\n".join(data)) - out.write("\n") + out = open(docFile, "w") + out.write("Alphabetical list of Lua fields for OpenTX version %s\n\n\n" % version) + FIELD_NAME_WIDTH = 25 + out.write("Field name%sField description\n" % (' ' * (FIELD_NAME_WIDTH - len('Field name')))) + out.write("----------------------------------------------\n") + data = ["%s%s%s" % (name_, ' ' * (FIELD_NAME_WIDTH - len(name_)), desc_) for (name_, desc_) in all_exports] + out.write("\n".join(data)) + out.write("\n") - out.close() + out.close() if warning: - sys.exit(1) + sys.exit(1) elif error: - os.remove(outputFile) - sys.exit(2) + os.remove(outputFile) + sys.exit(2) sys.exit(0) From 196dbb1d391fa2cf540419e998c4ab00080e68af Mon Sep 17 00:00:00 2001 From: Sean Vig Date: Fri, 9 Oct 2015 01:06:23 -0500 Subject: [PATCH 15/21] PEP8 radio/util/parse.py Fix whitespace and indentation --- radio/util/parse.py | 89 ++++++++++++++++++++++----------------------- 1 file changed, 44 insertions(+), 45 deletions(-) diff --git a/radio/util/parse.py b/radio/util/parse.py index cb75901bc..d4ea45f69 100755 --- a/radio/util/parse.py +++ b/radio/util/parse.py @@ -7,61 +7,60 @@ import sys filename = sys.argv[1] print(filename) fr = open(filename) -fw = open(filename+".new", "w") -ew = open(filename+".en", "w") -hw = open(filename+".stringsh", "w") -cw = open(filename+".stringsc", "w") +fw = open(filename + ".new", "w") +ew = open(filename + ".en", "w") +hw = open(filename + ".stringsh", "w") +cw = open(filename + ".stringsc", "w") -replacements = {} +replacements = {} for line in fr.readlines(): - pos_pstr = line.find("PSTR(\"") - MENU = False - if pos_pstr < 0: - pos_pstr = line.find("MENU(\"") - MENU = True - while pos_pstr >= 0: - # print line, - if MENU: - pos_endparenthesis = line.find('"', pos_pstr+7) - else: - pos_endparenthesis = line.find("\")", pos_pstr) - str = line[pos_pstr+6:pos_endparenthesis] + pos_pstr = line.find("PSTR(\"") + MENU = False + if pos_pstr < 0: + pos_pstr = line.find("MENU(\"") + MENU = True + while pos_pstr >= 0: + # print line, + if MENU: + pos_endparenthesis = line.find('"', pos_pstr + 7) + else: + pos_endparenthesis = line.find("\")", pos_pstr) + pstr = line[pos_pstr + 6:pos_endparenthesis] - str_rep = "STR_"+str.upper() - for s in (" ", ".", "[", "]", "-", "!", "/", ")", "(", "%", "+", ":"): - str_rep = str_rep.replace(s, "") + str_rep = "STR_" + pstr.upper() + for s in (" ", ".", "[", "]", "-", "!", "/", ")", "(", "%", "+", ":"): + str_rep = str_rep.replace(s, "") - if "14" in str or "32" in str or "@" in str or len(str_rep) <= 5: - pos_pstr = -1 - else: - if MENU: - glob_str = line[pos_pstr+5:pos_endparenthesis+1] - str_rep = "STR_MENU"+str.upper() - else: - glob_str = line[pos_pstr:pos_endparenthesis+2] - str_rep = "STR_"+str.upper() - for s in (" ", ".", "[", "]", "-", "!", "/", ")", "(", "%", "+", ":"): - str_rep = str_rep.replace(s, "") + if "14" in pstr or "32" in pstr or "@" in pstr or len(str_rep) <= 5: + pos_pstr = -1 + else: + if MENU: + glob_str = line[pos_pstr + 5:pos_endparenthesis + 1] + str_rep = "STR_MENU" + pstr.upper() + else: + glob_str = line[pos_pstr:pos_endparenthesis + 2] + str_rep = "STR_" + pstr.upper() + for s in (" ", ".", "[", "]", "-", "!", "/", ")", "(", "%", "+", ":"): + str_rep = str_rep.replace(s, "") - line = line.replace(glob_str, str_rep) + line = line.replace(glob_str, str_rep) - if str_rep in replacements.keys(): - if replacements[str_rep] != str: - print("!!!!! NON !!!!!") - else: - replacements[str_rep] = str - print(glob_str, "=>", str, str_rep) - ew.write("#define " + str_rep[1:] + " "*(17-len(str_rep)) + '"%s"\n' % str) - hw.write("extern const PROGMEM char %s[];\n" % str_rep) - cw.write("const prog_char APM %s[] = %s;\n" % (str_rep, str_rep[1:])) - - pos_pstr = line.find("PSTR(\"") + if str_rep in replacements.keys(): + if replacements[str_rep] != pstr: + print("!!!!! NON !!!!!") + else: + replacements[str_rep] = pstr + print(glob_str, "=>", pstr, str_rep) + ew.write("#define " + str_rep[1:] + " " * (17 - len(str_rep)) + '"%s"\n' % pstr) + hw.write("extern const PROGMEM char %s[];\n" % str_rep) + cw.write("const prog_char APM %s[] = %s;\n" % (str_rep, str_rep[1:])) - fw.write(line) + pos_pstr = line.find("PSTR(\"") + + fw.write(line) fw.close() ew.close() hw.close() cw.close() - From 0743785126496a84e972bd608a3b4440520d01b4 Mon Sep 17 00:00:00 2001 From: Sean Vig Date: Fri, 9 Oct 2015 01:06:54 -0500 Subject: [PATCH 16/21] PEP8 radio/util/sinus.py Fix whitespace --- radio/util/sinus.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/radio/util/sinus.py b/radio/util/sinus.py index bea4b3fc0..2e9b0932b 100755 --- a/radio/util/sinus.py +++ b/radio/util/sinus.py @@ -12,8 +12,8 @@ min = 0 for i in range(samples): sample = 0.0 - for harmonic, amplitude in enumerate(amplitudes): - sample += math.sin(math.pi*2*i*(harmonic+1)/samples) * amplitude / 2 + for harmonic, amplitude in enumerate(amplitudes): + sample += math.sin(math.pi * 2 * i * (harmonic + 1) / samples) * amplitude / 2 sample = int(sample) if sample > max: max = sample @@ -28,4 +28,3 @@ print('Range is:', min, max) if max > 32767 or min < -32768: print("Invalid range!") - From bcc7982b3be0bb8d9fa0eea8806effb87549ffe6 Mon Sep 17 00:00:00 2001 From: Sean Vig Date: Mon, 16 Nov 2015 15:55:30 -0600 Subject: [PATCH 17/21] PEP8 radio/util/sportparse.py Remove unused import, fix whitespace, indentation, and comments --- radio/util/sport-parse.py | 245 +++++++++++++++++++------------------- 1 file changed, 125 insertions(+), 120 deletions(-) diff --git a/radio/util/sport-parse.py b/radio/util/sport-parse.py index c11f66a44..1e4e68cca 100755 --- a/radio/util/sport-parse.py +++ b/radio/util/sport-parse.py @@ -5,173 +5,178 @@ from __future__ import division, print_function -import os import sys import struct - START_STOP = '\x7e' -BYTESTUFF = '\x7d' +BYTESTUFF = '\x7d' STUFF_MASK = '\x20' DATA_FRAME = 0x10 - lineNumber = 0 sportDataBuff = "" quiet = False - def ParseFlVSS(packet, dataId, prim, appId, data, crc): - # if dataId != 0xa1: - # return - print("packet: %s (%4d)" % (dump(packet), lineNumber), end=' ') - cells = (data & 0xF0) >> 4 - battnumber = data & 0xF; - voltage1 = ((data & 0x000FFF00) >> 8) // 5 - voltage2 = ((data & 0xFFF00000) >> 20) // 5 - print(" FLVSS: no cells: %d, cell: %d: voltages: %0.2f %0.2f" % (cells, battnumber, voltage1/100., voltage2/100.)) + # if dataId != 0xa1: + # return + print("packet: %s (%4d)" % (dump(packet), lineNumber), end=' ') + cells = (data & 0xF0) >> 4 + battnumber = data & 0xF + voltage1 = ((data & 0x000FFF00) >> 8) // 5 + voltage2 = ((data & 0xFFF00000) >> 20) // 5 + print(" FLVSS: no cells: %d, cell: %d: voltages: %0.2f %0.2f" % (cells, battnumber, voltage1 / 100., voltage2 / 100.)) + def ParseRSSI(packet, dataId, prim, appId, data, crc): - print("packet: %s (%4d)" % (dump(packet), lineNumber), end=' ') - print(" RSSI: %d" % (data & 0xFF)) + print("packet: %s (%4d)" % (dump(packet), lineNumber), end=' ') + print(" RSSI: %d" % (data & 0xFF)) + def ParseAdc(packet, dataId, prim, appId, data, crc): - print("packet: %s (%4d)" % (dump(packet), lineNumber), end=' ') - print(" A%d: %d" % (dataId - 0xf102, data & 0xFF)) + print("packet: %s (%4d)" % (dump(packet), lineNumber), end=' ') + print(" A%d: %d" % (dataId - 0xf102, data & 0xFF)) + def ParseBatt(packet, dataId, prim, appId, data, crc): - print("packet: %s (%4d)" % (dump(packet), lineNumber), end=' ') - print(" Batt: %d" % (data & 0xFF)) + print("packet: %s (%4d)" % (dump(packet), lineNumber), end=' ') + print(" Batt: %d" % (data & 0xFF)) + def ParseSWR(packet, dataId, prim, appId, data, crc): - print("packet: %s (%4d)" % (dump(packet), lineNumber), end=' ') - print(" SWR: %d" % (data & 0xFF)) + print("packet: %s (%4d)" % (dump(packet), lineNumber), end=' ') + print(" SWR: %d" % (data & 0xFF)) + def ParseAirSpeed(packet, dataId, prim, appId, data, crc): - print "packet: %s (%4d)" % (dump(packet), lineNumber) , - print " Aspd: %.1f km/h" % (data/10.0) + print("packet: %s (%4d)" % (dump(packet), lineNumber), end=' ') + print(" Aspd: %.1f km/h" % (data / 10.0)) -appIdParsers = ( - (0x0300, 0x030f, ParseFlVSS), - (0xf101, 0xf101, ParseRSSI), - (0xf102, 0xf103, ParseAdc), - (0xf104, 0xf104, ParseBatt), - (0xf105, 0xf105, ParseSWR), - (0x0a00, 0x0a0f, ParseAirSpeed), + +appIdParsers = ( + (0x0300, 0x030f, ParseFlVSS), + (0xf101, 0xf101, ParseRSSI), + (0xf102, 0xf103, ParseAdc), + (0xf104, 0xf104, ParseBatt), + (0xf105, 0xf105, ParseSWR), ) -def dump(data, maxLen = None): - if maxLen and len(data) > maxLen: - data = data[:maxLen] - return ":".join("{:02x}".format(ord(c)) for c in data) + +def dump(data, maxLen=None): + if maxLen and len(data) > maxLen: + data = data[:maxLen] + return ":".join("{:02x}".format(ord(c)) for c in data) + def CheckSportCrc(packet): - return True + return True + def ParseSportPacket(packet): - global lineNumber - (dataId, prim, appId, data, crc) = struct.unpack('= firstId and appId <= lastId: - parser(packet, dataId, prim, appId, data, crc) - return - #no parser found - if not quiet: - print("\tdataId:%02x, prim:%02x, appId:%04x, data:%08x, crc:%02x)" % (dataId, prim, appId, data, crc)) - print("\tparser for appId %02x not implemented" % appId) + global lineNumber + (dataId, prim, appId, data, crc) = struct.unpack('= firstId and appId <= lastId: + parser(packet, dataId, prim, appId, data, crc) + return + # no parser found + if not quiet: + print("\tdataId:%02x, prim:%02x, appId:%04x, data:%08x, crc:%02x)" % (dataId, prim, appId, data, crc)) + print("\tparser for appId %02x not implemented" % appId) + def ParsePacket(packet): - global lineNumber - #unstuff packet - while True: - pos = packet.find(BYTESTUFF) - if pos == -1: break - #print "found stuff at %d in %s" % (pos, dump(packet, 20)) - #if we have nex char, then unstuff it - if len(packet) > pos+1: - unstuffed = ord(packet[pos]) ^ ord(STUFF_MASK); - #print "unstuffed data: %02x" % unstuffed - #buffer[pos] = chr(unstuffed) - packet = packet[:pos] + chr(unstuffed) + packet[pos+2:] - #print "buff after unstuff %s" % dump(packet, 20) - else: - #missin data, wait for more data - print("unstuff missing data") - return + global lineNumber + # unstuff packet + while True: + pos = packet.find(BYTESTUFF) + if pos == -1: + break + # print "found stuff at %d in %s" % (pos, dump(packet, 20)) + # if we have nex char, then unstuff it + if len(packet) > pos + 1: + unstuffed = ord(packet[pos]) ^ ord(STUFF_MASK) + # print "unstuffed data: %02x" % unstuffed + # buffer[pos] = chr(unstuffed) + packet = packet[:pos] + chr(unstuffed) + packet[pos + 2:] + # print "buff after unstuff %s" % dump(packet, 20) + else: + # missing data, wait for more data + print("unstuff missing data") + return - #print "packet: %s" % dump(packet, 10) - if len(packet) == 9: - # valid sport packet length - #print "\npacket: %s @%d" % (dump(packet), lineNumber) - #check crc - if not CheckSportCrc(packet): - print("error: wrong CRC for packet %s at line %d" % (dump(packet), lineNumber)) - ParseSportPacket(packet) - else: - if len(packet) > 1: - print("warning: wrong length %s for packet %s at line %d" % (len(packet), dump(packet, 10), lineNumber)) + # print "packet: %s" % dump(packet, 10) + if len(packet) == 9: + # valid sport packet length + # print "\npacket: %s @%d" % (dump(packet), lineNumber) + # check crc + if not CheckSportCrc(packet): + print("error: wrong CRC for packet %s at line %d" % (dump(packet), lineNumber)) + ParseSportPacket(packet) + else: + if len(packet) > 1: + print("warning: wrong length %s for packet %s at line %d" % (len(packet), dump(packet, 10), lineNumber)) def ParseSportData(data): - global sportDataBuff - #convert from hex - parts = data.split(' ') - binData = [chr(int(hex, 16)) for hex in parts] - #print binData - data = ''.join(binData) - sportDataBuff += data - #process whole packets - while True: - #find whole frame - # remove all data before START_STOP - # find next START_STOP - #print "start: %s" % dump(sportDataBuff, 10) - posStop = sportDataBuff.find(START_STOP) - # process pacet between two START_STOPs - if posStop > -1: - #print "found stop at %d" % posStop - ParsePacket(sportDataBuff[:posStop]) - # remove processed data - sportDataBuff = sportDataBuff[posStop+1:] - #print "after: %s" % dump(sportDataBuff, 10) - else: - break - - - + global sportDataBuff + # convert from hex + parts = data.split(' ') + binData = [chr(int(hex, 16)) for hex in parts] + # print binData + data = ''.join(binData) + sportDataBuff += data + # process whole packets + while True: + # find whole frame + # remove all data before START_STOP + # find next START_STOP + # print "start: %s" % dump(sportDataBuff, 10) + posStop = sportDataBuff.find(START_STOP) + # process pacet between two START_STOPs + if posStop > -1: + # print "found stop at %d" % posStop + ParsePacket(sportDataBuff[:posStop]) + # remove processed data + sportDataBuff = sportDataBuff[posStop + 1:] + # print "after: %s" % dump(sportDataBuff, 10) + else: + break inputFile = None if len(sys.argv) > 1: - inputFile = sys.argv[1] + inputFile = sys.argv[1] -#open input +# open input if inputFile: - inp = open(inputFile, 'r') + inp = open(inputFile, 'r') else: - inp = sys.stdin + inp = sys.stdin while True: - line = inp.readline() - lineNumber += 1 - if len(line) == 0: break - line = line.strip('\r\n') - if len(line) == 0: continue - #print line - parts = line.split(': ') - if len(parts) < 2: - print("weird data: \"%s\" at line %d" % (line, lineNumber)) - continue - sportData = parts[1].strip() - # print "sd: %s" % sportData - ParseSportData(sportData) + line = inp.readline() + lineNumber += 1 + if len(line) == 0: + break + line = line.strip('\r\n') + if len(line) == 0: + continue + # print line + parts = line.split(': ') + if len(parts) < 2: + print("weird data: \"%s\" at line %d" % (line, lineNumber)) + continue + sportData = parts[1].strip() + # print "sd: %s" % sportData + ParseSportData(sportData) From 4bfcfd0fc8a179f6a9d96d8224f6c2ed3be4064f Mon Sep 17 00:00:00 2001 From: Sean Vig Date: Fri, 9 Oct 2015 01:09:12 -0500 Subject: [PATCH 18/21] PEP8 radio/util/taranisicons.py Remove unused imports, fix whitespace, fix indentation --- radio/util/taranisicons.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/radio/util/taranisicons.py b/radio/util/taranisicons.py index ae108c89d..fc26296e1 100755 --- a/radio/util/taranisicons.py +++ b/radio/util/taranisicons.py @@ -1,17 +1,16 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -import sys from PyQt4 import Qt, QtGui -menu = [ "radio_setup", "model_select", "model_settings", "model_checklist", "files", "version" ] +menu = ["radio_setup", "model_select", "model_settings", "model_checklist", "files", "version"] -image = QtGui.QImage(24*8, 24, QtGui.QImage.Format_RGB32) +image = QtGui.QImage(24 * 8, 24, QtGui.QImage.Format_RGB32) image.fill(QtGui.QColor(255, 255, 255)) painter = QtGui.QPainter() painter.begin(image) for i, str in enumerate(menu): - icon = QtGui.QImage("../src/bitmaps/taranis/std/%s.png" % str) - painter.drawImage(Qt.QPoint(24*i, 0), icon) + icon = QtGui.QImage("../src/bitmaps/taranis/std/%s.png" % str) + painter.drawImage(Qt.QPoint(24 * i, 0), icon) painter.end() image.save("../src/bitmaps/taranis/mainmenu.png") From 5f698d2b178fc32caae4d65bb3f1a637732dbf5d Mon Sep 17 00:00:00 2001 From: Sean Vig Date: Fri, 9 Oct 2015 01:10:22 -0500 Subject: [PATCH 19/21] PEP8 radio/util/translate.py Remove unused imports, fix whitespace, fix undefined variable --- radio/util/translate.py | 24 ++++++++++-------------- 1 file changed, 10 insertions(+), 14 deletions(-) diff --git a/radio/util/translate.py b/radio/util/translate.py index d2ff4cb86..908e8be4f 100755 --- a/radio/util/translate.py +++ b/radio/util/translate.py @@ -3,9 +3,8 @@ # Imports import argparse -import os -import os.path import codecs +import sys translations = {'cz': [('\\200', u'á'), ('\\201', u'č'), @@ -55,7 +54,7 @@ translations = {'cz': [('\\200', u'á'), 'it': [('\\200', u'à'), ('\\201', u'ù')], - + 'pl': [('\\200', u'ą'), ('\\201', u'ć'), ('\\202', u'ę'), @@ -98,7 +97,7 @@ translations = {'cz': [('\\200', u'á'), ('\\222', u'Õ'), ('\\223', u'õ'), ('\\224', u'Ú'), - ('\\225', u'ú'),], + ('\\225', u'ú'), ], 'se': [('\\200', u'å'), ('\\201', u'ä'), @@ -106,7 +105,7 @@ translations = {'cz': [('\\200', u'á'), ('\\203', u'Å'), ('\\204', u'Ä'), ('\\205', u'Ö')], - + 'en': [], 'nl': [], @@ -115,8 +114,7 @@ translations = {'cz': [('\\200', u'á'), ('\\173', u'~'), ('\\036', u'\\n'), ('\\035', u'\\t')], - - } + } # Take care of command line options parser = argparse.ArgumentParser(description='Encoder for open9x translations') @@ -124,18 +122,18 @@ parser.add_argument('input', action="store", help="Input file name") parser.add_argument('output', action="store", help="Output file name") parser.add_argument('language', action="store", help="Two letter language identifier") parser.add_argument("--reverse", help="Reversed char conversion (from number to char)", action="store_true") -args = parser.parse_args() +args = parser.parse_args() if args.language not in translations: - parser.error(args.language + ' is not a supported language. Try one of the supported ones: ' + str(list(translations.keys()))) - system.exit() + parser.error(args.language + ' is not a supported language. Try one of the supported ones: ' + str(list(translations.keys()))) + sys.exit() if args.reverse: for translation in translations: translations[translation] = [(after, before) for (before, after) in translations[translation]] # Read the input file into a buffer -in_file = codecs.open( args.input, "r", "utf-8" ) +in_file = codecs.open(args.input, "r", "utf-8") # Write the result to a temporary file out_file = codecs.open(args.output, 'w', 'utf-8') @@ -156,9 +154,7 @@ for line in in_file.readlines(): c = "\\%03o" % (ord(c) - ord('0') + 27) after = after + c line = line[:32] + after + line[-2:] - out_file.write(line) + out_file.write(line) out_file.close() in_file.close() - - From 82c3230981e137edeca93173816461c455a06d66 Mon Sep 17 00:00:00 2001 From: Sean Vig Date: Sun, 11 Oct 2015 22:32:07 -0500 Subject: [PATCH 20/21] PEP8 and break up radio/util/tts.py Break up tts.py so that each language configuration of system and custom sounds is done in a separate file, also fixing PEP8 problems with tts.py, mostly whitespace related --- radio/util/tts.py | 845 ++++++------------------------------------- radio/util/tts_cz.py | 98 +++++ radio/util/tts_de.py | 85 +++++ radio/util/tts_en.py | 120 ++++++ radio/util/tts_es.py | 83 +++++ radio/util/tts_fr.py | 67 ++++ radio/util/tts_it.py | 100 +++++ radio/util/tts_pt.py | 81 +++++ 8 files changed, 751 insertions(+), 728 deletions(-) create mode 100644 radio/util/tts_cz.py create mode 100644 radio/util/tts_de.py create mode 100644 radio/util/tts_en.py create mode 100644 radio/util/tts_es.py create mode 100644 radio/util/tts_fr.py create mode 100644 radio/util/tts_it.py create mode 100644 radio/util/tts_pt.py diff --git a/radio/util/tts.py b/radio/util/tts.py index 6a9c02cf5..32a7dfa1d 100755 --- a/radio/util/tts.py +++ b/radio/util/tts.py @@ -9,18 +9,18 @@ # PyWin32 http://sourceforge.net/projects/pywin32/files/pywin32/ # # Note -# At the moment, pyTTS is only available for Python 2.3, 2.4 and 2.5. To use it for later versions without having to +# At the moment, pyTTS is only available for Python 2.3, 2.4 and 2.5. To use it for later versions without having to # recompile it, a quick and dirty solution is to: # copy the entire pyTTS directory from Python25\Lib\site-packages to Python26 or Python27 # replace TTSFast.py with an empty file. This way the version-dependent pyd file isn't loaded. -# in addition you will need some tools. +# in addition you will need some tools. # ffmpeg, sox, adconvertor ttscmd (2cnd speach centre) # have fun! # Sound pack maintainers (incomplete list) by language alphabetical order # Czech : Martin Hotar # French : Bertrand Songis & André Bernet -# English : Rob Thompson & Martin Hotar +# English : Rob Thompson & Martin Hotar # German : Romolo Manfredini (Some corrections by Peer) # Italian : Romolo Manfredini # Portuguese : Romolo Manfredini @@ -28,7 +28,10 @@ from __future__ import print_function -import os, sys, shutil, platform, subprocess, wave, zipfile +import os +import sys +import subprocess +import zipfile try: # Python 3 @@ -41,6 +44,7 @@ except ImportError: NO_ALTERNATE = 1024 + def filename(idx, alternate=0): if "gruvin9x" in sys.argv: ext = ".ad4" @@ -56,19 +60,20 @@ def filename(idx, alternate=0): result = "%04d%s" % (alternate, ext) return result + def wavstrip(filename): - output = "_" + filename - subprocess.Popen(["sox", filename, output, "silence", "1", "0.1", "0.1%", "reverse", "silence", "1", "0.1", "0.1%", "reverse"], stdout=subprocess.PIPE, stderr=subprocess.PIPE).wait() - os.remove(filename) - os.rename(output, filename) - - + output = "_" + filename + subprocess.Popen(["sox", filename, output, "silence", "1", "0.1", "0.1%", "reverse", "silence", "1", "0.1", "0.1%", "reverse"], stdout=subprocess.PIPE, stderr=subprocess.PIPE).wait() + os.remove(filename) + os.rename(output, filename) + + def generate(str, filename): print(filename, str) if not str: - str = " !" #this is so blank wav files never exist! - + str = " !" # this is so blank wav files never exist! + if "speak" in sys.argv: if "sapi" in sys.argv: tts.Speak(str) @@ -84,9 +89,9 @@ def generate(str, filename): if "sapi" in sys.argv: ttsfilename = "ttsfile.wav" tts.SpeakToWave(ttsfilename, str) - elif "sapi2" in sys.argv: - ttsfilename = "ttsfile.wav" - subprocess.Popen(["ttscmd", "/ttw", str.encode("utf-8"), ttsfilename, "-v", voiceID, "-b", "32","-s", "\"-3\"","-w","32","-f","47"], stdout=subprocess.PIPE, stderr=subprocess.PIPE).wait() + elif "sapi2" in sys.argv: + ttsfilename = "ttsfile.wav" + subprocess.Popen(["ttscmd", "/ttw", str.encode("utf-8"), ttsfilename, "-v", voiceID, "-b", "32", "-s", "\"-3\"", "-w", "32", "-f", "47"], stdout=subprocess.PIPE, stderr=subprocess.PIPE).wait() elif "espeak" in sys.argv: ttsfilename = "ttsfile.wav" subprocess.Popen(["espeak", "-v", espeakVoice, "-s", espeakspeed, "-z", "-w", ttsfilename, str.encode("utf-8")], stdout=subprocess.PIPE, stderr=subprocess.PIPE).wait() @@ -99,673 +104,52 @@ def generate(str, filename): conn.request("GET", u"/translate_tts?%s" % params, headers=headers) # conn.request("GET", "/translate_tts?ie=UTF-8&tl=%s&q=%s" % (directory, urllib.urlencode(str)), headers={"User-Agent": "Mozilla"}) resp = conn.getresponse() - file(ttsmp3, "wb").write(resp.read()) + with open(ttsmp3, "wb") as f: + f.write(resp.read()) subprocess.Popen(["ffmpeg", "-y", "-i", ttsmp3, "-acodec", "pcm_s16le", ttsfilename], stdout=subprocess.PIPE, stderr=subprocess.PIPE).wait() conn.close() - + else: print("which speach engine?") - exit() + exit() wavstrip(ttsfilename) - + if board in ('sky9x', 'taranis'): if 'sox' in sys.argv: maxvolume = subprocess.Popen(["sox", ttsfilename, "-n", "stat", "-v"], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[1] - if "not sound" in maxvolume: - subprocess.Popen(["sox", "--show-progress", filename, ttsfilename], stdout=subprocess.PIPE).communicate()[0]; - else: - subprocess.Popen(["sox", "--show-progress","-v", maxvolume, filename, ttsfilename], stdout=subprocess.PIPE).communicate()[0]; + if "not sound" in maxvolume: + subprocess.Popen(["sox", "--show-progress", filename, ttsfilename], stdout=subprocess.PIPE).communicate()[0] + else: + subprocess.Popen(["sox", "--show-progress", "-v", maxvolume, filename, ttsfilename], stdout=subprocess.PIPE).communicate()[0] if board == 'sky9x': - subprocess.Popen(["sox", "-twav", ttsfilename, "-b1600", "-c1", "-e", "a-law", filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE).wait() + subprocess.Popen(["sox", "-twav", ttsfilename, "-b1600", "-c1", "-e", "a-law", filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE).wait() else: - subprocess.Popen(["sox", "-twav", ttsfilename, "-b32000", "-c1", "-e", "a-law", filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE).wait() + subprocess.Popen(["sox", "-twav", ttsfilename, "-b32000", "-c1", "-e", "a-law", filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE).wait() else: if board == 'sky9x': - subprocess.Popen(["ffmpeg", "-y", "-i", ttsfilename, "-acodec", defaultcodec, "-ar", "16000", filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE).wait() + subprocess.Popen(["ffmpeg", "-y", "-i", ttsfilename, "-acodec", defaultcodec, "-ar", "16000", filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE).wait() else: - subprocess.Popen(["ffmpeg", "-y", "-i", ttsfilename, "-acodec", defaultcodec, "-ar", "32000", filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE).wait() + subprocess.Popen(["ffmpeg", "-y", "-i", ttsfilename, "-acodec", defaultcodec, "-ar", "32000", filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE).wait() elif board == 'gruvin9x': subprocess.Popen(["AD4CONVERTER", "-E4", ttsfilename], stdout=subprocess.PIPE, stderr=subprocess.PIPE).wait() - os.rename(ttsfilename.replace(".wav", ".ad4"), filename) + os.rename(ttsfilename.replace(".wav", ".ad4"), filename) else: subprocess.Popen(["ffmpeg", "-y", "-i", ttsfilename, "-acodec", "pcm_u8", "-ar", "16000", filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE).wait() os.remove(ttsfilename) ################################################################ -def ttsEn(): - systemSounds = [] - sounds = [] - - for i in range(100): - systemSounds.append((str(i), filename(PROMPT_SYSTEM_BASE+i))) - for i in range(9): - systemSounds.append((str(100*(i+1)), filename(PROMPT_SYSTEM_BASE+100+i))) - for i, s in enumerate(["thousand", "and", "minus", "point"]): - systemSounds.append((s, filename(PROMPT_SYSTEM_BASE+109+i))) - for i, s in enumerate(["volt", "volts", - "amp", "amps", - "milliamp", "milliamps", - "knot", "knots", - "meter per second", "meters per second", - "foot per second", "feet per second", - "kilometer per hour", "kilometers per hour", - "mile per hour", "miles per hour", - "meter", "meters", - "foot", "feet", - "degree celsius", "degrees celsius", - "degree fahrenheit", "degrees fahrenheit", - "percent", "percent", - "milliamp-hour", "milliamp-hours", - "watt", "watts", - "db", "db", - "r p m", "r p m", - "g", "g", - "degree", "degrees", - "milliliter", "milliliters", - "fluid ounce", "fluid ounces", - "hour", "hours", - "minute", "minutes", - "second", "seconds", - ]): - systemSounds.append((s, filename(PROMPT_SYSTEM_BASE+115+i))) - for i, s in enumerate(["point zero", "point one", "point two", "point three", - "point four", "point five", "point six", - "point seven", "point eight", "point nine"]): - systemSounds.append((s, filename(PROMPT_SYSTEM_BASE+165+i))) - for s, f, a in [(u"trim center", "midtrim", 495), - (u"maximum trim reached", "endtrim", NO_ALTERNATE), - (u"transmitter battery low", "lowbatt", 485), - (u"inactivity alarm", "inactiv", 486), - (u"throttle warning", "thralert", 481), - (u"switch warning", "swalert", 482), - (u"bad eeprom", "eebad", 483), - (u"Welcome to open tea ex!", "tada", 480), - (u"twenty. seconds", "timer20", 500), - (u"thirty. seconds", "timer30", 501), - (u"A1,low", "a1_org", NO_ALTERNATE), - (u"A1,critical", "a1_red", NO_ALTERNATE), - (u"A2,low", "a2_org", NO_ALTERNATE), - (u"A2,critical", "a2_red", NO_ALTERNATE), - (u"A3,low", "a3_org", NO_ALTERNATE), - (u"A3,critical", "a3_red", NO_ALTERNATE), - (u"A4,low", "a4_org", NO_ALTERNATE), - (u"A4,critical", "a4_red", NO_ALTERNATE), - (u"RF signal, low", "rssi_org", NO_ALTERNATE), - (u"RF signal, critical", "rssi_red", NO_ALTERNATE), - (u"radio antenna defective", "swr_red", NO_ALTERNATE), - (u"telemetry lost", "telemko", NO_ALTERNATE), - (u"telemetry recovered", "telemok", NO_ALTERNATE), - (u"trainer signal lost", "trainko", NO_ALTERNATE), - (u"trainer signal recovered", "trainok", NO_ALTERNATE), - ]: - systemSounds.append((s, filename(f, a))) - for i, (s, f) in enumerate([ - (u"gear!, up!", "gearup"), - (u"gear!, down!", "geardn"), - (u"flaps!, up!", "flapup"), - (u"flaps!, down!", "flapdn"), - (u"spoiler!, up!", "splrup"), - (u"spoiler!, down!", "splrdn"), - (u"trainer!, on!", "trnon"), - (u"trainer!, off!", "trnoff"), - (u"engine!, off!", "engoff"), - (u"too. high!", "tohigh"), - (u"too. low!", "tolow"), - (u"low. battery!", "lowbat"), - (u"crow!, on!", "crowon"), - (u"crow!, off!", "crowof"), - (u"rf. signal!, low!", "siglow"), - (u"rf. signal!, critical!", "sigcrt"), - (u"high. speed. mode!, active", "spdmod"), - (u"thermal. mode!, on", "thmmod"), - (u"normal. mode!, on", "nrmmod"), - (u"landing. mode!, on", "lnding"), - (u"acro. mode!, on", "acro"), - (u"flight. mode!, one", "fm-1"), - (u"flight. mode!, two", "fm-2"), - (u"flight. mode!, three", "fm-3"), - (u"flight. mode!, four", "fm-4"), - (u"flight. mode!, five", "fm-5"), - (u"flight. mode!, six", "fm-6"), - (u"flight. mode!, seven", "fm-7"), - (u"flight. mode!, eight", "fm-8"), - (u"vario!, on", "vrion"), - (u"vario!, off", "vrioff"), - (u"flight mode!, power", "fm-pwr"), - (u"flight mode!, land", "fm-lnd"), - (u"flight mode!, float", "fm-flt"), - (u"flight mode!, speed", "fm-spd"), - (u"flight mode!, fast", "fm-fst"), - (u"flight mode!, normal", "fm-nrm"), - (u"flight mode!, cruise", "fm-crs"), - (u"flight mode!, acro", "fm-acr"), - (u"flight mode!, race", "fm-rce"), - (u"flight mode!, launch", "fm-lch"), - (u"flight mode!, ping", "fm-png"), - (u"flight mode!, thermal", "fm-thm"), - (u"flight mode!, thermal left", "fm-thml"), - (u"flight mode!, thermal right", "fm-thmr"), - ]): - sounds.append((s, filename(f, PROMPT_CUSTOM_BASE+i))) - return systemSounds, sounds - -################################################################ - -def ttsFr(): - systemSounds = [] - sounds = [] - - for i in range(100): - systemSounds.append((str(i), filename(PROMPT_SYSTEM_BASE+i))) - for i in range(10): - systemSounds.append((str(100*(i+1)), filename(PROMPT_SYSTEM_BASE+100+i))) - for i, s in enumerate(["une", "onze", "vingt et une", "trente et une", "quarante et une", "cinquante et une", "soixante et une", "soixante et onze", "quatre vingt une"]): - systemSounds.append((s, filename(PROMPT_SYSTEM_BASE+110+i))) - for i, s in enumerate(["virgule", "et", "moins", "minuit", "midi"]): - systemSounds.append((s, filename(PROMPT_SYSTEM_BASE+119+i))) - for i, s in enumerate(["volts", u"ampères", u"milli ampères", u"knots", u"mètres seconde", u"pieds par seconde", u"kilomètre heure", u"miles par heure", u"mètres", "pieds", u"degrés", u"degrés fahrenheit", "pourcents", u"milli ampères / heure", "watt", "db", "tours minute", "g", u"degrés", "millilitres", "onces", "heure", "minute", "seconde"]): - systemSounds.append((s, filename(PROMPT_SYSTEM_BASE+125+i))) - #for i, s in enumerate(["timer", "", "tension", "tension", u"émission", u"réception", "altitude", "moteur", - # "essence", u"température", u"température", "vitesse", "distance", "altitude", u"élément lipo", - # "total lipo", "tension", "courant", "consommation", "puissance", u"accelération X", u"accelération Y", u"accelération Z", - # "orientation", "vario"]): - # systemSounds.append((s, filename(PROMPT_SYSTEM_BASE+146+i))) - for i, s in enumerate(["virgule 0", "virgule 1", "virgule 2", "virgule 3", "virgule 4", "virgule 5", "virgule 6", "virgule 7", "virgule 8", "virgule 9"]): - systemSounds.append((s, filename(PROMPT_SYSTEM_BASE+180+i))) - for s, f, a in [(u"Trim centré", "midtrim", 495), - (u"Trim maximum atteint", "endtrim", NO_ALTERNATE), - (u"Batterie radio faible !", "lowbatt", 485), - (u"Radio inactive !", "inactiv", 486), - (u"Alerte manche des gaz", "thralert", 481), - (u"Alerte inters", "swalert", 482), - (u"éprome corrompue", "eebad", 483), - (u"Bienvenue sur Open TI X!", "tada", 480), - (u"vingt secondes", "timer20", 500), - (u"trente secondes", "timer30", 501), - (u"A1,faible", "a1_org", NO_ALTERNATE), - (u"A1,critique", "a1_red", NO_ALTERNATE), - (u"A2,faible", "a2_org", NO_ALTERNATE), - (u"A2,critique", "a2_red", NO_ALTERNATE), - (u"A3,faible", "a3_org", NO_ALTERNATE), - (u"A3,critique", "a3_red", NO_ALTERNATE), - (u"A4,faible", "a4_org", NO_ALTERNATE), - (u"A4,critique", "a4_red", NO_ALTERNATE), - (u"Signal RF, faible", "rssi_org", NO_ALTERNATE), - (u"Signal RF, critique", "rssi_red", NO_ALTERNATE), - (u"Antenne défectueuse", "swr_red", NO_ALTERNATE), - (u"Plus de télémétrie", "telemko", NO_ALTERNATE), - (u"Télémétrie retrouvée", "telemok", NO_ALTERNATE), - (u"Signal écolage perdu", "trainko", NO_ALTERNATE), - (u"Signal écolage retrouvé", "trainok", NO_ALTERNATE), - ]: - systemSounds.append((s, filename(f, a))) - for i, (s, f) in enumerate([ - (u"altitude", "altitude"), - (u"température moteur", "moteur"), - (u"température contrôleur", "cntrleur"), - (u"train rentré", "gearup"), - (u"train sorti", "geardn"), - (u"volets rentrés", "flapup"), - (u"volets sortis", "flapdn"), - (u"atterrissage", "attero"), - (u"écolage", "trnon"), - (u"fin écolage", "trnoff"), - (u"moteur coupé", "engoff"), - ]): - sounds.append((s, filename(f, PROMPT_CUSTOM_BASE+i))) - return systemSounds, sounds - -################################################################ - -def ttsIt(): - systemSounds = [] - sounds = [] - - for i in range(101): - systemSounds.append((str(i), filename(PROMPT_SYSTEM_BASE+i))) - systemSounds.append(("mila", filename(PROMPT_SYSTEM_BASE+101))) - systemSounds.append(("mille", filename(PROMPT_SYSTEM_BASE+102))) - for i, s in enumerate(["virgola", "un", "e", "meno", "ora", "ore", "minuto", "minuti", "secondo", "secondi"]): - systemSounds.append((s, filename(PROMPT_SYSTEM_BASE+103+i))) - for i, s in enumerate(["", "", - "volt", "volt", - "ampere", "ampere", - "milliampers", "milliampers", - "nodo", "nodi", - "metro al secondo", "metri al secondo", - "piede al secondo", "piedi al secondo", - "chilometro ora", "chilometri ora", - "miglio per ora", "miglia per ora", - "metro", "metri", - "piede", "piedi", - "grado celsius", "gradi celsius", - "grado fahrenheit", "gradi fahrenheit", - "percento", "percento", - "milliampere ora", "milliampere ora", - "watt", "watt", - "decibel", "decibel", - "R P M", "R P M", - "g", "g", - "grado", "gradi", - "millilitro", "millilitri", - "oncia", "once"]): - systemSounds.append((s, filename(PROMPT_SYSTEM_BASE+113+i))) - for s, f, a in [(u"radio inattiva controllare", "inactiv", 486), - (u"batteria della radio scarica", "lowbatt", 485), - (u"controllo motore non in posizione, verificare", "thralert", 481), - (u"interruttori non in posizione, verificare", "swalert", 482), - (u"eeprom corrotta", "eebad", NO_ALTERNATE), - (u"formattazone eeprom in corso", "eeformat", NO_ALTERNATE), - (u"errore", "error", NO_ALTERNATE), - (u"trim centrato", "midtrim", 495), - (u"potenziometro centrato", "midpot", 496), - (u"massimo trim raggiunto", "endtrim", NO_ALTERNATE), - (u"venti secondi", "timer20", 500), - (u"trenta secondi", "timer30", 501), - (u"assorbimento elevato", "highmah", NO_ALTERNATE), - (u"temperatura elevata", "hightemp", NO_ALTERNATE), - (u"A1 in allarme", "a1_org", NO_ALTERNATE), - (u"A1 critico", "a1_red", NO_ALTERNATE), - (u"A2 in allarme", "a2_org", NO_ALTERNATE), - (u"A2 critico", "a2_red", NO_ALTERNATE), - (u"A3 in allarme", "a3_org", NO_ALTERNATE), - (u"A3 critico", "a3_red", NO_ALTERNATE), - (u"A4 in allarme", "a4_org", NO_ALTERNATE), - (u"A4 critico", "a4_red", NO_ALTERNATE), - (u"Segnale radio basso", "rssi_org", NO_ALTERNATE), - (u"Segnale radio critico", "rssi_red", NO_ALTERNATE), - (u"Problema all'antenna della radio", "swr_red", NO_ALTERNATE), - (u"Telemetria assente", "telemko", NO_ALTERNATE), - (u"Telemetria disponibile", "telemok", NO_ALTERNATE), - ]: - systemSounds.append((s, filename(f, a))) - for i, s in enumerate([u"timer", u"", u"tensione", u"tensione", u"trasmissione", u"ricezione", u"altitudine", u"motore", - u"carburante", u"temperatura", u"temperatura", u"velocità", "distanza", u"altitudine", u"cella lipo", - u"totale lipo", u"tensione", u"corrente", u"consumo", u"potenza", u"accellerazione X", u"accellerazione Y", u"accellerazione Z", - u"direzione", u"variometro",u"minimo",u"massimo"]): - systemSounds.append((s, filename(PROMPT_SYSTEM_BASE+135+i))) - for i, (s, f) in enumerate([ - (u"carrello chiuso", "gearup"), - (u"carrello aperto", "geardn"), - (u"flap rientrati", "flapup"), - (u"flap estesi", "flapdn"), - (u"atterraggiio", "attero"), - (u"modalità maestro attiva", "trnon"), - (u"modalità maestro disattiva", "trnoff"), - (u"motore spento", "engoff"), - (u"troppo alto", "tohigh"), - (u"troppo basso", "tolow"), - (u"batteria scarica", "lowbat"), - (u"crow on", "crowon"), - (u"crow off", "crowof"), - (u"modo velocità", "spdmod"), - (u"modo termica", "thmmod"), - (u"modo volo normale", "nrmmod"), - (u"fase di volo 1", "fltmd1"), - (u"fase di volo 2", "fltmd2"), - (u"fase di volo 3", "fltmd3"), - (u"fase di volo 4", "fltmd4"), - (u"fase di volo 5", "fltmd5"), - (u"fase di volo 6", "fltmd6"), - (u"fase di volo 7", "fltmd7"), - (u"fase di volo 8", "fltmd8"), - (u"fase di volo 9", "fltmd9"), - ]): - sounds.append((s, filename(f, PROMPT_CUSTOM_BASE+i))) - return systemSounds, sounds - -################################################################ - -def ttsPt(): - systemSounds = [] - sounds = [] - - for i in range(101): - systemSounds.append((str(i), filename(PROMPT_SYSTEM_BASE+i))) - systemSounds.append(("cento", filename(PROMPT_SYSTEM_BASE+101))) - systemSounds.append(("duzentos", filename(PROMPT_SYSTEM_BASE+102))) - systemSounds.append(("trezentos", filename(PROMPT_SYSTEM_BASE+103))) - systemSounds.append(("quatrocentos", filename(PROMPT_SYSTEM_BASE+104))) - systemSounds.append(("quinhentos", filename(PROMPT_SYSTEM_BASE+105))) - systemSounds.append(("seiscentos", filename(PROMPT_SYSTEM_BASE+106))) - systemSounds.append(("setecentos", filename(PROMPT_SYSTEM_BASE+107))) - systemSounds.append(("oitocentos", filename(PROMPT_SYSTEM_BASE+108))) - systemSounds.append(("novecentos", filename(PROMPT_SYSTEM_BASE+109))) - systemSounds.append(("mil", filename(PROMPT_SYSTEM_BASE+110))) - for i, s in enumerate(["virgula", "uma", "duas", "e", "menos", "hora", "horas", "minuto", "minutos", "segundo", "segundos"]): - systemSounds.append((s, filename(PROMPT_SYSTEM_BASE+111+i))) - for i, s in enumerate([u"Volt", u"ampére", u"metros por segundo", u"", u"quilômetros por hora", u"metros", u"graus", u"cento", u"miliamperes", u"miliamperes por hora", u"watt", u"db", u"pés", u"nós", u"horas", u"minutos", u"segundos", u"RPM", u"g", u"mililitri", u"onças"]): - systemSounds.append((s, filename(PROMPT_SYSTEM_BASE+122+i))) - for s, f, a in [(u"atenção, o rádio foi esquecido ligado, por favor desligue-o", "inactiv", 486), - (u"bateria do rádio fraca", "lowbatt", 485), - (u"atenção,acelerador não está no mínimo", "thralert", 481), - (u"atenção, certifique-se que os interruptores estão na posição certa", "swalert", 482), - (u"eeprom corrompida", "eebad", NO_ALTERNATE), - (u"formatação da eeprom em curso", "eeformat", NO_ALTERNATE), - (u"erro", "error", NO_ALTERNATE), - (u"trim centrado", "midtrim", 495), - (u"potenciómetro centrado", "midpot", 496), - (u"trim no máximo", "endtrim", NO_ALTERNATE), - (u"20 segundos", "timer20", 500), - (u"30 segundos", "timer30", 501), - (u"assorbimento elevato", "highmah", NO_ALTERNATE), - (u"temperatura elevata", "hightemp", NO_ALTERNATE), - (u"Alarme A1", "a1_org", NO_ALTERNATE), - (u"A1 critica", "a1_red", NO_ALTERNATE), - (u"Alarme A2", "a2_org", NO_ALTERNATE), - (u"A2 critica", "a2_red", NO_ALTERNATE), - (u"recepção de sinal muito baixa", "rssi_org", NO_ALTERNATE), - (u"recepção de sinal crítica", "rssi_red", NO_ALTERNATE), - (u"Problema com a antena do transmissor", "swr_red", NO_ALTERNATE), - ]: - systemSounds.append((s, filename(f, a))) - for i, s in enumerate([u"cronómetro", u"cronómetro", u"transmissão", u"recepção", u"A1", u"A2", u"altitude", u"motor", - u"combustível", u"temperatura", u"temperatura", u"velocidade", u"distância", u"altitude", u"célula lipo", - u"Total lipo", u"tensão", u"corrente", u"consumo", u"potência", u"aceleração X", u"aceleração Y", u"aceleração Z", - u"Direcção", u"variómetro", u"mínimo", u"máximo"]): - systemSounds.append((s, filename(PROMPT_SYSTEM_BASE+141+i))) - for i, (s, f) in enumerate([ - (u"trem, em cima.", "gearup"), - (u"trem, em baixo.", "geardn"), - (u"flaps recolhidos", "flapup"), - (u"flaps estendidos", "flapdn"), - (u"aterragem", "attero"), - (u"modo de treino ligado", "trnon"), - (u"modo de treino desligado", "trnoff"), - (u"motor desligado", "engoff"), - (u"muito alto", "tohigh"), - (u"muito baixo", "tolow"), - (u"bateria fraca", "lowbat"), - (u"crou, activo", "crowon"), - (u"crou, desligado", "crowof"), - (u"modo de velocidade", "spdmod"), - (u"modo de térmica", "thmmod"), - (u"modo de voo normal", "nrmmod"), - (u"fase de voo 1", "fltmd1"), - (u"fase de voo 2", "fltmd2"), - (u"fase de voo 3", "fltmd3"), - (u"fase de voo 4", "fltmd4"), - (u"fase de voo 5", "fltmd5"), - (u"fase de vôo 6", "fltmd6"), - (u"fase de voo 7", "fltmd7"), - (u"fase de voo 8", "fltmd8"), - (u"fase de voo 9", "fltmd9"), - ]): - sounds.append((s, filename(f, PROMPT_CUSTOM_BASE+i))) - return systemSounds, sounds - -################################################################ - -def ttsEs(): - systemSounds = [] - sounds = [] - - for i in range(101): - systemSounds.append((str(i), filename(PROMPT_SYSTEM_BASE+i))) - systemSounds.append(("ciento", filename(PROMPT_SYSTEM_BASE+101))) - systemSounds.append(("doscientos", filename(PROMPT_SYSTEM_BASE+102))) - systemSounds.append(("trescientos", filename(PROMPT_SYSTEM_BASE+103))) - systemSounds.append(("cuatrocientos", filename(PROMPT_SYSTEM_BASE+104))) - systemSounds.append(("quinientos", filename(PROMPT_SYSTEM_BASE+105))) - systemSounds.append(("sescientos", filename(PROMPT_SYSTEM_BASE+106))) - systemSounds.append(("setecientos", filename(PROMPT_SYSTEM_BASE+107))) - systemSounds.append(("ochocientos", filename(PROMPT_SYSTEM_BASE+108))) - systemSounds.append(("nuevecientos", filename(PROMPT_SYSTEM_BASE+109))) - systemSounds.append(("mil", filename(PROMPT_SYSTEM_BASE+110))) - for i, s in enumerate(["coma", "un", "una", "y", "meno", "hora", "horas", "minuto", "minutos", "segundo", "segundos"]): - systemSounds.append((s, filename(PROMPT_SYSTEM_BASE+111+i))) - for i, s in enumerate([u"Voltio", u"ampério", u"metros por segundo", u"", u"kilómetro por hora", u"metros", u"grados", u"por ciento", u"miliamperios", u"miliamperios por hora", u"vatio", u"db", u"pés", u"nós", u"horas", u"minutos", u"segundos", u"RPM", u"g", u"mililitro", u"onzas"]): - systemSounds.append((s, filename(PROMPT_SYSTEM_BASE+122+i))) - for s, f, a in [(u"me tienes abandonada", "inactiv", 486), - (u"batería del transmisor baja", "lowbatt", 485), - (u"El acelerador está activado, por favor, corrijalo", "thralert", 481), - (u"Los interruptores no están en la posición correcta, por favor corrijalo", "swalert", 482), - (u"eeprom corrompida", "eebad", NO_ALTERNATE), - (u"Formateo de eeprom en curso", "eeformat", NO_ALTERNATE), - (u"error", "error", NO_ALTERNATE), - (u"trim centrado", "midtrim", 495), - (u"potenciómetro centrado", "midpot", 496), - (u"trim al máximo", "endtrim", NO_ALTERNATE), - (u"20 segundos", "timer20", 500), - (u"30 segundos", "timer30", 501), - (u"assorbimiento elevado", "highmah", NO_ALTERNATE), - (u"temperatura elevada", "hightemp", NO_ALTERNATE), - (u"Alarma A1", "a1_org", NO_ALTERNATE), - (u"A1 crítica", "a1_red", NO_ALTERNATE), - (u"Alarma A2", "a2_org", NO_ALTERNATE), - (u"A2 crítica", "a2_red", NO_ALTERNATE), - (u"recepcion de señal baja", "rssi_org", NO_ALTERNATE), - (u"recepción de señal crítica", "rssi_red", NO_ALTERNATE), - (u"Problemas con la antena del transmisor", "swr_red", NO_ALTERNATE), - (u"Sin telemetría", "telemko", NO_ALTERNATE), - (u"Telemetría disponible", "telemok", NO_ALTERNATE), - ]: - systemSounds.append((s, filename(f, a))) - for i, s in enumerate([u"cronómetro", u"cronómetro", u"transmisión", u"recepción", u"A1", u"A2", u"altitud", u"motor", - u"combustible", u"temperatura", u"temperatura", u"velocidad", u"distancia", u"altitude", u"célula lipo", - u"Total lipo", u"voltaje", u"corriente", u"consumo", u"potencia", u"aceleración X", u"aceleración Y", u"aceleración Z", - u"dirección", u"variómetro", u"minimo", u"máximo"]): - systemSounds.append((s, filename(PROMPT_SYSTEM_BASE+141+i))) - for i, (s, f) in enumerate([ - (u"tren arriba.", "gearup"), - (u"tren abajo.", "geardn"), - (u"flaps arriba", "flapup"), - (u"flaps abajo", "flapdn"), - (u"aterrizaje", "attero"), - (u"modo de entrenamiento activado", "trnon"), - (u"modo de entrenamiento deshabilitado", "trnoff"), - (u"motor apagado", "engoff"), - (u"muy alto", "tohigh"), - (u"muy bajo", "tolow"), - (u"bateria baja", "lowbat"), - (u"crou, activo", "crowon"), - (u"crou, desligado", "crowof"), - (u"modo de velocidad", "spdmod"), - (u"modo de térmica", "thmmod"), - (u"modo de vuelo normal", "nrmmod"), - (u"fase de vuelo 1", "fltmd1"), - (u"fase de vuelo 2", "fltmd2"), - (u"fase de vuelo 3", "fltmd3"), - (u"fase de vuelo 4", "fltmd4"), - (u"fase de vuelo 5", "fltmd5"), - (u"fase de vuelo 6", "fltmd6"), - (u"fase de vuelo 7", "fltmd7"), - (u"fase de vuelo 8", "fltmd8"), - (u"fase de vuelo 9", "fltmd9"), - ]): - sounds.append((s, filename(f, PROMPT_CUSTOM_BASE+i))) - return systemSounds, sounds - -################################################################ - -def ttsDe(): - systemSounds = [] - sounds = [] - - for i in range(101): - systemSounds.append((str(i), filename(PROMPT_SYSTEM_BASE+i))) - systemSounds.append(("tausend", filename(PROMPT_SYSTEM_BASE+101))) - for i, s in enumerate(["comma", "und", "minus", "uhr", "minute", "minuten", "sekunde", "sekunden"]): - systemSounds.append((s, filename(PROMPT_SYSTEM_BASE+102+i))) - for i, s in enumerate(["", "Volt", "Ampere", "MilliAmpere", "Knoten", "Meter pro sekunde", "Fuesse pro sekunde", "kilometer pro stunde", "Meilen pro Stunde", "Meter", "Fuesse", "Grad", "Grad Fahrenheit", "Prozent", "Milliampere pro stunde", "Watt", "db", "R P M", "g", "Milliliter", "Unze", "Uhr", "Minuten", "Secunden",]): - systemSounds.append((s, filename(PROMPT_SYSTEM_BASE+110+i))) - for s, f, a in [(u"Sender ist inaktiv,bitte Ueberpruefen Sie", "inactiv", 486), - (u"Senderakku niedrig", "lowbatt", 485), - (u"Gaskanal nicht Null, bitte pruefen", "thralert", 481), - (u"Schalten fehlpositioniert, bitte pruefen", "swalert", 482), - (u"Das EEPROM ist fehlerhaft", "eebad", NO_ALTERNATE), - (u"Das EEPROM ist immer formatiert", "eeformat", NO_ALTERNATE), - (u"fehler", "error", NO_ALTERNATE), - (u"Trim zentriert", "midtrim", 495), - (u"Poti zentriert", "midpot", 496), - (u"Maximale trimmung erreicht", "endtrim", NO_ALTERNATE), - (u"20 sekunden", "timer20", 500), - (u"30 sekunden", "timer30", 501), - (u"Senderstrom ist zu hoch!", "highmah", NO_ALTERNATE), - (u"Sendertemperatur ist zu hoch!", "hightemp", NO_ALTERNATE), - (u"A1 schlecht!", "a1_org", NO_ALTERNATE), - (u"A1 kritisch!", "a1_red", NO_ALTERNATE), - (u"A2 schlecht!", "a2_org", NO_ALTERNATE), - (u"A2 kritisch!", "a2_red", NO_ALTERNATE), - (u"A3 schlecht!", "a3_org", NO_ALTERNATE), - (u"A3 kritisch!", "a3_red", NO_ALTERNATE), - (u"A4 schlecht!", "a4_org", NO_ALTERNATE), - (u"A4 kritisch!", "a4_red", NO_ALTERNATE), - (u"Funksignal schlecht!", "rssi_org", NO_ALTERNATE), - (u"Funksignal kritisch!", "rssi_red", NO_ALTERNATE), - (u"Problem mit der sender Antenna", "swr_red", NO_ALTERNATE), - (u"Telemetrie verloren", "telemko", NO_ALTERNATE), - (u"Telemetrie wiederhergestellt", "telemok", NO_ALTERNATE), - (u"Schülersignal verloren", "trainko", NO_ALTERNATE), - (u"Schülersignal wiederhergestellt", "trainok", NO_ALTERNATE), - ]: - systemSounds.append((s, filename(f, a))) - for i, s in enumerate(["Timer", "Timer", "Sendung", "Empfang", "A1", "A2", "Hoehe", "Motor", - "Treibstoff", "Temperatur", "Temperatur", "Geschwindigkeit", "Ferne", "Hoehe", "Lipo-Zelle", - "Zellen gesamt", "Spannung", "Strom", "Verbrauch", "Power", "Beschleunigung X", "Beschleunigung Y", "Beschleunigung Z", - "Richtung", "Variometer","Minimum","Maximum"]): - systemSounds.append((s, filename(PROMPT_SYSTEM_BASE+134+i))) - for i, (s, f) in enumerate([ - (u"Fahrwerk eingezogen", "gearup"), - (u"Fahrwerk ausgefahren", "geardn"), - (u"Klappen eingefahren", "flapup"), - (u"Klappen ausgefahren", "flapdn"), - (u"Landung", "attero"), - (u"Trainer-Modus ein", "trnon"), - (u"Trainer-Modus aus", "trnoff"), - (u"Motor aus", "engoff"), - (u"zu hoch", "tohigh"), - (u"zu niedrig", "tolow"), - (u"Batterie schwach", "lowbat"), - (u"crow ein", "crowon"), - (u"crow aus", "crowof"), - (u"Schnell-Modus ist aktiviert", "spdmod"), - (u"Thermik-Modus ist aktiviert", "thmmod"), - (u"Normal-Modus ist aktiviert", "nrmmod"), - (u"Regime 1", "fltmd1"), - (u"Regime 2", "fltmd2"), - (u"Regime 3", "fltmd3"), - (u"Regime 4", "fltmd4"), - (u"Regime 5", "fltmd5"), - (u"Regime 6", "fltmd6"), - (u"Regime 7", "fltmd7"), - (u"Regime 8", "fltmd8"), - (u"Regime 9", "fltmd9"), - ]): - sounds.append((s, filename(f, PROMPT_CUSTOM_BASE+i))) - return systemSounds, sounds - -################################################################ - -def ttsCz(): - systemSounds = [] - sounds = [] - - for i, s in enumerate(["nula", "jedna", "dva"]): - systemSounds.append((s, filename(PROMPT_SYSTEM_BASE+i))) - for i in range(97): - systemSounds.append((str(3+i), filename(PROMPT_SYSTEM_BASE+3+i))) - for i, s in enumerate(["sto", u"dvěsta", u"třista", u"čtyřista", u"pětset", u"šestset", "sedmset", "osmset", - u"devětset", u"tisíc"]): - systemSounds.append((s, filename(PROMPT_SYSTEM_BASE+100+i))) - for i, s in enumerate([u"tisíce", "jeden", "jedno", u"dvě", u"celá", u"celé", u"celých", u"mínus"]): - systemSounds.append((s, filename(PROMPT_SYSTEM_BASE+110+i))) - - for i, s in enumerate(["volt", "volty", u"voltů", "voltu", - u"ampér", u"ampéry", u"ampérů", u"ampéru", - u"miliampér", u"miliampéry", u"miliampérů", u"miliampéru", - u"uzel", u"uzly", u"uzlů", u"uzlu", - "metr za sekundu", "metry za sekundu", u"metrů za sekundu", "metru za sekundu", - "stopa za sekundu", "stopy za sekundu", "stop za sekundu", "stopy za sekundu", - "kilometr za hodinu", "kilometry za hodinu", u"kilometrů za hodinu", "kilometru za hodinu", - u"míle za hodinu", u"míle za hodinu", u"mil za hodinu", u"míle za hodinu", - "metr", "metry", u"metrů", "metru", - "stopa", "stopy", "stop", "stopy", - u"stupeň celsia", u"stupně celsia", u"stupňů celsia", u"stupně celsia", - u"stupeň fahrenheita", u"stupně fahrenheita", u"stupňů fahrenheita", u"stupně fahrenheita", - "procento", "procenta", "procent", "procenta", - u"miliampérhodina", u"miliampérhodiny", u"miliampérhodin", u"miliampérhodiny", - "vat", "vaty", u"vatů", "vatu", - "decibel", "decibely", u"decibelů", "decibelu", - u"otáčka za minutu", u"otáčky za minutu", u"otáček za minutu", u"otáčky za minutu", - u"gé", u"gé", u"gé", u"gé" - u"stupeň", u"stupně", u"stupňů", u"stupně", - u"mililitr", u"mililitry", u"mililitrů", "mililitru", - u"dutá unce", u"duté unce", u"dutých uncí", u"duté unce", - "hodina", "hodiny", "hodin", "hodiny", - "minuta", "minuty", "minut", "minuty", - "sekunda", "sekundy", "sekund", "sekundy", - ]): - systemSounds.append((s, filename(PROMPT_SYSTEM_BASE+118+i))) - - for s, f, a in [(u"střed trimu", "midtrim", 495), - (u"maximum trimu", "endtrim", NO_ALTERNATE), - (u"baterie rádia je vybitá", "lowbatt", 485), - (u"zapoměl jsi na mě!", "inactiv", 486), - (u"plyn není na nule", "thralert", 481), - (u"přepínače nejsou ve výchozí poloze", "swalert", 482), - (u"neplatná eeprom", "eebad", 483), - (u"Oupn najn iks", "tada", 480), - (u"dvacet sekund", "timer20", 500), - (u"třicet sekund", "timer30", 501), - (u"A1,nízká", "a1_org", NO_ALTERNATE), - (u"A1,kritická", "a1_red", NO_ALTERNATE), - (u"A2,nízká", "a2_org", NO_ALTERNATE), - (u"A2,kritická", "a2_red", NO_ALTERNATE), - (u"A3,nízká", "a3_org", NO_ALTERNATE), - (u"A3,kritická", "a3_red", NO_ALTERNATE), - (u"A4,nízká", "a4_org", NO_ALTERNATE), - (u"A4,kritická", "a4_red", NO_ALTERNATE), - (u"nízký RF signál", "rssi_org", NO_ALTERNATE), - (u"kritický RF signál", "rssi_red", NO_ALTERNATE), - (u"problém s anténou rádia", "swr_red", NO_ALTERNATE), - (u"telemetrie ztracena", "telemko", NO_ALTERNATE), - (u"telemetrie je funkční", "telemok", NO_ALTERNATE), - (u"trenér port odpojen", "trainko", NO_ALTERNATE), - (u"trenér port připojen", "trainok", NO_ALTERNATE), - ]: - systemSounds.append((s, filename(f, a))) - for i, (s, f) in enumerate([ - (u"podvozek je zasunut", "podvoz0"), - (u"podvozek je vysunut", "podvoz1"), - (u"klapky jsou zapnuty", "klapky1"), - (u"klapky jsou vypnuty", "klapky0"), - (u"trenér je zapnut", "trener1"), - (u"trenér je vypnutý", "trener0"), - (u"motor je vypnut", "motor0"), - (u"motor je aktivován", "motor1"), - (u"jsi příliš vysoko", "vysoko"), - (u"jsi příliš nízko", "nizko"), - (u"baterie modelu je vybitá", "batvybit"), - (u"dochází palivo", "palivo"), - (u"nízký signál!", "nsignal"), - (u"kritický signál!", "ksignal"), - (u"rychlý režim aktivován", "r_rychly"), - (u"termický režim aktivován", "r_termik"), - (u"normální režim aktivován", "r_norm"), - (u"režim start aktivován", "r_start"), - (u"režim přistání aktivován", "r_prista"), - (u"vario je zapnuto", "vario0"), - (u"vario je vypnuto", "vario1"), - (u"start povolen", "startok"), - ]): - sounds.append((s, filename(f, PROMPT_CUSTOM_BASE+i))) - return systemSounds, sounds - -################################################################ - if __name__ == "__main__": - + if "sky9x" in sys.argv: board = "sky9x" PROMPT_CUSTOM_BASE = 256 PROMPT_SYSTEM_BASE = 0 - elif "taranis" in sys.argv: + elif "taranis" in sys.argv: board = "taranis" PROMPT_CUSTOM_BASE = 256 - PROMPT_SYSTEM_BASE = 0 + PROMPT_SYSTEM_BASE = 0 elif "gruvin9x" in sys.argv: board = "gruvin9x" PROMPT_CUSTOM_BASE = 0 @@ -784,60 +168,63 @@ if __name__ == "__main__": if "list" in sys.argv: print(tts.GetVoiceNames()) exit() - + if "mulaw" in sys.argv: defaultcodec = "pcm_mulaw" else: defaultcodec = "pcm_alaw" - + if "en" in sys.argv: + from tts_en import systemSounds, sounds + directory = "en" voice = "english" if "sapi" in sys.argv: if "scottish" in sys.argv: tts.SetVoiceByName("ScanSoftFiona_Full_22kHz") voice = "english-scottish" - elif "american" in sys.argv: - tts.SetVoiceByName("ScanSoftJennifer_Full_22kHz") - voice = "english-american" - elif "australian" in sys.argv: + elif "american" in sys.argv: + tts.SetVoiceByName("ScanSoftJennifer_Full_22kHz") + voice = "english-american" + elif "australian" in sys.argv: tts.SetVoiceByName("ScanSoftKaren_Full_22kHz") - voice = "english-australian" + voice = "english-australian" elif "irish" in sys.argv: tts.SetVoiceByName("ScanSoftMoira_Full_22kHz") - voice = "english-irish" + voice = "english-irish" else: tts.SetVoiceByName("ScanSoftFiona_Full_22kHz") voice = "english-english" elif "sapi2" in sys.argv: if "scottish" in sys.argv: - voiceID = "17" - voice = "english-scottish" - elif "american" in sys.argv: - voiceID = "18" - voice = "english-american" - elif "australian" in sys.argv: - voiceID = "20" - voice = "english-australian" + voiceID = "17" + voice = "english-scottish" + elif "american" in sys.argv: + voiceID = "18" + voice = "english-american" + elif "australian" in sys.argv: + voiceID = "20" + voice = "english-australian" elif "irish" in sys.argv: - voiceID = "21" - voice = "english-irish" + voiceID = "21" + voice = "english-irish" elif "french" in sys.argv: - voiceID = "19" - voice = "english-french" + voiceID = "19" + voice = "english-french" elif "german" in sys.argv: - voiceID = "22" - voice = "english-german" + voiceID = "22" + voice = "english-german" else: - voiceID = "17" - voice = "english-english" - + voiceID = "17" + voice = "english-english" + elif "espeak" in sys.argv: espeakVoice = "mb-us1" espeakspeed = "150" - systemSounds, sounds = ttsEn() - + elif "fr" in sys.argv: + from tts_fr import systemSounds, sounds + directory = "fr" voice = "french" if "sapi" in sys.argv: @@ -845,9 +232,10 @@ if __name__ == "__main__": elif "espeak" in sys.argv: espeakVoice = "mb-fr4+f4" espeakspeed = "140" - systemSounds, sounds = ttsFr() - + elif "it" in sys.argv: + from tts_it import systemSounds, sounds + directory = "it" voice = "italian" if "sapi" in sys.argv: @@ -855,9 +243,10 @@ if __name__ == "__main__": elif "espeak" in sys.argv: espeakVoice = "mb-it4" espeakspeed = "160" - systemSounds, sounds = ttsIt() - + elif "de" in sys.argv: + from tts_de import systemSounds, sounds + directory = "de" voice = "german" if "sapi" in sys.argv: @@ -865,9 +254,10 @@ if __name__ == "__main__": elif "espeak" in sys.argv: espeakVoice = "mb-de4" espeakspeed = "160" - systemSounds, sounds = ttsDe() elif "pt" in sys.argv: + from tts_pt import systemSounds, sounds + directory = "pt" voice = "portuguese" if "sapi" in sys.argv: @@ -875,9 +265,10 @@ if __name__ == "__main__": elif "espeak" in sys.argv: espeakVoice = "mb-pt1+f1" espeakspeed = "160" - systemSounds, sounds = ttsPt() elif "es" in sys.argv: + from tts_es import systemSounds, sounds + directory = "es" voice = "spanish" if "sapi" in sys.argv: @@ -885,57 +276,55 @@ if __name__ == "__main__": elif "espeak" in sys.argv: espeakVoice = "mb-es1+f1" espeakspeed = "160" - systemSounds, sounds = ttsEs() - + elif "cz" in sys.argv: + from tts_cz import systemSounds, sounds + directory = "cz" - voice = "czech" + voice = "czech" if "sapi" in sys.argv: tts.SetVoiceByName("ScanSoftZuzana_Full_22kHz") elif "espeak" in sys.argv: espeakVoice = "mb-cz2" espeakspeed = "150" - systemSounds, sounds = ttsCz() - + else: print("which language?") - exit() - + exit() + if "csv" in sys.argv: - csvFile = open("%s-%s.csv" % (voice, board), "w") - for s, f in systemSounds: - if s and f: - l = u"" - if board in ("sky9x", "taranis"): - l += u"SOUNDS/%s/SYSTEM;" % directory - l += f + u";" + s + u"\n" - csvFile.write(l.encode("utf-8")) - for s, f in sounds: - if s and f: - l = u"" - if board in ("sky9x", "taranis"): - l += u"SOUNDS/%s;" % directory - l += f + u";" + s + u"\n" - csvFile.write(l.encode("utf-8")) - csvFile.close() - + with open("%s-%s.csv" % (voice, board), "w") as csvFile: + for s, f in systemSounds: + if s and f: + l = u"" + if board in ("sky9x", "taranis"): + l += u"SOUNDS/%s/SYSTEM;" % directory + l += f + u";" + s + u"\n" + csvFile.write(l.encode("utf-8")) + for s, f in sounds: + if s and f: + l = u"" + if board in ("sky9x", "taranis"): + l += u"SOUNDS/%s;" % directory + l += f + u";" + s + u"\n" + csvFile.write(l.encode("utf-8")) + if "zip" in sys.argv: zip_name = "%s-%s.zip" % (voice, board) - zip = zipfile.ZipFile(zip_name, "w", zipfile.ZIP_DEFLATED) - for s, f in systemSounds: - if s and f: - generate(s, f) - if board in ("sky9x", "taranis"): - zip.write(f, "SOUNDS/%s/SYSTEM/" % directory + f) - else: - zip.write(f, f) - os.remove(f) - for s, f in sounds: - if s and f: - generate(s, f) - if board in ("sky9x", "taranis"): - zip.write(f, "SOUNDS/%s/" % directory + f) - else: - zip.write(f, f) - os.remove(f) - zip.close() + with zipfile.ZipFile(zip_name, "w", zipfile.ZIP_DEFLATED) as zip: + for s, f in systemSounds: + if s and f: + generate(s, f) + if board in ("sky9x", "taranis"): + zip.write(f, "SOUNDS/%s/SYSTEM/" % directory + f) + else: + zip.write(f, f) + os.remove(f) + for s, f in sounds: + if s and f: + generate(s, f) + if board in ("sky9x", "taranis"): + zip.write(f, "SOUNDS/%s/" % directory + f) + else: + zip.write(f, f) + os.remove(f) diff --git a/radio/util/tts_cz.py b/radio/util/tts_cz.py new file mode 100644 index 000000000..94ee32d59 --- /dev/null +++ b/radio/util/tts_cz.py @@ -0,0 +1,98 @@ +# -*- coding: utf-8 -*- + +# Czech language sounds configuration + +from tts import filename, NO_ALTERNATE, PROMPT_SYSTEM_BASE, PROMPT_CUSTOM_BASE + + +systemSounds = [] +sounds = [] + +for i, s in enumerate(["nula", "jedna", "dva"]): + systemSounds.append((s, filename(PROMPT_SYSTEM_BASE + i))) +for i in range(97): + systemSounds.append((str(3 + i), filename(PROMPT_SYSTEM_BASE + 3 + i))) +for i, s in enumerate(["sto", u"dvěsta", u"třista", u"čtyřista", u"pětset", u"šestset", "sedmset", "osmset", + u"devětset", u"tisíc"]): + systemSounds.append((s, filename(PROMPT_SYSTEM_BASE + 100 + i))) +for i, s in enumerate([u"tisíce", "jeden", "jedno", u"dvě", u"celá", u"celé", u"celých", u"mínus"]): + systemSounds.append((s, filename(PROMPT_SYSTEM_BASE + 110 + i))) + +for i, s in enumerate(["volt", "volty", u"voltů", "voltu", + u"ampér", u"ampéry", u"ampérů", u"ampéru", + u"miliampér", u"miliampéry", u"miliampérů", u"miliampéru", + u"uzel", u"uzly", u"uzlů", u"uzlu", + "metr za sekundu", "metry za sekundu", u"metrů za sekundu", "metru za sekundu", + "stopa za sekundu", "stopy za sekundu", "stop za sekundu", "stopy za sekundu", + "kilometr za hodinu", "kilometry za hodinu", u"kilometrů za hodinu", "kilometru za hodinu", + u"míle za hodinu", u"míle za hodinu", u"mil za hodinu", u"míle za hodinu", + "metr", "metry", u"metrů", "metru", + "stopa", "stopy", "stop", "stopy", + u"stupeň celsia", u"stupně celsia", u"stupňů celsia", u"stupně celsia", + u"stupeň fahrenheita", u"stupně fahrenheita", u"stupňů fahrenheita", u"stupně fahrenheita", + "procento", "procenta", "procent", "procenta", + u"miliampérhodina", u"miliampérhodiny", u"miliampérhodin", u"miliampérhodiny", + "vat", "vaty", u"vatů", "vatu", + "decibel", "decibely", u"decibelů", "decibelu", + u"otáčka za minutu", u"otáčky za minutu", u"otáček za minutu", u"otáčky za minutu", + u"gé", u"gé", u"gé", u"gé" + u"stupeň", u"stupně", u"stupňů", u"stupně", + u"mililitr", u"mililitry", u"mililitrů", "mililitru", + u"dutá unce", u"duté unce", u"dutých uncí", u"duté unce", + "hodina", "hodiny", "hodin", "hodiny", + "minuta", "minuty", "minut", "minuty", + "sekunda", "sekundy", "sekund", "sekundy", + ]): + systemSounds.append((s, filename(PROMPT_SYSTEM_BASE + 118 + i))) + +for s, f, a in [(u"střed trimu", "midtrim", 495), + (u"maximum trimu", "endtrim", NO_ALTERNATE), + (u"baterie rádia je vybitá", "lowbatt", 485), + (u"zapoměl jsi na mě!", "inactiv", 486), + (u"plyn není na nule", "thralert", 481), + (u"přepínače nejsou ve výchozí poloze", "swalert", 482), + (u"neplatná eeprom", "eebad", 483), + (u"Oupn najn iks", "tada", 480), + (u"dvacet sekund", "timer20", 500), + (u"třicet sekund", "timer30", 501), + (u"A1,nízká", "a1_org", NO_ALTERNATE), + (u"A1,kritická", "a1_red", NO_ALTERNATE), + (u"A2,nízká", "a2_org", NO_ALTERNATE), + (u"A2,kritická", "a2_red", NO_ALTERNATE), + (u"A3,nízká", "a3_org", NO_ALTERNATE), + (u"A3,kritická", "a3_red", NO_ALTERNATE), + (u"A4,nízká", "a4_org", NO_ALTERNATE), + (u"A4,kritická", "a4_red", NO_ALTERNATE), + (u"nízký RF signál", "rssi_org", NO_ALTERNATE), + (u"kritický RF signál", "rssi_red", NO_ALTERNATE), + (u"problém s anténou rádia", "swr_red", NO_ALTERNATE), + (u"telemetrie ztracena", "telemko", NO_ALTERNATE), + (u"telemetrie je funkční", "telemok", NO_ALTERNATE), + (u"trenér port odpojen", "trainko", NO_ALTERNATE), + (u"trenér port připojen", "trainok", NO_ALTERNATE), + ]: + systemSounds.append((s, filename(f, a))) +for i, (s, f) in enumerate([(u"podvozek je zasunut", "podvoz0"), + (u"podvozek je vysunut", "podvoz1"), + (u"klapky jsou zapnuty", "klapky1"), + (u"klapky jsou vypnuty", "klapky0"), + (u"trenér je zapnut", "trener1"), + (u"trenér je vypnutý", "trener0"), + (u"motor je vypnut", "motor0"), + (u"motor je aktivován", "motor1"), + (u"jsi příliš vysoko", "vysoko"), + (u"jsi příliš nízko", "nizko"), + (u"baterie modelu je vybitá", "batvybit"), + (u"dochází palivo", "palivo"), + (u"nízký signál!", "nsignal"), + (u"kritický signál!", "ksignal"), + (u"rychlý režim aktivován", "r_rychly"), + (u"termický režim aktivován", "r_termik"), + (u"normální režim aktivován", "r_norm"), + (u"režim start aktivován", "r_start"), + (u"režim přistání aktivován", "r_prista"), + (u"vario je zapnuto", "vario0"), + (u"vario je vypnuto", "vario1"), + (u"start povolen", "startok"), + ]): + sounds.append((s, filename(f, PROMPT_CUSTOM_BASE + i))) diff --git a/radio/util/tts_de.py b/radio/util/tts_de.py new file mode 100644 index 000000000..647073522 --- /dev/null +++ b/radio/util/tts_de.py @@ -0,0 +1,85 @@ +# -*- coding: utf-8 -*- + +# German language sounds configuration + +from tts import filename, NO_ALTERNATE, PROMPT_SYSTEM_BASE, PROMPT_CUSTOM_BASE + + +systemSounds = [] +sounds = [] + +for i in range(101): + systemSounds.append((str(i), filename(PROMPT_SYSTEM_BASE + i))) +systemSounds.append(("tausend", filename(PROMPT_SYSTEM_BASE + 101))) +for i, s in enumerate(["comma", "und", "minus", "uhr", "minute", "minuten", "sekunde", "sekunden"]): + systemSounds.append((s, filename(PROMPT_SYSTEM_BASE + 102 + i))) +for i, s in enumerate(["", "Volt", "Ampere", "MilliAmpere", "Knoten", + "Meter pro sekunde", "Fuesse pro sekunde", + "kilometer pro stunde", "Meilen pro Stunde", "Meter", + "Fuesse", "Grad", "Grad Fahrenheit", "Prozent", + "Milliampere pro stunde", "Watt", "db", "R P M", "g", + "Milliliter", "Unze", "Uhr", "Minuten", "Secunden"]): + systemSounds.append((s, filename(PROMPT_SYSTEM_BASE + 110 + i))) +for s, f, a in [(u"Sender ist inaktiv,bitte Ueberpruefen Sie", "inactiv", 486), + (u"Senderakku niedrig", "lowbatt", 485), + (u"Gaskanal nicht Null, bitte pruefen", "thralert", 481), + (u"Schalten fehlpositioniert, bitte pruefen", "swalert", 482), + (u"Das EEPROM ist fehlerhaft", "eebad", NO_ALTERNATE), + (u"Das EEPROM ist immer formatiert", "eeformat", NO_ALTERNATE), + (u"fehler", "error", NO_ALTERNATE), + (u"Trim zentriert", "midtrim", 495), + (u"Poti zentriert", "midpot", 496), + (u"Maximale trimmung erreicht", "endtrim", NO_ALTERNATE), + (u"20 sekunden", "timer20", 500), + (u"30 sekunden", "timer30", 501), + (u"Senderstrom ist zu hoch!", "highmah", NO_ALTERNATE), + (u"Sendertemperatur ist zu hoch!", "hightemp", NO_ALTERNATE), + (u"A1 schlecht!", "a1_org", NO_ALTERNATE), + (u"A1 kritisch!", "a1_red", NO_ALTERNATE), + (u"A2 schlecht!", "a2_org", NO_ALTERNATE), + (u"A2 kritisch!", "a2_red", NO_ALTERNATE), + (u"A3 schlecht!", "a3_org", NO_ALTERNATE), + (u"A3 kritisch!", "a3_red", NO_ALTERNATE), + (u"A4 schlecht!", "a4_org", NO_ALTERNATE), + (u"A4 kritisch!", "a4_red", NO_ALTERNATE), + (u"Funksignal schlecht!", "rssi_org", NO_ALTERNATE), + (u"Funksignal kritisch!", "rssi_red", NO_ALTERNATE), + (u"Problem mit der sender Antenna", "swr_red", NO_ALTERNATE), + (u"Telemetrie verloren", "telemko", NO_ALTERNATE), + (u"Telemetrie wiederhergestellt", "telemok", NO_ALTERNATE), + (u"Schülersignal verloren", "trainko", NO_ALTERNATE), + (u"Schülersignal wiederhergestellt", "trainok", NO_ALTERNATE), + ]: + systemSounds.append((s, filename(f, a))) +for i, s in enumerate(["Timer", "Timer", "Sendung", "Empfang", "A1", "A2", "Hoehe", "Motor", + "Treibstoff", "Temperatur", "Temperatur", "Geschwindigkeit", "Ferne", "Hoehe", "Lipo-Zelle", + "Zellen gesamt", "Spannung", "Strom", "Verbrauch", "Power", "Beschleunigung X", "Beschleunigung Y", "Beschleunigung Z", + "Richtung", "Variometer", "Minimum", "Maximum"]): + systemSounds.append((s, filename(PROMPT_SYSTEM_BASE + 134 + i))) +for i, (s, f) in enumerate([(u"Fahrwerk eingezogen", "gearup"), + (u"Fahrwerk ausgefahren", "geardn"), + (u"Klappen eingefahren", "flapup"), + (u"Klappen ausgefahren", "flapdn"), + (u"Landung", "attero"), + (u"Trainer-Modus ein", "trnon"), + (u"Trainer-Modus aus", "trnoff"), + (u"Motor aus", "engoff"), + (u"zu hoch", "tohigh"), + (u"zu niedrig", "tolow"), + (u"Batterie schwach", "lowbat"), + (u"crow ein", "crowon"), + (u"crow aus", "crowof"), + (u"Schnell-Modus ist aktiviert", "spdmod"), + (u"Thermik-Modus ist aktiviert", "thmmod"), + (u"Normal-Modus ist aktiviert", "nrmmod"), + (u"Regime 1", "fltmd1"), + (u"Regime 2", "fltmd2"), + (u"Regime 3", "fltmd3"), + (u"Regime 4", "fltmd4"), + (u"Regime 5", "fltmd5"), + (u"Regime 6", "fltmd6"), + (u"Regime 7", "fltmd7"), + (u"Regime 8", "fltmd8"), + (u"Regime 9", "fltmd9"), + ]): + sounds.append((s, filename(f, PROMPT_CUSTOM_BASE + i))) diff --git a/radio/util/tts_en.py b/radio/util/tts_en.py new file mode 100644 index 000000000..e7796d323 --- /dev/null +++ b/radio/util/tts_en.py @@ -0,0 +1,120 @@ +# -*- coding: utf-8 -*- + +# English language sounds configuration + +from tts import filename, NO_ALTERNATE, PROMPT_SYSTEM_BASE, PROMPT_CUSTOM_BASE + + +systemSounds = [] +sounds = [] + +for i in range(100): + systemSounds.append((str(i), filename(PROMPT_SYSTEM_BASE + i))) +for i in range(9): + systemSounds.append((str(100 * (i + 1)), filename(PROMPT_SYSTEM_BASE + 100 + i))) +for i, s in enumerate(["thousand", "and", "minus", "point"]): + systemSounds.append((s, filename(PROMPT_SYSTEM_BASE + 109 + i))) +for i, s in enumerate(["volt", "volts", + "amp", "amps", + "milliamp", "milliamps", + "knot", "knots", + "meter per second", "meters per second", + "foot per second", "feet per second", + "kilometer per hour", "kilometers per hour", + "mile per hour", "miles per hour", + "meter", "meters", + "foot", "feet", + "degree celsius", "degrees celsius", + "degree fahrenheit", "degrees fahrenheit", + "percent", "percent", + "milliamp-hour", "milliamp-hours", + "watt", "watts", + "db", "db", + "r p m", "r p m", + "g", "g", + "degree", "degrees", + "milliliter", "milliliters", + "fluid ounce", "fluid ounces", + "hour", "hours", + "minute", "minutes", + "second", "seconds", + ]): + systemSounds.append((s, filename(PROMPT_SYSTEM_BASE + 115 + i))) +for i, s in enumerate(["point zero", "point one", "point two", "point three", + "point four", "point five", "point six", + "point seven", "point eight", "point nine"]): + systemSounds.append((s, filename(PROMPT_SYSTEM_BASE + 165 + i))) +for s, f, a in [(u"trim center", "midtrim", 495), + (u"maximum trim reached", "endtrim", NO_ALTERNATE), + (u"transmitter battery low", "lowbatt", 485), + (u"inactivity alarm", "inactiv", 486), + (u"throttle warning", "thralert", 481), + (u"switch warning", "swalert", 482), + (u"bad eeprom", "eebad", 483), + (u"Welcome to open tea ex!", "tada", 480), + (u"twenty. seconds", "timer20", 500), + (u"thirty. seconds", "timer30", 501), + (u"A1,low", "a1_org", NO_ALTERNATE), + (u"A1,critical", "a1_red", NO_ALTERNATE), + (u"A2,low", "a2_org", NO_ALTERNATE), + (u"A2,critical", "a2_red", NO_ALTERNATE), + (u"A3,low", "a3_org", NO_ALTERNATE), + (u"A3,critical", "a3_red", NO_ALTERNATE), + (u"A4,low", "a4_org", NO_ALTERNATE), + (u"A4,critical", "a4_red", NO_ALTERNATE), + (u"RF signal, low", "rssi_org", NO_ALTERNATE), + (u"RF signal, critical", "rssi_red", NO_ALTERNATE), + (u"radio antenna defective", "swr_red", NO_ALTERNATE), + (u"telemetry lost", "telemko", NO_ALTERNATE), + (u"telemetry recovered", "telemok", NO_ALTERNATE), + (u"trainer signal lost", "trainko", NO_ALTERNATE), + (u"trainer signal recovered", "trainok", NO_ALTERNATE), + ]: + systemSounds.append((s, filename(f, a))) +for i, (s, f) in enumerate([(u"gear!, up!", "gearup"), + (u"gear!, down!", "geardn"), + (u"flaps!, up!", "flapup"), + (u"flaps!, down!", "flapdn"), + (u"spoiler!, up!", "splrup"), + (u"spoiler!, down!", "splrdn"), + (u"trainer!, on!", "trnon"), + (u"trainer!, off!", "trnoff"), + (u"engine!, off!", "engoff"), + (u"too. high!", "tohigh"), + (u"too. low!", "tolow"), + (u"low. battery!", "lowbat"), + (u"crow!, on!", "crowon"), + (u"crow!, off!", "crowof"), + (u"rf. signal!, low!", "siglow"), + (u"rf. signal!, critical!", "sigcrt"), + (u"high. speed. mode!, active", "spdmod"), + (u"thermal. mode!, on", "thmmod"), + (u"normal. mode!, on", "nrmmod"), + (u"landing. mode!, on", "lnding"), + (u"acro. mode!, on", "acro"), + (u"flight. mode!, one", "fm-1"), + (u"flight. mode!, two", "fm-2"), + (u"flight. mode!, three", "fm-3"), + (u"flight. mode!, four", "fm-4"), + (u"flight. mode!, five", "fm-5"), + (u"flight. mode!, six", "fm-6"), + (u"flight. mode!, seven", "fm-7"), + (u"flight. mode!, eight", "fm-8"), + (u"vario!, on", "vrion"), + (u"vario!, off", "vrioff"), + (u"flight mode!, power", "fm-pwr"), + (u"flight mode!, land", "fm-lnd"), + (u"flight mode!, float", "fm-flt"), + (u"flight mode!, speed", "fm-spd"), + (u"flight mode!, fast", "fm-fst"), + (u"flight mode!, normal", "fm-nrm"), + (u"flight mode!, cruise", "fm-crs"), + (u"flight mode!, acro", "fm-acr"), + (u"flight mode!, race", "fm-rce"), + (u"flight mode!, launch", "fm-lch"), + (u"flight mode!, ping", "fm-png"), + (u"flight mode!, thermal", "fm-thm"), + (u"flight mode!, thermal left", "fm-thml"), + (u"flight mode!, thermal right", "fm-thmr"), + ]): + sounds.append((s, filename(f, PROMPT_CUSTOM_BASE + i))) diff --git a/radio/util/tts_es.py b/radio/util/tts_es.py new file mode 100644 index 000000000..d3de61c3d --- /dev/null +++ b/radio/util/tts_es.py @@ -0,0 +1,83 @@ +# -*- coding: utf-8 -*- + +# Spanish language sounds configuration + +from tts import filename, NO_ALTERNATE, PROMPT_SYSTEM_BASE, PROMPT_CUSTOM_BASE + + +systemSounds = [] +sounds = [] + +for i in range(101): + systemSounds.append((str(i), filename(PROMPT_SYSTEM_BASE + i))) +systemSounds.append(("ciento", filename(PROMPT_SYSTEM_BASE + 101))) +systemSounds.append(("doscientos", filename(PROMPT_SYSTEM_BASE + 102))) +systemSounds.append(("trescientos", filename(PROMPT_SYSTEM_BASE + 103))) +systemSounds.append(("cuatrocientos", filename(PROMPT_SYSTEM_BASE + 104))) +systemSounds.append(("quinientos", filename(PROMPT_SYSTEM_BASE + 105))) +systemSounds.append(("sescientos", filename(PROMPT_SYSTEM_BASE + 106))) +systemSounds.append(("setecientos", filename(PROMPT_SYSTEM_BASE + 107))) +systemSounds.append(("ochocientos", filename(PROMPT_SYSTEM_BASE + 108))) +systemSounds.append(("nuevecientos", filename(PROMPT_SYSTEM_BASE + 109))) +systemSounds.append(("mil", filename(PROMPT_SYSTEM_BASE + 110))) +for i, s in enumerate(["coma", "un", "una", "y", "meno", "hora", "horas", "minuto", "minutos", "segundo", "segundos"]): + systemSounds.append((s, filename(PROMPT_SYSTEM_BASE + 111 + i))) +for i, s in enumerate([u"Voltio", u"ampério", u"metros por segundo", u"", u"kilómetro por hora", u"metros", u"grados", u"por ciento", u"miliamperios", u"miliamperios por hora", u"vatio", u"db", u"pés", u"nós", u"horas", u"minutos", u"segundos", u"RPM", u"g", u"mililitro", u"onzas"]): + systemSounds.append((s, filename(PROMPT_SYSTEM_BASE + 122 + i))) +for s, f, a in [(u"me tienes abandonada", "inactiv", 486), + (u"batería del transmisor baja", "lowbatt", 485), + (u"El acelerador está activado, por favor, corrijalo", "thralert", 481), + (u"Los interruptores no están en la posición correcta, por favor corrijalo", "swalert", 482), + (u"eeprom corrompida", "eebad", NO_ALTERNATE), + (u"Formateo de eeprom en curso", "eeformat", NO_ALTERNATE), + (u"error", "error", NO_ALTERNATE), + (u"trim centrado", "midtrim", 495), + (u"potenciómetro centrado", "midpot", 496), + (u"trim al máximo", "endtrim", NO_ALTERNATE), + (u"20 segundos", "timer20", 500), + (u"30 segundos", "timer30", 501), + (u"assorbimiento elevado", "highmah", NO_ALTERNATE), + (u"temperatura elevada", "hightemp", NO_ALTERNATE), + (u"Alarma A1", "a1_org", NO_ALTERNATE), + (u"A1 crítica", "a1_red", NO_ALTERNATE), + (u"Alarma A2", "a2_org", NO_ALTERNATE), + (u"A2 crítica", "a2_red", NO_ALTERNATE), + (u"recepcion de señal baja", "rssi_org", NO_ALTERNATE), + (u"recepción de señal crítica", "rssi_red", NO_ALTERNATE), + (u"Problemas con la antena del transmisor", "swr_red", NO_ALTERNATE), + (u"Sin telemetría", "telemko", NO_ALTERNATE), + (u"Telemetría disponible", "telemok", NO_ALTERNATE), + ]: + systemSounds.append((s, filename(f, a))) +for i, s in enumerate([u"cronómetro", u"cronómetro", u"transmisión", u"recepción", u"A1", u"A2", u"altitud", u"motor", + u"combustible", u"temperatura", u"temperatura", u"velocidad", u"distancia", u"altitude", u"célula lipo", + u"Total lipo", u"voltaje", u"corriente", u"consumo", u"potencia", u"aceleración X", u"aceleración Y", u"aceleración Z", + u"dirección", u"variómetro", u"minimo", u"máximo"]): + systemSounds.append((s, filename(PROMPT_SYSTEM_BASE + 141 + i))) +for i, (s, f) in enumerate([(u"tren arriba.", "gearup"), + (u"tren abajo.", "geardn"), + (u"flaps arriba", "flapup"), + (u"flaps abajo", "flapdn"), + (u"aterrizaje", "attero"), + (u"modo de entrenamiento activado", "trnon"), + (u"modo de entrenamiento deshabilitado", "trnoff"), + (u"motor apagado", "engoff"), + (u"muy alto", "tohigh"), + (u"muy bajo", "tolow"), + (u"bateria baja", "lowbat"), + (u"crou, activo", "crowon"), + (u"crou, desligado", "crowof"), + (u"modo de velocidad", "spdmod"), + (u"modo de térmica", "thmmod"), + (u"modo de vuelo normal", "nrmmod"), + (u"fase de vuelo 1", "fltmd1"), + (u"fase de vuelo 2", "fltmd2"), + (u"fase de vuelo 3", "fltmd3"), + (u"fase de vuelo 4", "fltmd4"), + (u"fase de vuelo 5", "fltmd5"), + (u"fase de vuelo 6", "fltmd6"), + (u"fase de vuelo 7", "fltmd7"), + (u"fase de vuelo 8", "fltmd8"), + (u"fase de vuelo 9", "fltmd9"), + ]): + sounds.append((s, filename(f, PROMPT_CUSTOM_BASE + i))) diff --git a/radio/util/tts_fr.py b/radio/util/tts_fr.py new file mode 100644 index 000000000..ea8145441 --- /dev/null +++ b/radio/util/tts_fr.py @@ -0,0 +1,67 @@ +# -*- coding: utf-8 -*- + +# French language sounds configuration + +from tts import filename, NO_ALTERNATE, PROMPT_SYSTEM_BASE, PROMPT_CUSTOM_BASE + + +systemSounds = [] +sounds = [] + +for i in range(100): + systemSounds.append((str(i), filename(PROMPT_SYSTEM_BASE + i))) +for i in range(10): + systemSounds.append((str(100 * (i + 1)), filename(PROMPT_SYSTEM_BASE + 100 + i))) +for i, s in enumerate(["une", "onze", "vingt et une", "trente et une", "quarante et une", "cinquante et une", "soixante et une", "soixante et onze", "quatre vingt une"]): + systemSounds.append((s, filename(PROMPT_SYSTEM_BASE + 110 + i))) +for i, s in enumerate(["virgule", "et", "moins", "minuit", "midi"]): + systemSounds.append((s, filename(PROMPT_SYSTEM_BASE + 119 + i))) +for i, s in enumerate(["volts", u"ampères", u"milli ampères", u"knots", u"mètres seconde", u"pieds par seconde", u"kilomètre heure", u"miles par heure", u"mètres", "pieds", u"degrés", u"degrés fahrenheit", "pourcents", u"milli ampères / heure", "watt", "db", "tours minute", "g", u"degrés", "millilitres", "onces", "heure", "minute", "seconde"]): + systemSounds.append((s, filename(PROMPT_SYSTEM_BASE + 125 + i))) +# for i, s in enumerate(["timer", "", "tension", "tension", u"émission", u"réception", "altitude", "moteur", +# "essence", u"température", u"température", "vitesse", "distance", "altitude", u"élément lipo", +# "total lipo", "tension", "courant", "consommation", "puissance", u"accelération X", u"accelération Y", u"accelération Z", +# "orientation", "vario"]): +# systemSounds.append((s, filename(PROMPT_SYSTEM_BASE+146+i))) +for i, s in enumerate(["virgule 0", "virgule 1", "virgule 2", "virgule 3", "virgule 4", "virgule 5", "virgule 6", "virgule 7", "virgule 8", "virgule 9"]): + systemSounds.append((s, filename(PROMPT_SYSTEM_BASE + 180 + i))) +for s, f, a in [(u"Trim centré", "midtrim", 495), + (u"Trim maximum atteint", "endtrim", NO_ALTERNATE), + (u"Batterie radio faible !", "lowbatt", 485), + (u"Radio inactive !", "inactiv", 486), + (u"Alerte manche des gaz", "thralert", 481), + (u"Alerte inters", "swalert", 482), + (u"éprome corrompue", "eebad", 483), + (u"Bienvenue sur Open TI X!", "tada", 480), + (u"vingt secondes", "timer20", 500), + (u"trente secondes", "timer30", 501), + (u"A1,faible", "a1_org", NO_ALTERNATE), + (u"A1,critique", "a1_red", NO_ALTERNATE), + (u"A2,faible", "a2_org", NO_ALTERNATE), + (u"A2,critique", "a2_red", NO_ALTERNATE), + (u"A3,faible", "a3_org", NO_ALTERNATE), + (u"A3,critique", "a3_red", NO_ALTERNATE), + (u"A4,faible", "a4_org", NO_ALTERNATE), + (u"A4,critique", "a4_red", NO_ALTERNATE), + (u"Signal RF, faible", "rssi_org", NO_ALTERNATE), + (u"Signal RF, critique", "rssi_red", NO_ALTERNATE), + (u"Antenne défectueuse", "swr_red", NO_ALTERNATE), + (u"Plus de télémétrie", "telemko", NO_ALTERNATE), + (u"Télémétrie retrouvée", "telemok", NO_ALTERNATE), + (u"Signal écolage perdu", "trainko", NO_ALTERNATE), + (u"Signal écolage retrouvé", "trainok", NO_ALTERNATE), + ]: + systemSounds.append((s, filename(f, a))) +for i, (s, f) in enumerate([(u"altitude", "altitude"), + (u"température moteur", "moteur"), + (u"température contrôleur", "cntrleur"), + (u"train rentré", "gearup"), + (u"train sorti", "geardn"), + (u"volets rentrés", "flapup"), + (u"volets sortis", "flapdn"), + (u"atterrissage", "attero"), + (u"écolage", "trnon"), + (u"fin écolage", "trnoff"), + (u"moteur coupé", "engoff"), + ]): + sounds.append((s, filename(f, PROMPT_CUSTOM_BASE + i))) diff --git a/radio/util/tts_it.py b/radio/util/tts_it.py new file mode 100644 index 000000000..b84fdf52e --- /dev/null +++ b/radio/util/tts_it.py @@ -0,0 +1,100 @@ +# -*- coding: utf-8 -*- + +# Italian language sounds configuration + +from tts import filename, NO_ALTERNATE, PROMPT_SYSTEM_BASE, PROMPT_CUSTOM_BASE + + +systemSounds = [] +sounds = [] + +for i in range(101): + systemSounds.append((str(i), filename(PROMPT_SYSTEM_BASE + i))) +systemSounds.append(("mila", filename(PROMPT_SYSTEM_BASE + 101))) +systemSounds.append(("mille", filename(PROMPT_SYSTEM_BASE + 102))) +for i, s in enumerate(["virgola", "un", "e", "meno", "ora", "ore", "minuto", "minuti", "secondo", "secondi"]): + systemSounds.append((s, filename(PROMPT_SYSTEM_BASE + 103 + i))) +for i, s in enumerate(["", "", + "volt", "volt", + "ampere", "ampere", + "milliampers", "milliampers", + "nodo", "nodi", + "metro al secondo", "metri al secondo", + "piede al secondo", "piedi al secondo", + "chilometro ora", "chilometri ora", + "miglio per ora", "miglia per ora", + "metro", "metri", + "piede", "piedi", + "grado celsius", "gradi celsius", + "grado fahrenheit", "gradi fahrenheit", + "percento", "percento", + "milliampere ora", "milliampere ora", + "watt", "watt", + "decibel", "decibel", + "R P M", "R P M", + "g", "g", + "grado", "gradi", + "millilitro", "millilitri", + "oncia", "once"]): + systemSounds.append((s, filename(PROMPT_SYSTEM_BASE + 113 + i))) +for s, f, a in [(u"radio inattiva controllare", "inactiv", 486), + (u"batteria della radio scarica", "lowbatt", 485), + (u"controllo motore non in posizione, verificare", "thralert", 481), + (u"interruttori non in posizione, verificare", "swalert", 482), + (u"eeprom corrotta", "eebad", NO_ALTERNATE), + (u"formattazone eeprom in corso", "eeformat", NO_ALTERNATE), + (u"errore", "error", NO_ALTERNATE), + (u"trim centrato", "midtrim", 495), + (u"potenziometro centrato", "midpot", 496), + (u"massimo trim raggiunto", "endtrim", NO_ALTERNATE), + (u"venti secondi", "timer20", 500), + (u"trenta secondi", "timer30", 501), + (u"assorbimento elevato", "highmah", NO_ALTERNATE), + (u"temperatura elevata", "hightemp", NO_ALTERNATE), + (u"A1 in allarme", "a1_org", NO_ALTERNATE), + (u"A1 critico", "a1_red", NO_ALTERNATE), + (u"A2 in allarme", "a2_org", NO_ALTERNATE), + (u"A2 critico", "a2_red", NO_ALTERNATE), + (u"A3 in allarme", "a3_org", NO_ALTERNATE), + (u"A3 critico", "a3_red", NO_ALTERNATE), + (u"A4 in allarme", "a4_org", NO_ALTERNATE), + (u"A4 critico", "a4_red", NO_ALTERNATE), + (u"Segnale radio basso", "rssi_org", NO_ALTERNATE), + (u"Segnale radio critico", "rssi_red", NO_ALTERNATE), + (u"Problema all'antenna della radio", "swr_red", NO_ALTERNATE), + (u"Telemetria assente", "telemko", NO_ALTERNATE), + (u"Telemetria disponibile", "telemok", NO_ALTERNATE), + ]: + systemSounds.append((s, filename(f, a))) +for i, s in enumerate([u"timer", u"", u"tensione", u"tensione", u"trasmissione", u"ricezione", u"altitudine", u"motore", + u"carburante", u"temperatura", u"temperatura", u"velocità", "distanza", u"altitudine", u"cella lipo", + u"totale lipo", u"tensione", u"corrente", u"consumo", u"potenza", u"accellerazione X", u"accellerazione Y", u"accellerazione Z", + u"direzione", u"variometro", u"minimo", u"massimo"]): + systemSounds.append((s, filename(PROMPT_SYSTEM_BASE + 135 + i))) +for i, (s, f) in enumerate([(u"carrello chiuso", "gearup"), + (u"carrello aperto", "geardn"), + (u"flap rientrati", "flapup"), + (u"flap estesi", "flapdn"), + (u"atterraggiio", "attero"), + (u"modalità maestro attiva", "trnon"), + (u"modalità maestro disattiva", "trnoff"), + (u"motore spento", "engoff"), + (u"troppo alto", "tohigh"), + (u"troppo basso", "tolow"), + (u"batteria scarica", "lowbat"), + (u"crow on", "crowon"), + (u"crow off", "crowof"), + (u"modo velocità", "spdmod"), + (u"modo termica", "thmmod"), + (u"modo volo normale", "nrmmod"), + (u"fase di volo 1", "fltmd1"), + (u"fase di volo 2", "fltmd2"), + (u"fase di volo 3", "fltmd3"), + (u"fase di volo 4", "fltmd4"), + (u"fase di volo 5", "fltmd5"), + (u"fase di volo 6", "fltmd6"), + (u"fase di volo 7", "fltmd7"), + (u"fase di volo 8", "fltmd8"), + (u"fase di volo 9", "fltmd9"), + ]): + sounds.append((s, filename(f, PROMPT_CUSTOM_BASE + i))) diff --git a/radio/util/tts_pt.py b/radio/util/tts_pt.py new file mode 100644 index 000000000..668709a19 --- /dev/null +++ b/radio/util/tts_pt.py @@ -0,0 +1,81 @@ +# -*- coding: utf-8 -*- + +# Portuguese language sounds configuration + +from tts import filename, NO_ALTERNATE, PROMPT_SYSTEM_BASE, PROMPT_CUSTOM_BASE + + +systemSounds = [] +sounds = [] + +for i in range(101): + systemSounds.append((str(i), filename(PROMPT_SYSTEM_BASE + i))) +systemSounds.append(("cento", filename(PROMPT_SYSTEM_BASE + 101))) +systemSounds.append(("duzentos", filename(PROMPT_SYSTEM_BASE + 102))) +systemSounds.append(("trezentos", filename(PROMPT_SYSTEM_BASE + 103))) +systemSounds.append(("quatrocentos", filename(PROMPT_SYSTEM_BASE + 104))) +systemSounds.append(("quinhentos", filename(PROMPT_SYSTEM_BASE + 105))) +systemSounds.append(("seiscentos", filename(PROMPT_SYSTEM_BASE + 106))) +systemSounds.append(("setecentos", filename(PROMPT_SYSTEM_BASE + 107))) +systemSounds.append(("oitocentos", filename(PROMPT_SYSTEM_BASE + 108))) +systemSounds.append(("novecentos", filename(PROMPT_SYSTEM_BASE + 109))) +systemSounds.append(("mil", filename(PROMPT_SYSTEM_BASE + 110))) +for i, s in enumerate(["virgula", "uma", "duas", "e", "menos", "hora", "horas", "minuto", "minutos", "segundo", "segundos"]): + systemSounds.append((s, filename(PROMPT_SYSTEM_BASE + 111 + i))) +for i, s in enumerate([u"Volt", u"ampére", u"metros por segundo", u"", u"quilômetros por hora", u"metros", u"graus", u"cento", u"miliamperes", u"miliamperes por hora", u"watt", u"db", u"pés", u"nós", u"horas", u"minutos", u"segundos", u"RPM", u"g", u"mililitri", u"onças"]): + systemSounds.append((s, filename(PROMPT_SYSTEM_BASE + 122 + i))) +for s, f, a in [(u"atenção, o rádio foi esquecido ligado, por favor desligue-o", "inactiv", 486), + (u"bateria do rádio fraca", "lowbatt", 485), + (u"atenção,acelerador não está no mínimo", "thralert", 481), + (u"atenção, certifique-se que os interruptores estão na posição certa", "swalert", 482), + (u"eeprom corrompida", "eebad", NO_ALTERNATE), + (u"formatação da eeprom em curso", "eeformat", NO_ALTERNATE), + (u"erro", "error", NO_ALTERNATE), + (u"trim centrado", "midtrim", 495), + (u"potenciómetro centrado", "midpot", 496), + (u"trim no máximo", "endtrim", NO_ALTERNATE), + (u"20 segundos", "timer20", 500), + (u"30 segundos", "timer30", 501), + (u"assorbimento elevato", "highmah", NO_ALTERNATE), + (u"temperatura elevata", "hightemp", NO_ALTERNATE), + (u"Alarme A1", "a1_org", NO_ALTERNATE), + (u"A1 critica", "a1_red", NO_ALTERNATE), + (u"Alarme A2", "a2_org", NO_ALTERNATE), + (u"A2 critica", "a2_red", NO_ALTERNATE), + (u"recepção de sinal muito baixa", "rssi_org", NO_ALTERNATE), + (u"recepção de sinal crítica", "rssi_red", NO_ALTERNATE), + (u"Problema com a antena do transmissor", "swr_red", NO_ALTERNATE), + ]: + systemSounds.append((s, filename(f, a))) +for i, s in enumerate([u"cronómetro", u"cronómetro", u"transmissão", u"recepção", u"A1", u"A2", u"altitude", u"motor", + u"combustível", u"temperatura", u"temperatura", u"velocidade", u"distância", u"altitude", u"célula lipo", + u"Total lipo", u"tensão", u"corrente", u"consumo", u"potência", u"aceleração X", u"aceleração Y", u"aceleração Z", + u"Direcção", u"variómetro", u"mínimo", u"máximo"]): + systemSounds.append((s, filename(PROMPT_SYSTEM_BASE + 141 + i))) +for i, (s, f) in enumerate([(u"trem, em cima.", "gearup"), + (u"trem, em baixo.", "geardn"), + (u"flaps recolhidos", "flapup"), + (u"flaps estendidos", "flapdn"), + (u"aterragem", "attero"), + (u"modo de treino ligado", "trnon"), + (u"modo de treino desligado", "trnoff"), + (u"motor desligado", "engoff"), + (u"muito alto", "tohigh"), + (u"muito baixo", "tolow"), + (u"bateria fraca", "lowbat"), + (u"crou, activo", "crowon"), + (u"crou, desligado", "crowof"), + (u"modo de velocidade", "spdmod"), + (u"modo de térmica", "thmmod"), + (u"modo de voo normal", "nrmmod"), + (u"fase de voo 1", "fltmd1"), + (u"fase de voo 2", "fltmd2"), + (u"fase de voo 3", "fltmd3"), + (u"fase de voo 4", "fltmd4"), + (u"fase de voo 5", "fltmd5"), + (u"fase de vôo 6", "fltmd6"), + (u"fase de voo 7", "fltmd7"), + (u"fase de voo 8", "fltmd8"), + (u"fase de voo 9", "fltmd9"), + ]): + sounds.append((s, filename(f, PROMPT_CUSTOM_BASE + i))) From 4bd90d79d0a048166d6a74e7227b7c45901aeb89 Mon Sep 17 00:00:00 2001 From: Sean Vig Date: Sun, 13 Dec 2015 18:57:36 -0600 Subject: [PATCH 21/21] Use `with open(...) as ...:` context managers Instead of manually opening and closes file objects, use the context manager that will properly handle opening and closing files for us, even in the event of some error --- radio/util/addtr.py | 6 +- radio/util/bin2lbm.py | 24 ++-- radio/util/copyright.py | 15 +-- radio/util/font2png.py | 17 ++- radio/util/img2lbm.py | 253 ++++++++++++++++++------------------ radio/util/include-guard.py | 10 +- radio/util/luaexport.py | 158 +++++++++++----------- 7 files changed, 234 insertions(+), 249 deletions(-) diff --git a/radio/util/addtr.py b/radio/util/addtr.py index 9081a6235..d31ca3ad8 100755 --- a/radio/util/addtr.py +++ b/radio/util/addtr.py @@ -8,12 +8,14 @@ import glob def addLine(filename, newline, after): print(filename, newline) - lines = file(filename, 'r').readlines() + with open(filename, 'r') as f: + lines = f.readlines() for i, line in enumerate(lines): if after in line: lines.insert(i + 1, newline + '\n') break - file(filename, 'w').writelines(lines) + with open(filename, 'w') as f: + f.writelines(lines) def modifyTranslations(constant, translation, after): diff --git a/radio/util/bin2lbm.py b/radio/util/bin2lbm.py index c86e51c21..f34999b34 100755 --- a/radio/util/bin2lbm.py +++ b/radio/util/bin2lbm.py @@ -1,22 +1,20 @@ #!/usr/bin/env python +from __future__ import division import sys filename = sys.argv[1] fileout = sys.argv[2] -fr = open(filename, "rb") -fw = open(fileout, "w") +# Read entire file +with open(filename, "rb") as fr: + sts = fr.read() +# Parse into chunks of 16 bytes +sts = [sts[i * 16:(i + 1) * 16] for i in range(len(sts) // 16)] -st = fr.read(16) - -while st: - for b in st: - fw.write("0x%02x," % ord(b)) +with open(fileout, "w") as fw: + for st in sts: + for b in st: + fw.write("0x%02x," % ord(b)) + fw.write("\n") fw.write("\n") - st = fr.read(16) - -fw.write("\n") - -fw.close() -fr.close() diff --git a/radio/util/copyright.py b/radio/util/copyright.py index 4a2c0643f..13f25cb2b 100755 --- a/radio/util/copyright.py +++ b/radio/util/copyright.py @@ -13,9 +13,8 @@ def writeheader(filename, header): header should be a list of strings skip should be a regex """ - f = open(filename,"r") - inpt =f.readlines() - f.close() + with open(filename, "r") as f: + inpt = f.readlines() output = [] # comment out the next 3 lines if you don't wish to preserve shebangs @@ -36,18 +35,16 @@ def writeheader(filename, header): for line in inpt: output.append(line) try: - f = open(filename,'w') - f.writelines(output) - f.close() + with open(filename, 'w') as f: + f.writelines(output) print("added header to %s" % filename) except IOError as err: print("something went wrong trying to add header to %s: %s" % (filename, err)) def main(args=sys.argv): - headerfile = open(args[1]) - header = headerfile.readlines() - headerfile.close() + with open(args[1]) as headerfile: + header = headerfile.readlines() writeheader(args[2], header) diff --git a/radio/util/font2png.py b/radio/util/font2png.py index dd18d5875..302ed6659 100755 --- a/radio/util/font2png.py +++ b/radio/util/font2png.py @@ -88,15 +88,14 @@ def createFontBitmap(filename, fontname, fontsize, fontbold, foreground, backgro painter.end() image.save(filename + ".png") if coordsfile: - f = file(filename + ".specs", "w") - f.write("{ ") - f.write(",".join(str(tmp) for tmp in coords)) - if extraWidth: - for i in range(1, 14): - f.write(", %d" % (int(coords[-1]) + i * (extraWidth / 12))) - # f.write(file("fonts/extra_%dpx.specs" % fontsize).read()) - f.write(" }") - f.close() + with open(filename + ".specs", "w") as f: + f.write("{ ") + f.write(",".join(str(tmp) for tmp in coords)) + if extraWidth: + for i in range(1, 14): + f.write(", %d" % (int(coords[-1]) + i * (extraWidth / 12))) + # f.write(file("fonts/extra_%dpx.specs" % fontsize).read()) + f.write(" }") return coords if __name__ == "__main__": diff --git a/radio/util/img2lbm.py b/radio/util/img2lbm.py index 0e4d5f39e..56bc9e1ff 100755 --- a/radio/util/img2lbm.py +++ b/radio/util/img2lbm.py @@ -16,140 +16,139 @@ def writeSize(f, width, height): f.write("%d,%d,\n" % (width, height)) -f = open(sys.argv[2], "w") +with open(sys.argv[2], "w") as f: + lcdwidth = int(sys.argv[3]) -lcdwidth = int(sys.argv[3]) + if len(sys.argv) > 4: + what = sys.argv[4] + else: + for s in ("03x05", "04x06", "05x07", "08x10", "10x14", "22x38"): + if s in sys.argv[2]: + what = s + break -if len(sys.argv) > 4: - what = sys.argv[4] -else: - for s in ("03x05", "04x06", "05x07", "08x10", "10x14", "22x38"): - if s in sys.argv[2]: - what = s - break - -if what == "1bit": - rows = 1 - if len(sys.argv) > 5: - rows = int(sys.argv[5]) - writeSize(f, width, height // rows) - for y in range(0, height, 8): - for x in range(width): - value = 0 - for z in range(8): - if y + z < height and image.pixel(x, y + z) == Qt.qRgb(0, 0, 0): - value += 1 << z - f.write("0x%02x," % value) - f.write("\n") -elif what == "4/4/4/4": - colors = [] - f.write("%d,%d,\n" % (width, height)) - for y in range(height): - for x in range(width): - pixel = image.pixel(x, y) - f.write("0x%1x%1x%1x%1x," % (Qt.qAlpha(pixel) // 16, Qt.qRed(pixel) // 16, Qt.qGreen(pixel) // 16, Qt.qBlue(pixel) // 16)) - f.write("\n") -elif what == "5/6/5/8": - colors = [] - writeSize(f, width, height) - for y in range(height): - for x in range(width): - pixel = image.pixel(x, y) - val = ((Qt.qRed(pixel) >> 3) << 11) + ((Qt.qGreen(pixel) >> 2) << 5) + ((Qt.qBlue(pixel) >> 3) << 0) - # f.write("%d,%d,%d," % (val%256, val/256, Qt.qAlpha(pixel) >> 4)) - f.write("%d,%d," % (val % 256, val // 256)) - f.write("\n") -elif what == "4bits": - colors = [] - writeSize(f, width, height) - for y in range(0, height, 2): - for x in range(width): - value = 0xFF - gray1 = Qt.qGray(image.pixel(x, y)) - if y + 1 < height: - gray2 = Qt.qGray(image.pixel(x, y + 1)) - else: - gray2 = Qt.qRgb(255, 255, 255) - for i in range(4): - if (gray1 & (1 << (4 + i))): - value -= 1 << i - if (gray2 & (1 << (4 + i))): - value -= 1 << (4 + i) - f.write("0x%02x," % value) - f.write("\n") -elif what == "8bits": - colors = [] - writeSize(f, width, height) - for y in range(height): - for x in range(width): - value = Qt.qGray(image.pixel(x, y)) - value = 0x0f - (value >> 4) - f.write("0x%02x," % value) - f.write("\n") -elif what == "03x05": - for y in range(0, height, 5): - for x in range(width): - value = 0 - for z in range(5): - if image.pixel(x, y + z) == Qt.qRgb(0, 0, 0): - value += 1 << z - f.write("0x%02x," % value) - f.write("\n") -elif what == "04x06": - for y in range(0, height, 7): - for x in range(width): - value = 0 - for z in range(7): - if image.pixel(x, y + z) == Qt.qRgb(0, 0, 0): - value += 1 << z - if value == 0x7f: - value = 0xff - f.write("0x%02x," % value) - f.write("\n") -elif what == "05x07": - for y in range(0, height, 8): - for x in range(width): - value = 0 - for z in range(8): - if image.pixel(x, y + z) == Qt.qRgb(0, 0, 0): - value += 1 << z - f.write("0x%02x," % value) - f.write("\n") -elif what == "08x10": - for y in range(0, height, 12): - for x in range(width): - skip = True - for l in range(0, 12, 8): + if what == "1bit": + rows = 1 + if len(sys.argv) > 5: + rows = int(sys.argv[5]) + writeSize(f, width, height // rows) + for y in range(0, height, 8): + for x in range(width): value = 0 for z in range(8): - if l + z < 12: - if image.pixel(x, y + l + z) == Qt.qRgb(0, 0, 0): - value += 1 << z - else: - skip = False - if skip and l == 8: + if y + z < height and image.pixel(x, y + z) == Qt.qRgb(0, 0, 0): + value += 1 << z + f.write("0x%02x," % value) + f.write("\n") + elif what == "4/4/4/4": + colors = [] + f.write("%d,%d,\n" % (width, height)) + for y in range(height): + for x in range(width): + pixel = image.pixel(x, y) + f.write("0x%1x%1x%1x%1x," % (Qt.qAlpha(pixel) // 16, Qt.qRed(pixel) // 16, Qt.qGreen(pixel) // 16, Qt.qBlue(pixel) // 16)) + f.write("\n") + elif what == "5/6/5/8": + colors = [] + writeSize(f, width, height) + for y in range(height): + for x in range(width): + pixel = image.pixel(x, y) + val = ((Qt.qRed(pixel) >> 3) << 11) + ((Qt.qGreen(pixel) >> 2) << 5) + ((Qt.qBlue(pixel) >> 3) << 0) + # f.write("%d,%d,%d," % (val%256, val/256, Qt.qAlpha(pixel) >> 4)) + f.write("%d,%d," % (val % 256, val // 256)) + f.write("\n") + elif what == "4bits": + colors = [] + writeSize(f, width, height) + for y in range(0, height, 2): + for x in range(width): + value = 0xFF + gray1 = Qt.qGray(image.pixel(x, y)) + if y + 1 < height: + gray2 = Qt.qGray(image.pixel(x, y + 1)) + else: + gray2 = Qt.qRgb(255, 255, 255) + for i in range(4): + if (gray1 & (1 << (4 + i))): + value -= 1 << i + if (gray2 & (1 << (4 + i))): + value -= 1 << (4 + i) + f.write("0x%02x," % value) + f.write("\n") + elif what == "8bits": + colors = [] + writeSize(f, width, height) + for y in range(height): + for x in range(width): + value = Qt.qGray(image.pixel(x, y)) + value = 0x0f - (value >> 4) + f.write("0x%02x," % value) + f.write("\n") + elif what == "03x05": + for y in range(0, height, 5): + for x in range(width): + value = 0 + for z in range(5): + if image.pixel(x, y + z) == Qt.qRgb(0, 0, 0): + value += 1 << z + f.write("0x%02x," % value) + f.write("\n") + elif what == "04x06": + for y in range(0, height, 7): + for x in range(width): + value = 0 + for z in range(7): + if image.pixel(x, y + z) == Qt.qRgb(0, 0, 0): + value += 1 << z + if value == 0x7f: value = 0xff f.write("0x%02x," % value) - f.write("\n") -elif what == "10x14": - for y in range(0, height, 16): - for x in range(width): - for l in range(0, 16, 8): + f.write("\n") + elif what == "05x07": + for y in range(0, height, 8): + for x in range(width): value = 0 for z in range(8): - if image.pixel(x, y + l + z) == Qt.qRgb(0, 0, 0): + if image.pixel(x, y + z) == Qt.qRgb(0, 0, 0): value += 1 << z f.write("0x%02x," % value) - f.write("\n") -elif what == "22x38": - for y in range(0, height, 40): - for x in range(width): - for l in range(0, 40, 8): - value = 0 - for z in range(8): - if image.pixel(x, y + l + z) == Qt.qRgb(0, 0, 0): - value += 1 << z - f.write("0x%02x," % value) - f.write("\n") -else: - print("wrong argument", sys.argv[4]) + f.write("\n") + elif what == "08x10": + for y in range(0, height, 12): + for x in range(width): + skip = True + for l in range(0, 12, 8): + value = 0 + for z in range(8): + if l + z < 12: + if image.pixel(x, y + l + z) == Qt.qRgb(0, 0, 0): + value += 1 << z + else: + skip = False + if skip and l == 8: + value = 0xff + f.write("0x%02x," % value) + f.write("\n") + elif what == "10x14": + for y in range(0, height, 16): + for x in range(width): + for l in range(0, 16, 8): + value = 0 + for z in range(8): + if image.pixel(x, y + l + z) == Qt.qRgb(0, 0, 0): + value += 1 << z + f.write("0x%02x," % value) + f.write("\n") + elif what == "22x38": + for y in range(0, height, 40): + for x in range(width): + for l in range(0, 40, 8): + value = 0 + for z in range(8): + if image.pixel(x, y + l + z) == Qt.qRgb(0, 0, 0): + value += 1 << z + f.write("0x%02x," % value) + f.write("\n") + else: + print("wrong argument", sys.argv[4]) diff --git a/radio/util/include-guard.py b/radio/util/include-guard.py index 428edbfc0..5a60f6b27 100755 --- a/radio/util/include-guard.py +++ b/radio/util/include-guard.py @@ -6,9 +6,8 @@ import sys import os for filename in sys.argv[1:]: - f = file(filename, "r") - lines = f.readlines() - f.close() + with open(filename, "r") as f: + lines = f.readlines() newguard = "_" + os.path.basename(filename).upper().replace(".", "_") + "_" @@ -24,7 +23,6 @@ for filename in sys.argv[1:]: while not lines[end].strip().startswith("#endif"): end -= 1 lines[end] = "#endif // %s\n" % newguard - f = file(filename, "w") - f.write("".join(lines)) - f.close() + with open(filename, "w") as f: + f.write("".join(lines)) break diff --git a/radio/util/luaexport.py b/radio/util/luaexport.py index 512d7cf19..fdc86dd41 100755 --- a/radio/util/luaexport.py +++ b/radio/util/luaexport.py @@ -66,86 +66,80 @@ print("Output file %s" % outputFile) if docFile: print("Documentation file %s" % docFile) -np = open(inputFile, "r") +with open(inputFile, "r") as inp: + while True: + line = inp.readline() + if len(line) == 0: + break + line = line.strip('\r\n') + line = line.strip() + # print "line: %s" % line -while True: - line = inp.readline() - if len(line) == 0: - break - line = line.strip('\r\n') - line = line.strip() - # print "line: %s" % line + parts = line.split('LEXP') + # print parts + if len(parts) != 2: + print("Wrong line: %s" % line) + continue + cmd = 'LEXP' + parts[1] + cnst = parts[0].rstrip(', ') + if cnst.find('=') != -1: + # constant contains = + cnst = cnst.split('=')[0].strip() + # print "Found constant %s with command: %s" % (cnst, cmd) + try: + CONSTANT_VALUE = cnst + # if CONSTANT_VALUE in dups_cnst: + # print "WARNING: Duplicate CONSTANT_VALUE found: %s" % CONSTANT_VALUE + # warning = True + # continue + # dups_cnst.append(CONSTANT_VALUE) + # print cmd + eval(cmd) + except: + print("ERROR: problem with the definition: %s" % line) + traceback.print_exc() + error = True - parts = line.split('LEXP') - # print parts - if len(parts) != 2: - print("Wrong line: %s" % line) - continue - cmd = 'LEXP' + parts[1] - cnst = parts[0].rstrip(', ') - if cnst.find('=') != -1: - # constant contains = - cnst = cnst.split('=')[0].strip() - # print "Found constant %s with command: %s" % (cnst, cmd) - try: - CONSTANT_VALUE = cnst - # if CONSTANT_VALUE in dups_cnst: - # print "WARNING: Duplicate CONSTANT_VALUE found: %s" % CONSTANT_VALUE - # warning = True - # continue - # dups_cnst.append(CONSTANT_VALUE) - # print cmd - eval(cmd) - except: - print("ERROR: problem with the definition: %s" % line) - traceback.print_exc() - error = True +with open(outputFile, "w") as out: + out.write("//This file was generated by luaexport.py script on %s for OpenTX version %s\n\n\n" + % (time.asctime(), version)) -inp.close() + header = """ + struct LuaSingleField { + uint16_t id; + const char * name; + const char * desc; + }; -out = open(outputFile, "w") + struct LuaMultipleField { + uint16_t id; + const char * name; + const char * desc; + uint8_t count; + }; -out.write("//This file was generated by luaexport.py script on %s for OpenTX version %s\n\n\n" - % (time.asctime(), version)) + """ + out.write(header) -header = """ -struct LuaSingleField { - uint16_t id; - const char * name; - const char * desc; -}; + out.write(""" + // The list of Lua fields + // this aray is alphabetically sorted by the second field (name) + const LuaSingleField luaSingleFields[] = { + """) + exports.sort(key=lambda x: x[1]) # sort by name + data = [" {%s, \"%s\", \"%s\"}" % export for export in exports] + out.write(",\n".join(data)) + out.write("\n};\n\n") + print("Generated %d items in luaFields[]" % len(exports)) -struct LuaMultipleField { - uint16_t id; - const char * name; - const char * desc; - uint8_t count; -}; - -""" -out.write(header) - -out.write(""" -// The list of Lua fields -// this aray is alphabetically sorted by the second field (name) -const LuaSingleField luaSingleFields[] = { -""") -exports.sort(key=lambda x: x[1]) # sort by name -data = [" {%s, \"%s\", \"%s\"}" % export for export in exports] -out.write(",\n".join(data)) -out.write("\n};\n\n") -print("Generated %d items in luaFields[]" % len(exports)) - -out.write(""" -// The list of Lua fields that have a range of values -const LuaMultipleField luaMultipleFields[] = { -""") -data = [" {%s, \"%s\", \"%s\", %d}" % export for export in exports_multiple] -out.write(",\n".join(data)) -out.write("\n};\n\n") -print("Generated %d items in luaMultipleFields[]" % len(exports_multiple)) - -out.close() + out.write(""" + // The list of Lua fields that have a range of values + const LuaMultipleField luaMultipleFields[] = { + """) + data = [" {%s, \"%s\", \"%s\", %d}" % export for export in exports_multiple] + out.write(",\n".join(data)) + out.write("\n};\n\n") + print("Generated %d items in luaMultipleFields[]" % len(exports_multiple)) if docFile: # prepare fields @@ -160,16 +154,14 @@ if docFile: alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key[0])] all_exports.sort(key=alphanum_key) - out = open(docFile, "w") - out.write("Alphabetical list of Lua fields for OpenTX version %s\n\n\n" % version) - FIELD_NAME_WIDTH = 25 - out.write("Field name%sField description\n" % (' ' * (FIELD_NAME_WIDTH - len('Field name')))) - out.write("----------------------------------------------\n") - data = ["%s%s%s" % (name_, ' ' * (FIELD_NAME_WIDTH - len(name_)), desc_) for (name_, desc_) in all_exports] - out.write("\n".join(data)) - out.write("\n") - - out.close() + with open(docFile, "w") as out: + out.write("Alphabetical list of Lua fields for OpenTX version %s\n\n\n" % version) + FIELD_NAME_WIDTH = 25 + out.write("Field name%sField description\n" % (' ' * (FIELD_NAME_WIDTH - len('Field name')))) + out.write("----------------------------------------------\n") + data = ["%s%s%s" % (name_, ' ' * (FIELD_NAME_WIDTH - len(name_)), desc_) for (name_, desc_) in all_exports] + out.write("\n".join(data)) + out.write("\n") if warning: sys.exit(1)