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

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