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 43KB

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