My Marlin configs for Fabrikator Mini and CTC i3 Pro B
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

auto_build.py 45KB

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