auto_build.py 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455
  1. #######################################
  2. #
  3. # Marlin 3D Printer Firmware
  4. # Copyright (C) 2018 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
  5. #
  6. # Based on Sprinter and grbl.
  7. # Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
  8. #
  9. # This program is free software: you can redistribute it and/or modify
  10. # it under the terms of the GNU General Public License as published by
  11. # the Free Software Foundation, either version 3 of the License, or
  12. # (at your option) any later version.
  13. #
  14. # This program is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License
  20. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  21. #
  22. #######################################
  23. #######################################
  24. #
  25. # Revision: 2.0.1
  26. #
  27. # Description: script to automate PlatformIO builds
  28. # CLI: python auto_build.py build_option
  29. # build_option (required)
  30. # build executes -> platformio run -e target_env
  31. # clean executes -> platformio run --target clean -e target_env
  32. # upload executes -> platformio run --target upload -e target_env
  33. # traceback executes -> platformio run --target upload -e target_env
  34. # program executes -> platformio run --target program -e target_env
  35. # test executes -> platformio test upload -e target_env
  36. # remote executes -> platformio remote run --target upload -e target_env
  37. # debug executes -> platformio debug -e target_env
  38. #
  39. # 'traceback' just uses the debug variant of the target environment if one exists
  40. #
  41. #######################################
  42. #######################################
  43. #
  44. # General program flow
  45. #
  46. # 1. Scans Configuration.h for the motherboard name and Marlin version.
  47. # 2. Scans pins.h for the motherboard.
  48. # returns the CPU(s) and platformio environment(s) used by the motherboard
  49. # 3. If further info is needed then a popup gets it from the user.
  50. # 4. The OUTPUT_WINDOW class creates a window to display the output of the PlatformIO program.
  51. # 5. A thread is created by the OUTPUT_WINDOW class in order to execute the RUN_PIO function.
  52. # 6. The RUN_PIO function uses a subprocess to run the CLI version of PlatformIO.
  53. # 7. The "iter(pio_subprocess.stdout.readline, '')" function is used to stream the output of
  54. # PlatformIO back to the RUN_PIO function.
  55. # 8. Each line returned from PlatformIO is formatted to match the color coding seen in the
  56. # PlatformIO GUI.
  57. # 9. If there is a color change within a line then the line is broken at each color change
  58. # and sent separately.
  59. # 10. Each formatted segment (could be a full line or a split line) is put into the queue
  60. # IO_queue as it arrives from the platformio subprocess.
  61. # 11. The OUTPUT_WINDOW class periodically samples IO_queue. If data is available then it
  62. # is written to the window.
  63. # 12. The window stays open until the user closes it.
  64. # 13. The OUTPUT_WINDOW class continues to execute as long as the window is open. This allows
  65. # copying, saving, scrolling of the window. A right click popup is available.
  66. #
  67. #######################################
  68. import sys
  69. import os
  70. pwd = os.getcwd() # make sure we're executing from the correct directory level
  71. pwd = pwd.replace('\\', '/')
  72. if 0 <= pwd.find('buildroot/share/atom'):
  73. pwd = pwd[ : pwd.find('buildroot/share/atom')]
  74. os.chdir(pwd)
  75. print 'pwd: ', pwd
  76. num_args = len(sys.argv)
  77. if num_args > 1:
  78. build_type = str(sys.argv[1])
  79. else:
  80. print 'Please specify build type'
  81. exit()
  82. print'build_type: ', build_type
  83. print '\nWorking\n'
  84. python_ver = sys.version_info[0] # major version - 2 or 3
  85. if python_ver == 2:
  86. print "python version " + str(sys.version_info[0]) + "." + str(sys.version_info[1]) + "." + str(sys.version_info[2])
  87. else:
  88. print "python version " + str(sys.version_info[0])
  89. print "This script only runs under python 2"
  90. exit()
  91. import platform
  92. current_OS = platform.system()
  93. #globals
  94. target_env = ''
  95. board_name = ''
  96. #########
  97. # Python 2 error messages:
  98. # Can't find a usable init.tcl in the following directories ...
  99. # error "invalid command name "tcl_findLibrary""
  100. #
  101. # Fix for the above errors on my Win10 system:
  102. # search all init.tcl files for the line "package require -exact Tcl" that has the highest 8.5.x number
  103. # copy it into the first directory listed in the error messages
  104. # set the environmental variables TCLLIBPATH and TCL_LIBRARY to the directory where you found the init.tcl file
  105. # reboot
  106. #########
  107. #
  108. # data/definitions used by memory check routine to determine if need to
  109. # insert % memory used
  110. #
  111. mem_check_environments = ('at90USB1286_CDC', 'at90USB1286_DFU')
  112. mem_check_builds = ('upload', 'program')
  113. FLASH_MAX = 128 * 1024 - 4 * 1024 # DFU & CDC bootloaders start at word address F800
  114. RAM_MAX = 8 * 1024
  115. FLASH_PERCENT_WARN = 0.90
  116. RAM_SYSTEM = 1024 # assume that 1K bytes is enough for stack, heap. ...
  117. RAM_WARN = RAM_SYSTEM * 1.5
  118. ##########################################################################################
  119. #
  120. # popup to get input from user
  121. #
  122. ##########################################################################################
  123. def get_answer(board_name, cpu_label_txt, cpu_a_txt, cpu_b_txt):
  124. if python_ver == 2:
  125. import Tkinter as tk
  126. else:
  127. import tkinter as tk
  128. def CPU_exit_3(): # forward declare functions
  129. CPU_exit_3_()
  130. def CPU_exit_4():
  131. CPU_exit_4_()
  132. def kill_session():
  133. kill_session_()
  134. root_get_answer = tk.Tk()
  135. root_get_answer.chk_state_1 = 1 # declare variables used by TK and enable
  136. chk_state_1 = 0 # set initial state of check boxes
  137. global get_answer_val
  138. get_answer_val = 2 # return get_answer_val, set default to match chk_state_1 default
  139. l1 = tk.Label(text=board_name,
  140. fg = "light green",
  141. bg = "dark green",
  142. font = "Helvetica 12 bold").grid(row=1)
  143. l2 = tk.Label(text=cpu_label_txt,
  144. fg = "light green",
  145. bg = "dark green",
  146. font = "Helvetica 16 bold italic").grid(row=2)
  147. b4 = tk.Checkbutton(text=cpu_a_txt,
  148. fg = "black",
  149. font = "Times 20 bold ",
  150. variable=chk_state_1, onvalue=1, offvalue=0,
  151. command = CPU_exit_3).grid(row=3)
  152. b5 = tk.Checkbutton(text=cpu_b_txt,
  153. fg = "black",
  154. font = "Times 20 bold ",
  155. variable=chk_state_1, onvalue=0, offvalue=1,
  156. command = CPU_exit_4).grid(row=4) # use same variable but inverted so they will track
  157. b6 = tk.Button(text="CONFIRM",
  158. fg = "blue",
  159. font = "Times 20 bold ",
  160. command = root_get_answer.destroy).grid(row=5, pady=4)
  161. b7 = tk.Button(text="CANCEL",
  162. fg = "red",
  163. font = "Times 12 bold ",
  164. command = kill_session).grid(row=6, pady=4)
  165. def CPU_exit_3_():
  166. global get_answer_val
  167. get_answer_val = 1
  168. def CPU_exit_4_():
  169. global get_answer_val
  170. get_answer_val = 2
  171. def kill_session_():
  172. raise SystemExit(0) # kill everything
  173. root_get_answer.mainloop()
  174. # end - get answer
  175. #
  176. # move custom board definitions from project folder to PlatformIO
  177. #
  178. def resolve_path(path):
  179. import os
  180. # turn the selection into a partial path
  181. if 0 <= path.find('"'):
  182. path = path[ path.find('"') : ]
  183. if 0 <= path.find(', line '):
  184. path = path.replace(', line ', ':')
  185. path = path.replace('"', '')
  186. #get line and column numbers
  187. line_num = 1
  188. column_num = 1
  189. line_start = path.find(':', 2) # use 2 here so don't eat Windows full path
  190. column_start = path.find(':', line_start + 1)
  191. if column_start == -1:
  192. column_start = len(path)
  193. column_end = path.find(':', column_start + 1)
  194. if column_end == -1:
  195. column_end = len(path)
  196. if 0 <= line_start:
  197. line_num = path[ line_start + 1 : column_start]
  198. if line_num == '':
  199. line_num = 1
  200. if not(column_start == column_end):
  201. column_num = path[ column_start + 1 : column_end]
  202. if column_num == '':
  203. column_num = 0
  204. index_end = path.find(',')
  205. if 0 <= index_end:
  206. path = path[ : index_end] # delete comma and anything after
  207. index_end = path.find(':', 2)
  208. if 0 <= index_end:
  209. path = path[ : path.find(':', 2)] # delete the line number and anything after
  210. path = path.replace('\\','/')
  211. if 1 == path.find(':') and current_OS == 'Windows':
  212. return path, line_num, column_num # found a full path - no need for further processing
  213. elif 0 == path.find('/') and (current_OS == 'Linux' or current_OS == 'Darwin'):
  214. return path, line_num, column_num # found a full path - no need for further processing
  215. else:
  216. # resolve as many '../' as we can
  217. while 0 <= path.find('../'):
  218. end = path.find('../') - 1
  219. start = path.find('/')
  220. while 0 <= path.find('/',start) and end > path.find('/',start):
  221. start = path.find('/',start) + 1
  222. path = path[0:start] + path[end + 4: ]
  223. # this is an alternative to the above - it just deletes the '../' section
  224. # start_temp = path.find('../')
  225. # while 0 <= path.find('../',start_temp):
  226. # start = path.find('../',start_temp)
  227. # start_temp = start + 1
  228. # if 0 <= start:
  229. # path = path[start + 2 : ]
  230. start = path.find('/')
  231. if not(0 == start): # make sure path starts with '/'
  232. while 0 == path.find(' '): # eat any spaces at the beginning
  233. path = path[ 1 : ]
  234. path = '/' + path
  235. if current_OS == 'Windows':
  236. search_path = path.replace('/', '\\') # os.walk uses '\' in Windows
  237. else:
  238. search_path = path
  239. start_path = os.path.abspath('')
  240. # search project directory for the selection
  241. found = False
  242. full_path = ''
  243. for root, directories, filenames in os.walk(start_path):
  244. for filename in filenames:
  245. if 0 <= root.find('.git'): # don't bother looking in this directory
  246. break
  247. full_path = os.path.join(root,filename)
  248. if 0 <= full_path.find(search_path):
  249. found = True
  250. break
  251. if found:
  252. break
  253. return full_path, line_num, column_num
  254. # end - resolve_path
  255. #
  256. # Opens the file in the preferred editor at the line & column number
  257. # If the preferred editor isn't already running then it tries the next.
  258. # If none are open then the system default is used.
  259. #
  260. # Editor order:
  261. # 1. Notepad++ (Windows only)
  262. # 2. Sublime Text
  263. # 3. Atom
  264. # 4. System default (opens at line 1, column 1 only)
  265. #
  266. def open_file(path):
  267. import subprocess
  268. file_path, line_num, column_num = resolve_path(path)
  269. if file_path == '' :
  270. return
  271. if current_OS == 'Windows':
  272. editor_note = subprocess.check_output('wmic process where "name=' + "'notepad++.exe'" + '" get ExecutablePath')
  273. editor_sublime = subprocess.check_output('wmic process where "name=' + "'sublime_text.exe'" + '" get ExecutablePath')
  274. editor_atom = subprocess.check_output('wmic process where "name=' + "'atom.exe'" + '" get ExecutablePath')
  275. if 0 <= editor_note.find('notepad++.exe'):
  276. start = editor_note.find('\n') + 1
  277. end = editor_note.find('\n',start + 5) -4
  278. editor_note = editor_note[ start : end]
  279. command = file_path , ' -n' + str(line_num) , ' -c' + str(column_num)
  280. subprocess.Popen([editor_note, command])
  281. elif 0 <= editor_sublime.find('sublime_text.exe'):
  282. start = editor_sublime.find('\n') + 1
  283. end = editor_sublime.find('\n',start + 5) -4
  284. editor_sublime = editor_sublime[ start : end]
  285. command = file_path + ':' + line_num + ':' + column_num
  286. subprocess.Popen([editor_sublime, command])
  287. elif 0 <= editor_atom.find('atom.exe'):
  288. start = editor_atom.find('\n') + 1
  289. end = editor_atom.find('\n',start + 5) -4
  290. editor_atom = editor_atom[ start : end]
  291. command = file_path + ':' + str(line_num) + ':' + str(column_num)
  292. subprocess.Popen([editor_atom, command])
  293. else:
  294. os.startfile(resolve_path(path)) # open file with default app
  295. elif current_OS == 'Linux':
  296. command = file_path + ':' + str(line_num) + ':' + str(column_num)
  297. index_end = command.find(',')
  298. if 0 <= index_end:
  299. command = command[ : index_end] # sometimes a comma magically appears, don't want it
  300. running_apps = subprocess.Popen('ps ax -o cmd', stdout=subprocess.PIPE, shell=True)
  301. (output, err) = running_apps.communicate()
  302. temp = output.split('\n')
  303. def find_editor_linux(name, search_obj):
  304. for line in search_obj:
  305. if 0 <= line.find(name):
  306. path = line
  307. return True, path
  308. return False , ''
  309. (success_sublime, editor_path_sublime) = find_editor_linux('sublime_text',temp)
  310. (success_atom, editor_path_atom) = find_editor_linux('atom',temp)
  311. if success_sublime:
  312. subprocess.Popen([editor_path_sublime, command])
  313. elif success_atom:
  314. subprocess.Popen([editor_path_atom, command])
  315. else:
  316. os.system('xdg-open ' + file_path )
  317. elif current_OS == 'Darwin': # MAC
  318. command = file_path + ':' + str(line_num) + ':' + str(column_num)
  319. index_end = command.find(',')
  320. if 0 <= index_end:
  321. command = command[ : index_end] # sometimes a comma magically appears, don't want it
  322. running_apps = subprocess.Popen('ps axwww -o command', stdout=subprocess.PIPE, shell=True)
  323. (output, err) = running_apps.communicate()
  324. temp = output.split('\n')
  325. def find_editor_mac(name, search_obj):
  326. for line in search_obj:
  327. if 0 <= line.find(name):
  328. path = line
  329. if 0 <= path.find('-psn'):
  330. path = path[ : path.find('-psn') - 1 ]
  331. return True, path
  332. return False , ''
  333. (success_sublime, editor_path_sublime) = find_editor_mac('Sublime',temp)
  334. (success_atom, editor_path_atom) = find_editor_mac('Atom',temp)
  335. if success_sublime:
  336. subprocess.Popen([editor_path_sublime, command])
  337. elif success_atom:
  338. subprocess.Popen([editor_path_atom, command])
  339. else:
  340. os.system('open ' + file_path )
  341. # end - open_file
  342. # gets the last build environment
  343. def get_build_last():
  344. env_last = ''
  345. DIR_PWD = os.listdir('.')
  346. if '.pioenvs' in DIR_PWD:
  347. date_last = 0.0
  348. DIR__pioenvs = os.listdir('.pioenvs')
  349. for name in DIR__pioenvs:
  350. if 0 <= name.find('.') or 0 <= name.find('-'): # skip files in listing
  351. continue
  352. DIR_temp = os.listdir('.pioenvs/' + name)
  353. for names_temp in DIR_temp:
  354. if 0 == names_temp.find('firmware.'):
  355. date_temp = os.path.getmtime('.pioenvs/' + name + '/' + names_temp)
  356. if date_temp > date_last:
  357. date_last = date_temp
  358. env_last = name
  359. return env_last
  360. # gets the board being built from the Configuration.h file
  361. # returns: board name, major version of Marlin being used (1 or 2)
  362. def get_board_name():
  363. board_name = ''
  364. # get board name
  365. with open('Marlin/Configuration.h', 'r') as myfile:
  366. Configuration_h = myfile.read()
  367. Configuration_h = Configuration_h.split('\n')
  368. Marlin_ver = 0 # set version to invalid number
  369. for lines in Configuration_h:
  370. if 0 == lines.find('#define CONFIGURATION_H_VERSION 01'):
  371. Marlin_ver = 1
  372. if 0 == lines.find('#define CONFIGURATION_H_VERSION 02'):
  373. Marlin_ver = 2
  374. board = lines.find(' BOARD_') + 1
  375. motherboard = lines.find(' MOTHERBOARD ') + 1
  376. define = lines.find('#define ')
  377. comment = lines.find('//')
  378. if (comment == -1 or comment > board) and \
  379. board > motherboard and \
  380. motherboard > define and \
  381. define >= 0 :
  382. spaces = lines.find(' ', board) # find the end of the board substring
  383. if spaces == -1:
  384. board_name = lines[board : ]
  385. else:
  386. board_name = lines[board : spaces]
  387. break
  388. return board_name, Marlin_ver
  389. # extract first environment name it finds after the start position
  390. # returns: environment name and position to start the next search from
  391. def get_env_from_line(line, start_position):
  392. env = ''
  393. next_position = -1
  394. env_position = line.find('env:', start_position)
  395. if 0 < env_position:
  396. next_position = line.find(' ', env_position + 4)
  397. if 0 < next_position:
  398. env = line[env_position + 4 : next_position]
  399. else:
  400. env = line[env_position + 4 : ] # at the end of the line
  401. return env, next_position
  402. #scans pins.h for board name and returns the environment(s) it finds
  403. def get_starting_env(board_name_full, version):
  404. # get environment starting point
  405. if version == 1:
  406. path = 'Marlin/pins.h'
  407. if version == 2:
  408. path = 'Marlin/src/pins/pins.h'
  409. with open(path, 'r') as myfile:
  410. pins_h = myfile.read()
  411. env_A = ''
  412. env_B = ''
  413. env_C = ''
  414. board_name = board_name_full[ 6 : ] # only use the part after "BOARD_" since we're searching the pins.h file
  415. pins_h = pins_h.split('\n')
  416. environment = ''
  417. board_line = ''
  418. cpu_A = ''
  419. cpu_B = ''
  420. i = 0
  421. list_start_found = False
  422. for lines in pins_h:
  423. i = i + 1 # i is always one ahead of the index into pins_h
  424. if 0 < lines.find("Unknown MOTHERBOARD value set in Configuration.h"):
  425. break # no more
  426. if 0 < lines.find('1280'):
  427. list_start_found = True
  428. if list_start_found == False: # skip lines until find start of CPU list
  429. continue
  430. board = lines.find(board_name)
  431. comment_start = lines.find('// ')
  432. cpu_A_loc = comment_start
  433. cpu_B_loc = 0
  434. if board > 0: # need to look at the next line for environment info
  435. cpu_line = pins_h[i]
  436. comment_start = cpu_line.find('// ')
  437. env_A, next_position = get_env_from_line(cpu_line, comment_start) # get name of environment & start of search for next
  438. env_B, next_position = get_env_from_line(cpu_line, next_position) # get next environment, if it exists
  439. env_C, next_position = get_env_from_line(cpu_line, next_position) # get next environment, if it exists
  440. break
  441. return env_A, env_B, env_C
  442. # scans input string for CPUs that the users may need to select from
  443. # returns: CPU name
  444. def get_CPU_name(environment):
  445. CPU_list = ('1280', '2560','644', '1284', 'LPC1768', 'DUE')
  446. CPU_name = ''
  447. for CPU in CPU_list:
  448. if 0 < environment.find(CPU):
  449. return CPU
  450. # get environment to be used for the build
  451. # returns: environment
  452. def get_env(board_name, ver_Marlin):
  453. def no_environment():
  454. print 'ERROR - no environment for this board'
  455. print board_name
  456. raise SystemExit(0) # no environment so quit
  457. def invalid_board():
  458. print 'ERROR - invalid board'
  459. print board_name
  460. raise SystemExit(0) # quit if unable to find board
  461. CPU_question = ( ('1280', '2560', " 1280 or 2560 CPU? "), ('644', '1284', " 644 or 1284 CPU? ") )
  462. if 0 < board_name.find('MELZI') :
  463. get_answer(' ' + board_name + ' ', " Which flavor of Melzi? ", "Melzi (Optiboot bootloader)", "Melzi ")
  464. if 1 == get_answer_val:
  465. target_env = 'melzi_optiboot'
  466. else:
  467. target_env = 'melzi'
  468. else:
  469. env_A, env_B, env_C = get_starting_env(board_name, ver_Marlin)
  470. if env_A == '':
  471. no_environment()
  472. if env_B == '':
  473. return env_A # only one environment so finished
  474. CPU_A = get_CPU_name(env_A)
  475. CPU_B = get_CPU_name(env_B)
  476. for item in CPU_question:
  477. if CPU_A == item[0]:
  478. get_answer(' ' + board_name + ' ', item[2], item[0], item[1])
  479. if 2 == get_answer_val:
  480. target_env = env_B
  481. else:
  482. target_env = env_A
  483. return target_env
  484. if env_A == 'LPC1768':
  485. if build_type == 'traceback' or (build_type == 'clean' and get_build_last() == 'LPC1768_debug_and_upload'):
  486. target_env = 'LPC1768_debug_and_upload'
  487. else:
  488. target_env = 'LPC1768'
  489. elif env_A == 'DUE':
  490. target_env = 'DUE'
  491. if build_type == 'traceback' or (build_type == 'clean' and get_build_last() == 'DUE_debug'):
  492. target_env = 'DUE_debug'
  493. elif env_B == 'DUE_USB':
  494. get_answer(' ' + board_name + ' ', " DUE: need download port ", "USB (native USB) port", "Programming port ")
  495. if 1 == get_answer_val:
  496. target_env = 'DUE_USB'
  497. else:
  498. target_env = 'DUE'
  499. else:
  500. invalid_board()
  501. if build_type == 'traceback' and not(target_env == 'LPC1768_debug_and_upload' or target_env == 'DUE_debug') and Marlin_ver == 2:
  502. print "ERROR - this board isn't setup for traceback"
  503. print 'board_name: ', board_name
  504. print 'target_env: ', target_env
  505. raise SystemExit(0)
  506. return target_env
  507. # end - get_env
  508. # puts screen text into queue so that the parent thread can fetch the data from this thread
  509. import Queue
  510. IO_queue = Queue.Queue()
  511. PIO_queue = Queue.Queue()
  512. def write_to_screen_queue(text, format_tag = 'normal'):
  513. double_in = [text, format_tag]
  514. IO_queue.put(double_in, block = False)
  515. #
  516. # send one line to the terminal screen with syntax highlighting
  517. #
  518. # input: unformatted text, flags from previous run
  519. # returns: formatted text ready to go to the terminal, flags from this run
  520. #
  521. # This routine remembers the status from call to call because previous
  522. # lines can affect how the current line is highlighted
  523. #
  524. # 'static' variables - init here and then keep updating them from within print_line
  525. warning = False
  526. warning_FROM = False
  527. error = False
  528. standard = True
  529. prev_line_COM = False
  530. next_line_warning = False
  531. warning_continue = False
  532. line_counter = 0
  533. def line_print(line_input):
  534. global warning
  535. global warning_FROM
  536. global error
  537. global standard
  538. global prev_line_COM
  539. global next_line_warning
  540. global warning_continue
  541. global line_counter
  542. # all '0' elements must precede all '1' elements or they'll be skipped
  543. platformio_highlights = [
  544. ['Environment', 0, 'highlight_blue'],
  545. ['[SKIP]', 1, 'warning'],
  546. ['[ERROR]', 1, 'error'],
  547. ['[SUCCESS]', 1, 'highlight_green']
  548. ]
  549. def write_to_screen_with_replace(text, highlights): # search for highlights & split line accordingly
  550. did_something = False
  551. for highlight in highlights:
  552. found = text.find(highlight[0])
  553. if did_something == True:
  554. break
  555. if found >= 0 :
  556. did_something = True
  557. if 0 == highlight[1]:
  558. found_1 = text.find(' ')
  559. found_tab = text.find('\t')
  560. if found_1 < 0 or found_1 > found_tab:
  561. found_1 = found_tab
  562. write_to_screen_queue(text[ : found_1 + 1 ])
  563. for highlight_2 in highlights:
  564. if highlight[0] == highlight_2[0] :
  565. continue
  566. found = text.find(highlight_2[0])
  567. if found >= 0 :
  568. found_space = text.find(' ', found_1 + 1)
  569. found_tab = text.find('\t', found_1 + 1)
  570. if found_space < 0 or found_space > found_tab:
  571. found_space = found_tab
  572. found_right = text.find(']', found + 1)
  573. write_to_screen_queue(text[found_1 + 1 : found_space + 1 ], highlight[2])
  574. write_to_screen_queue(text[found_space + 1 : found + 1 ])
  575. write_to_screen_queue(text[found + 1 : found_right], highlight_2[2])
  576. write_to_screen_queue(text[found_right : ] + '\n')
  577. break
  578. break
  579. if 1 == highlight[1]:
  580. found_right = text.find(']', found + 1)
  581. write_to_screen_queue(text[ : found + 1 ])
  582. write_to_screen_queue(text[found + 1 : found_right ], highlight[2])
  583. write_to_screen_queue(text[found_right : ] + '\n')
  584. break
  585. if did_something == False:
  586. r_loc = text.find('\r') + 1
  587. if r_loc > 0 and r_loc < len(text): # need to split this line
  588. text = text.split('\r')
  589. for line in text:
  590. write_to_screen_queue(line + '\n')
  591. else:
  592. write_to_screen_queue(text + '\n')
  593. # end - write_to_screen_with_replace
  594. # scan the line
  595. line_counter = line_counter + 1
  596. max_search = len(line_input)
  597. if max_search > 3 :
  598. max_search = 3
  599. beginning = line_input[:max_search]
  600. # set flags
  601. if 0 < line_input.find(': warning: '): # start of warning block
  602. warning = True
  603. warning_FROM = False
  604. error = False
  605. standard = False
  606. prev_line_COM = False
  607. prev_line_COM = False
  608. warning_continue = True
  609. if 0 < line_input.find('Thank you') or 0 < line_input.find('SUMMARY') :
  610. warning = False #standard line found
  611. warning_FROM = False
  612. error = False
  613. standard = True
  614. prev_line_COM = False
  615. warning_continue = False
  616. elif beginning == 'War' or \
  617. beginning == '#er' or \
  618. beginning == 'In ' or \
  619. (beginning != 'Com' and prev_line_COM == True and not(beginning == 'Arc' or beginning == 'Lin' or beginning == 'Ind') or \
  620. next_line_warning == True):
  621. warning = True #warning found
  622. warning_FROM = False
  623. error = False
  624. standard = False
  625. prev_line_COM = False
  626. elif beginning == 'Com' or \
  627. beginning == 'Ver' or \
  628. beginning == ' [E' or \
  629. beginning == 'Rem' or \
  630. beginning == 'Bui' or \
  631. beginning == 'Ind' or \
  632. beginning == 'PLA':
  633. warning = False #standard line found
  634. warning_FROM = False
  635. error = False
  636. standard = True
  637. prev_line_COM = False
  638. warning_continue = False
  639. elif beginning == '***':
  640. warning = False # error found
  641. warning_FROM = False
  642. error = True
  643. standard = False
  644. prev_line_COM = False
  645. elif 0 < line_input.find(': error:') or \
  646. 0 < line_input.find(': fatal error:'): # start of warning /error block
  647. warning = False # error found
  648. warning_FROM = False
  649. error = True
  650. standard = False
  651. prev_line_COM = False
  652. warning_continue = True
  653. elif beginning == 'fro' and warning == True or \
  654. beginning == '.pi' : # start of warning /error block
  655. warning_FROM = True
  656. prev_line_COM = False
  657. warning_continue = True
  658. elif warning_continue == True:
  659. warning = True
  660. warning_FROM = False # keep the warning status going until find a standard line or an error
  661. error = False
  662. standard = False
  663. prev_line_COM = False
  664. warning_continue = True
  665. else:
  666. warning = False # unknown so assume standard line
  667. warning_FROM = False
  668. error = False
  669. standard = True
  670. prev_line_COM = False
  671. warning_continue = False
  672. if beginning == 'Com':
  673. prev_line_COM = True
  674. # print based on flags
  675. if standard == True:
  676. write_to_screen_with_replace(line_input, platformio_highlights) #print white on black with substitutions
  677. if warning == True:
  678. write_to_screen_queue(line_input + '\n', 'warning')
  679. if error == True:
  680. write_to_screen_queue(line_input + '\n', 'error')
  681. # end - line_print
  682. def run_PIO(dummy):
  683. ##########################################################################
  684. # #
  685. # run Platformio #
  686. # #
  687. ##########################################################################
  688. # build platformio run -e target_env
  689. # clean platformio run --target clean -e target_env
  690. # upload platformio run --target upload -e target_env
  691. # traceback platformio run --target upload -e target_env
  692. # program platformio run --target program -e target_env
  693. # test platformio test upload -e target_env
  694. # remote platformio remote run --target upload -e target_env
  695. # debug platformio debug -e target_env
  696. global build_type
  697. global target_env
  698. global board_name
  699. print 'build_type: ', build_type
  700. import subprocess
  701. import sys
  702. print 'starting platformio'
  703. if build_type == 'build':
  704. # platformio run -e target_env
  705. # combine stdout & stderr so all compile messages are included
  706. pio_subprocess = subprocess.Popen(['platformio', 'run', '-e', target_env], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  707. elif build_type == 'clean':
  708. # platformio run --target clean -e target_env
  709. # combine stdout & stderr so all compile messages are included
  710. pio_subprocess = subprocess.Popen(['platformio', 'run', '--target', 'clean', '-e', target_env], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  711. elif build_type == 'upload':
  712. # platformio run --target upload -e target_env
  713. # combine stdout & stderr so all compile messages are included
  714. pio_subprocess = subprocess.Popen(['platformio', 'run', '--target', 'upload', '-e', target_env], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  715. elif build_type == 'traceback':
  716. # platformio run --target upload -e target_env - select the debug environment if there is one
  717. # combine stdout & stderr so all compile messages are included
  718. pio_subprocess = subprocess.Popen(['platformio', 'run', '--target', 'upload', '-e', target_env], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  719. elif build_type == 'program':
  720. # platformio run --target program -e target_env
  721. # combine stdout & stderr so all compile messages are included
  722. pio_subprocess = subprocess.Popen(['platformio', 'run', '--target', 'program', '-e', target_env], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  723. elif build_type == 'test':
  724. #platformio test upload -e target_env
  725. # combine stdout & stderr so all compile messages are included
  726. pio_subprocess = subprocess.Popen(['platformio', 'test', 'upload', '-e', target_env], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  727. elif build_type == 'remote':
  728. # platformio remote run --target upload -e target_env
  729. # combine stdout & stderr so all compile messages are included
  730. pio_subprocess = subprocess.Popen(['platformio', 'remote', 'run', '--target', 'program', '-e', target_env], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  731. elif build_type == 'debug':
  732. # platformio debug -e target_env
  733. # combine stdout & stderr so all compile messages are included
  734. pio_subprocess = subprocess.Popen(['platformio', 'debug', '-e', target_env], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  735. else:
  736. print 'ERROR - unknown build type: ', build_type
  737. raise SystemExit(0) # kill everything
  738. # stream output from subprocess and split it into lines
  739. for line in iter(pio_subprocess.stdout.readline, ''):
  740. line_print(line.replace('\n', ''))
  741. # append info used to run PlatformIO
  742. write_to_screen_queue('\nBoard name: ' + board_name + '\n') # put build info at the bottom of the screen
  743. write_to_screen_queue('Build type: ' + build_type + '\n')
  744. write_to_screen_queue('Environment used: ' + target_env + '\n')
  745. # end - run_PIO
  746. ########################################################################
  747. import time
  748. import threading
  749. import Tkinter as tk
  750. import ttk
  751. import Queue
  752. import subprocess
  753. import sys
  754. que = Queue.Queue()
  755. #IO_queue = Queue.Queue()
  756. from Tkinter import Tk, Frame, Text, Scrollbar, Menu
  757. from tkMessageBox import askokcancel
  758. import tkFileDialog
  759. from tkMessageBox import askokcancel
  760. import tkFileDialog
  761. class output_window(Text):
  762. # based on Super Text
  763. global continue_updates
  764. continue_updates = True
  765. global search_position
  766. search_position = '' # start with invalid search position
  767. global error_found
  768. error_found = False # are there any errors?
  769. global memory_check_first_time
  770. memory_check_first_time = True # wants to run memory_check twice
  771. def __init__(self):
  772. self.root = tk.Tk()
  773. self.frame = tk.Frame(self.root)
  774. self.frame.pack(fill='both', expand=True)
  775. # text widget
  776. #self.text = tk.Text(self.frame, borderwidth=3, relief="sunken")
  777. Text.__init__(self, self.frame, borderwidth=3, relief="sunken")
  778. self.config(tabs=(400,)) # configure Text widget tab stops
  779. self.config(background = 'black', foreground = 'white', font= ("consolas", 12), wrap = 'word', undo = 'True')
  780. # self.config(background = 'black', foreground = 'white', font= ("consolas", 12), wrap = 'none', undo = 'True')
  781. self.config(height = 24, width = 100)
  782. self.config(insertbackground = 'pale green') # keyboard insertion point
  783. self.pack(side='left', fill='both', expand=True)
  784. self.tag_config('normal', foreground = 'white')
  785. self.tag_config('warning', foreground = 'yellow' )
  786. self.tag_config('error', foreground = 'red')
  787. self.tag_config('highlight_green', foreground = 'green')
  788. self.tag_config('highlight_blue', foreground = 'cyan')
  789. self.tag_config('error_highlight_inactive', background = 'dim gray')
  790. self.tag_config('error_highlight_active', background = 'light grey')
  791. self.bind_class("Text","<Control-a>", self.select_all) # required in windows, works in others
  792. self.bind_all("<Control-Shift-E>", self.scroll_errors)
  793. self.bind_class("<Control-Shift-R>", self.rebuild)
  794. # scrollbar
  795. scrb = tk.Scrollbar(self.frame, orient='vertical', command=self.yview)
  796. self.config(yscrollcommand=scrb.set)
  797. scrb.pack(side='right', fill='y')
  798. # self.scrb_Y = tk.Scrollbar(self.frame, orient='vertical', command=self.yview)
  799. # self.scrb_Y.config(yscrollcommand=self.scrb_Y.set)
  800. # self.scrb_Y.pack(side='right', fill='y')
  801. #
  802. # self.scrb_X = tk.Scrollbar(self.frame, orient='horizontal', command=self.xview)
  803. # self.scrb_X.config(xscrollcommand=self.scrb_X.set)
  804. # self.scrb_X.pack(side='bottom', fill='x')
  805. # scrb_X = tk.Scrollbar(self, orient=tk.HORIZONTAL, command=self.xview) # tk.HORIZONTAL now have a horizsontal scroll bar BUT... shrinks it to a postage stamp and hides far right behind the vertical scroll bar
  806. # self.config(xscrollcommand=scrb_X.set)
  807. # scrb_X.pack(side='bottom', fill='x')
  808. #
  809. # scrb= tk.Scrollbar(self, orient='vertical', command=self.yview)
  810. # self.config(yscrollcommand=scrb.set)
  811. # scrb.pack(side='right', fill='y')
  812. # self.config(height = 240, width = 1000) # didn't get the size baCK TO NORMAL
  813. # self.pack(side='left', fill='both', expand=True) # didn't get the size baCK TO NORMAL
  814. # pop-up menu
  815. self.popup = tk.Menu(self, tearoff=0)
  816. self.popup.add_command(label='Copy', command=self._copy)
  817. self.popup.add_command(label='Paste', command=self._paste)
  818. self.popup.add_separator()
  819. self.popup.add_command(label='Cut', command=self._cut)
  820. self.popup.add_separator()
  821. self.popup.add_command(label='Select All', command=self._select_all)
  822. self.popup.add_command(label='Clear All', command=self._clear_all)
  823. self.popup.add_separator()
  824. self.popup.add_command(label='Save As', command=self._file_save_as)
  825. self.popup.add_separator()
  826. # self.popup.add_command(label='Repeat Build(CTL-shift-r)', command=self._rebuild)
  827. self.popup.add_command(label='Repeat Build', command=self._rebuild)
  828. self.popup.add_separator()
  829. self.popup.add_command(label='Scroll Errors (CTL-shift-e)', command=self._scroll_errors)
  830. self.popup.add_separator()
  831. self.popup.add_command(label='Open File at Cursor', command=self._open_selected_file)
  832. if current_OS == 'Darwin': # MAC
  833. self.bind('<Button-2>', self._show_popup) # macOS only
  834. else:
  835. self.bind('<Button-3>', self._show_popup) # Windows & Linux
  836. # threading & subprocess section
  837. def start_thread(self, ):
  838. global continue_updates
  839. # create then start a secondary thread to run an arbitrary function
  840. # must have at least one argument
  841. self.secondary_thread = threading.Thread(target = lambda q, arg1: q.put(run_PIO(arg1)), args=(que, ''))
  842. self.secondary_thread.start()
  843. continue_updates = True
  844. # check the Queue in 50ms
  845. self.root.after(50, self.check_thread)
  846. self.root.after(50, self.update)
  847. def check_thread(self): # wait for user to kill the window
  848. global continue_updates
  849. if continue_updates == True:
  850. self.root.after(10, self.check_thread)
  851. def update(self):
  852. global continue_updates
  853. if continue_updates == True:
  854. self.root.after(10, self.update)#method is called every 50ms
  855. temp_text = ['0','0']
  856. if IO_queue.empty():
  857. if not(self.secondary_thread.is_alive()):
  858. continue_updates = False # queue is exhausted and thread is dead so no need for further updates
  859. self.memory_check() # scan buffer and add percent used if needed
  860. print 'starting memory check'
  861. else:
  862. try:
  863. temp_text = IO_queue.get(block = False)
  864. except Queue.Empty:
  865. continue_updates = False # queue is exhausted so no need for further updates
  866. else:
  867. self.insert('end', temp_text[0], temp_text[1])
  868. self.see("end") # make the last line visible (scroll text off the top)
  869. # text editing section
  870. def _scroll_errors(self):
  871. global search_position
  872. global error_found
  873. if search_position == '': # first time so highlight all errors
  874. countVar = tk.IntVar()
  875. search_position = '1.0'
  876. search_count = 0
  877. while not(search_position == '') and search_count < 100:
  878. search_position = self.search("error", search_position, stopindex="end", count=countVar, nocase=1)
  879. search_count = search_count + 1
  880. if not(search_position == ''):
  881. error_found = True
  882. end_pos = '{}+{}c'.format(search_position, 5)
  883. self.tag_add("error_highlight_inactive", search_position, end_pos)
  884. search_position = '{}+{}c'.format(search_position, 1) # point to the next character for new search
  885. else:
  886. break
  887. if error_found:
  888. if search_position == '':
  889. search_position = self.search("error", '1.0', stopindex="end", nocase=1) # new search
  890. else: # remove active highlight
  891. end_pos = '{}+{}c'.format(search_position, 5)
  892. start_pos = '{}+{}c'.format(search_position, -1)
  893. self.tag_remove("error_highlight_active", start_pos, end_pos)
  894. search_position = self.search("error", search_position, stopindex="end", nocase=1) # finds first occurrence AGAIN on the first time through
  895. if search_position == "": # wrap around
  896. search_position = self.search("error", '1.0', stopindex="end", nocase=1)
  897. end_pos = '{}+{}c'.format(search_position, 5)
  898. self.tag_add("error_highlight_active", search_position, end_pos) # add active highlight
  899. self.see(search_position)
  900. search_position = '{}+{}c'.format(search_position, 1) # point to the next character for new search
  901. def scroll_errors(self, event):
  902. self._scroll_errors()
  903. def _rebuild(self):
  904. #global board_name
  905. #global Marlin_ver
  906. #global target_env
  907. #board_name, Marlin_ver = get_board_name()
  908. #target_env = get_env(board_name, Marlin_ver)
  909. self.start_thread()
  910. def rebuild(self, event):
  911. print "event happened"
  912. self._rebuild()
  913. def _open_selected_file(self):
  914. current_line = self.index('insert')
  915. line_start = current_line[ : current_line.find('.')] + '.0'
  916. line_end = current_line[ : current_line.find('.')] + '.200'
  917. self.mark_set("path_start", line_start)
  918. self.mark_set("path_end", line_end)
  919. path = self.get("path_start", "path_end")
  920. from_loc = path.find('from ')
  921. colon_loc = path.find(': ')
  922. if 0 <= from_loc and ((colon_loc == -1) or (from_loc < colon_loc)) :
  923. path = path [ from_loc + 5 : ]
  924. if 0 <= colon_loc:
  925. path = path [ : colon_loc ]
  926. if 0 <= path.find('\\') or 0 <= path.find('/'): # make sure it really contains a path
  927. open_file(path)
  928. def _file_save_as(self):
  929. self.filename = tkFileDialog.asksaveasfilename(defaultextension = '.txt')
  930. f = open(self.filename, 'w')
  931. f.write(self.get('1.0', 'end'))
  932. f.close()
  933. def copy(self, event):
  934. try:
  935. selection = self.get(*self.tag_ranges('sel'))
  936. self.clipboard_clear()
  937. self.clipboard_append(selection)
  938. except TypeError:
  939. pass
  940. def cut(self, event):
  941. try:
  942. selection = self.get(*self.tag_ranges('sel'))
  943. self.clipboard_clear()
  944. self.clipboard_append(selection)
  945. self.delete(*self.tag_ranges('sel'))
  946. except TypeError:
  947. pass
  948. def _show_popup(self, event):
  949. '''right-click popup menu'''
  950. if self.root.focus_get() != self:
  951. self.root.focus_set()
  952. try:
  953. self.popup.tk_popup(event.x_root, event.y_root, 0)
  954. finally:
  955. self.popup.grab_release()
  956. def _cut(self):
  957. try:
  958. selection = self.get(*self.tag_ranges('sel'))
  959. self.clipboard_clear()
  960. self.clipboard_append(selection)
  961. self.delete(*self.tag_ranges('sel'))
  962. except TypeError:
  963. pass
  964. def cut(self, event):
  965. self._cut()
  966. def _copy(self):
  967. try:
  968. selection = self.get(*self.tag_ranges('sel'))
  969. self.clipboard_clear()
  970. self.clipboard_append(selection)
  971. except TypeError:
  972. pass
  973. def copy(self, event):
  974. self._copy()
  975. def _paste(self):
  976. self.insert('insert', self.selection_get(selection='CLIPBOARD'))
  977. def _select_all(self):
  978. self.tag_add('sel', '1.0', 'end')
  979. def select_all(self, event):
  980. self.tag_add('sel', '1.0', 'end')
  981. def _clear_all(self):
  982. '''erases all text'''
  983. isok = askokcancel('Clear All', 'Erase all text?', frame=self,
  984. default='ok')
  985. if isok:
  986. self.delete('1.0', 'end')
  987. # add memory % if needed
  988. def memory_check(self):
  989. global memory_check_first_time
  990. if not(memory_check_first_time):
  991. return
  992. memory_check_first_time = False
  993. search_position = self.search("Environment used:", "1.0", stopindex="end")
  994. env_line = self.get(search_position, '{}+{}c'.format(search_position, 200))
  995. print 'env_line 1 ', env_line
  996. if 0 <= env_line.find('\n'):
  997. env_line = env_line[ : env_line.find('\n')]
  998. env_end = env_line.find(' ', 18)
  999. if env_end == -1:
  1000. env_end = len(env_line)
  1001. env_line = env_line[ 18 : env_end ]
  1002. print 'env_line 2 ', env_line
  1003. env_found = False
  1004. for env in mem_check_environments:
  1005. if env_line == env:
  1006. env_found = True
  1007. print 'env ', env
  1008. search_position = self.search("Build type:", "1.0", stopindex="end")
  1009. if search_position == "":
  1010. print "didn't find it"
  1011. return
  1012. build_line = self.get(search_position, '{}+{}c'.format(search_position, 200))
  1013. print 'build_line 1 ', build_line
  1014. if 0 <= build_line.find('\n'):
  1015. build_line = build_line[ : build_line.find('\n')]
  1016. build_end = build_line.find(' ', 14)
  1017. if build_end == -1:
  1018. build_end = len(build_line)
  1019. build_line = build_line[ 12 : build_end ]
  1020. print 'build_line 2 ', build_line
  1021. build_found = False
  1022. for build in mem_check_builds:
  1023. if build_line == build:
  1024. build_found = True
  1025. print 'build ', build
  1026. if env_found and build_found: # find the memory values
  1027. search_position = self.search("Checking program size", "1.0", stopindex="end")
  1028. if search_position != '':
  1029. print 'search_position: ' + search_position
  1030. line_int = int(search_position[ : search_position.find(".")]) + 1
  1031. line_str = str(line_int)
  1032. line = self.get(line_str + '.0', line_str + '.200')
  1033. print 'line: ', line
  1034. while 'text' != line[ : 4 ] :
  1035. line_int = line_int + 1
  1036. line_str = str(line_int)
  1037. line = self.get(line_str + '.0', line_str + '.200')
  1038. print 'line: ', line
  1039. line_int = line_int + 1
  1040. line_str = str(line_int)
  1041. print 'line + 3: ' + line_str + '.0'
  1042. size_line = self.get(line_str + '.0', line_str + '.200')
  1043. print 'size_line ', size_line
  1044. data_start = 0
  1045. while ' ' == size_line[ data_start : data_start + 1] :
  1046. data_start = data_start + 1 # eat leading blanks
  1047. print 'data_start: ', data_start, size_line.find(' ', data_start)
  1048. data_end = size_line.find(' ', data_start) - 1
  1049. text_str = size_line[ data_start : data_end]
  1050. print 'text_str = ', data_start, data_end, text_str + '/////'
  1051. text_val = int(text_str)
  1052. print 'text_val ', text_val
  1053. data_start = size_line.find(' ', data_end)
  1054. while ' ' == size_line[ data_start : data_start + 1] :
  1055. data_start = data_start + 1 # eat leading blanks
  1056. print 'data_start: ', data_start, size_line.find(' ', data_start)
  1057. data_end = size_line.find(' ', data_start) -1
  1058. data_val = int(size_line[ data_start : data_end])
  1059. print 'data_val ', data_val
  1060. data_start = size_line.find(' ', data_end)
  1061. while ' ' == size_line[ data_start : data_start + 1] :
  1062. data_start = data_start + 1 # eat leading blanks
  1063. print 'data_start: ', data_start, size_line.find(' ', data_start)
  1064. data_end = size_line.find(' ', data_start) - 1
  1065. if data_end == -1:
  1066. data_end = len(size_line)
  1067. bss_val = int(size_line[ data_start : data_end])
  1068. print 'bss_val ', bss_val
  1069. FLASH_total = text_val + data_val
  1070. RAM_total = bss_val + data_val
  1071. tag = 'normal'
  1072. if FLASH_total >= FLASH_MAX * FLASH_PERCENT_WARN:
  1073. tag = 'warning'
  1074. if FLASH_total >= FLASH_MAX:
  1075. tag = 'error'
  1076. line_int = line_int + 1
  1077. line_str = str(line_int)
  1078. self.insert('end', '\nProgram: ' + str(FLASH_total) + ' bytes (' + str( 100*FLASH_total/FLASH_MAX) + '% of application area)\n', tag)
  1079. self.insert(line_str + '.0', '\nProgram: ' + str(FLASH_total) + ' bytes (' + str( 100*FLASH_total/FLASH_MAX) + '% of application area)\n', tag)
  1080. tag = 'normal'
  1081. if RAM_total >= RAM_MAX - RAM_WARN:
  1082. tag = 'warning'
  1083. if RAM_total >= RAM_MAX - RAM_SYSTEM:
  1084. tag = 'error'
  1085. line_int = line_int + 2
  1086. line_str = str(line_int)
  1087. self.insert('end', 'Data: ' + str(RAM_total) + ' bytes (' + str( 100*RAM_total/(RAM_MAX-RAM_SYSTEM)) + '% of non-system RAM)\n', tag)
  1088. self.insert(line_str + '.0', 'Data: ' + str(RAM_total) + ' bytes (' + str( 100*RAM_total/(RAM_MAX-RAM_SYSTEM)) + '% of non-system RAM)\n\n', tag)
  1089. self.see("end") # make the new lines visible (scroll text off the top)
  1090. # end - memory_check
  1091. #
  1092. # error reporting proceedure for copy_boards_dir()
  1093. #
  1094. def report_failure(self, PIO_path, board_path):
  1095. # didn't find the file - user needs to copy it & re-run the script
  1096. self.insert('end', 'Unable to move board definition file to destination. User must manually copy the file.\n\n', 'error')
  1097. self.insert('end', 'Please copy the following file and re-run the script:\n', 'normal')
  1098. self.insert('end', ' FROM:\n')
  1099. self.insert('end', ' ' + pwd + '/' + board_path + '/at90usb1286.json\n')
  1100. self.insert('end', ' TO:\n')
  1101. self.insert('end', ' ' + PIO_path + '/at90usb1286.json\n')
  1102. #
  1103. # move custom board definitions from project folder to PlatformIO
  1104. # returns True if the file ends up in the correct location
  1105. #
  1106. def copy_boards_dir(self):
  1107. temp = os.environ
  1108. for key in temp:
  1109. if 0 <= os.environ[key].find('.platformio'):
  1110. part = os.environ[key].split(';')
  1111. for part2 in part:
  1112. if 0 <= part2.find('.platformio'):
  1113. path = part2
  1114. break
  1115. path = path.replace("\\", "/")
  1116. path = path.replace("//", "/")
  1117. path_remaining = path
  1118. still_looking = True
  1119. PIO_path = ''
  1120. while still_looking:
  1121. colon_pos = path_remaining.find(':')
  1122. if -1 == colon_pos:
  1123. still_looking = False
  1124. path_maybe = path_remaining
  1125. else:
  1126. path_maybe = path_remaining[ : colon_pos]
  1127. path_remaining = path_remaining[ colon_pos + 1 : ]
  1128. if 0 <= path_maybe.find('/.platformio'):
  1129. still_looking = False
  1130. PIO_path = path_maybe
  1131. start_loc = PIO_path.find('/.platformio')
  1132. next_loc = PIO_path.find('/', start_loc + 5)
  1133. if 0 <= next_loc:
  1134. PIO_path = PIO_path[ : next_loc]
  1135. PIO_path = PIO_path + '/boards'
  1136. board_path = 'buildroot/share/PlatformIO/boards'
  1137. from distutils.dir_util import copy_tree
  1138. try:
  1139. copy_tree(board_path, PIO_path)
  1140. except:
  1141. pass
  1142. # check to see if it's there
  1143. # macOS will throw an exception if it can't get to the directory
  1144. # Ubuntu doesn't complain if it can't get to the directory
  1145. # Windows always succeeds (have not been able to lock it out in testing)
  1146. short_path = PIO_path[ : PIO_path.find('/boards')]
  1147. try:
  1148. PIO_dir = os.listdir(short_path)
  1149. except:
  1150. self.report_failure(PIO_path, board_path)
  1151. return False
  1152. if 'boards' in PIO_dir:
  1153. try:
  1154. boards_dir = os.listdir(PIO_path)
  1155. except:
  1156. self.report_failure(PIO_path, board_path)
  1157. return False
  1158. if 'at90usb1286.json' in boards_dir:
  1159. return True # it's there so all is well
  1160. self.report_failure(PIO_path, board_path)
  1161. return False
  1162. # end copy_boards_dir
  1163. # end - output_window
  1164. def main():
  1165. ##########################################################################
  1166. # #
  1167. # main program #
  1168. # #
  1169. ##########################################################################
  1170. global build_type
  1171. global target_env
  1172. global board_name
  1173. board_name, Marlin_ver = get_board_name()
  1174. target_env = get_env(board_name, Marlin_ver)
  1175. os.environ["BUILD_TYPE"] = build_type # let sub processes know what is happening
  1176. os.environ["TARGET_ENV"] = target_env
  1177. os.environ["BOARD_NAME"] = board_name
  1178. auto_build = output_window()
  1179. continue_script = True
  1180. if 0 <= target_env.find('USB1286'):
  1181. continue_script = auto_build.copy_boards_dir() # copy custom boards over to PlatformIO if using custom board
  1182. if continue_script:
  1183. auto_build.start_thread() # executes the "run_PIO" function
  1184. auto_build.root.mainloop()
  1185. if __name__ == '__main__':
  1186. main()