My Marlin configs for Fabrikator Mini and CTC i3 Pro B
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

auto_build.py 32KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935
  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. #########
  84. # Python 2 error messages:
  85. # Can't find a usable init.tcl in the following directories ...
  86. # error "invalid command name "tcl_findLibrary""
  87. #
  88. # Fix for the above errors on my Win10 system:
  89. # search all init.tcl files for the line "package require -exact Tcl" that has the highest 8.5.x number
  90. # copy it into the first directory listed in the error messages
  91. # set the environmental variables TCLLIBPATH and TCL_LIBRARY to the directory where you found the init.tcl file
  92. # reboot
  93. #########
  94. #globals
  95. target_env = ''
  96. board_name = ''
  97. ##########################################################################################
  98. #
  99. # popup to get input from user
  100. #
  101. ##########################################################################################
  102. def get_answer(board_name, cpu_label_txt, cpu_a_txt, cpu_b_txt):
  103. if python_ver == 2:
  104. import Tkinter as tk
  105. else:
  106. import tkinter as tk
  107. def CPU_exit_3(): # forward declare functions
  108. CPU_exit_3_()
  109. def CPU_exit_4():
  110. CPU_exit_4_()
  111. def kill_session():
  112. kill_session_()
  113. root_get_answer = tk.Tk()
  114. root_get_answer.chk_state_1 = 1 # declare variables used by TK and enable
  115. chk_state_1 = 0 # set initial state of check boxes
  116. global get_answer_val
  117. get_answer_val = 2 # return get_answer_val, set default to match chk_state_1 default
  118. l1 = tk.Label(text=board_name,
  119. fg = "light green",
  120. bg = "dark green",
  121. font = "Helvetica 12 bold").grid(row=1)
  122. l2 = tk.Label(text=cpu_label_txt,
  123. fg = "light green",
  124. bg = "dark green",
  125. font = "Helvetica 16 bold italic").grid(row=2)
  126. b4 = tk.Checkbutton(text=cpu_a_txt,
  127. fg = "black",
  128. font = "Times 20 bold ",
  129. variable=chk_state_1, onvalue=1, offvalue=0,
  130. command = CPU_exit_3).grid(row=3)
  131. b5 = tk.Checkbutton(text=cpu_b_txt,
  132. fg = "black",
  133. font = "Times 20 bold ",
  134. variable=chk_state_1, onvalue=0, offvalue=1,
  135. command = CPU_exit_4).grid(row=4) # use same variable but inverted so they will track
  136. b6 = tk.Button(text="CONFIRM",
  137. fg = "blue",
  138. font = "Times 20 bold ",
  139. command = root_get_answer.destroy).grid(row=5, pady=4)
  140. b7 = tk.Button(text="CANCEL",
  141. fg = "red",
  142. font = "Times 12 bold ",
  143. command = kill_session).grid(row=6, pady=4)
  144. def CPU_exit_3_():
  145. global get_answer_val
  146. get_answer_val = 1
  147. def CPU_exit_4_():
  148. global get_answer_val
  149. get_answer_val = 2
  150. def kill_session_():
  151. raise SystemExit(0) # kill everything
  152. root_get_answer.mainloop()
  153. # end - get answer
  154. def env_name_check(argument):
  155. name_check = {
  156. 'teensy35' : True,
  157. 'teensy20' : True,
  158. 'STM32F4' : True,
  159. 'STM32F1' : True,
  160. 'sanguino_atmega644p' : True,
  161. 'sanguino_atmega1284p' : True,
  162. 'rambo' : True,
  163. 'melzi_optiboot' : True,
  164. 'melzi' : True,
  165. 'megaatmega2560' : True,
  166. 'megaatmega1280' : True,
  167. 'malyanm200' : True,
  168. 'LPC1768' : True,
  169. 'DUE_debug' : True,
  170. 'DUE_USB' : True,
  171. 'DUE' : True
  172. }
  173. return name_check.get(argument, False)
  174. # gets the last build environment
  175. def get_build_last():
  176. env_last = ''
  177. DIR_PWD = os.listdir('.')
  178. if '.pioenvs' in DIR_PWD:
  179. date_last = 0.0
  180. DIR__pioenvs = os.listdir('.pioenvs')
  181. for name in DIR__pioenvs:
  182. if env_name_check(name):
  183. DIR_temp = os.listdir('.pioenvs/' + name)
  184. for names_temp in DIR_temp:
  185. if 0 == names_temp.find('firmware.'):
  186. date_temp = os.path.getmtime('.pioenvs/' + name + '/' + names_temp)
  187. if date_temp > date_last:
  188. date_last = date_temp
  189. env_last = name
  190. return env_last
  191. # gets the board being built from the Configuration.h file
  192. # returns: board name, major version of Marlin being used (1 or 2)
  193. def get_board_name():
  194. board_name = ''
  195. # get board name
  196. with open('Marlin/Configuration.h', 'r') as myfile:
  197. Configuration_h = myfile.read()
  198. Configuration_h = Configuration_h.split('\n')
  199. Marlin_ver = 0 # set version to invalid number
  200. for lines in Configuration_h:
  201. if 0 == lines.find('#define CONFIGURATION_H_VERSION 01'):
  202. Marlin_ver = 1
  203. if 0 == lines.find('#define CONFIGURATION_H_VERSION 02'):
  204. Marlin_ver = 2
  205. board = lines.find(' BOARD_') + 1
  206. motherboard = lines.find(' MOTHERBOARD ') + 1
  207. define = lines.find('#define ')
  208. comment = lines.find('//')
  209. if (comment == -1 or comment > board) and \
  210. board > motherboard and \
  211. motherboard > define and \
  212. define >= 0 :
  213. spaces = lines.find(' ', board) # find the end of the board substring
  214. if spaces == -1:
  215. board_name = lines[board : ]
  216. else:
  217. board_name = lines[board : spaces]
  218. break
  219. return board_name, Marlin_ver
  220. # extract first environment name it finds after the start position
  221. # returns: environment name and position to start the next search from
  222. def get_env_from_line(line, start_position):
  223. env = ''
  224. next_position = -1
  225. env_position = line.find('env:', start_position)
  226. if 0 < env_position:
  227. next_position = line.find(' ', env_position + 4)
  228. if 0 < next_position:
  229. env = line[env_position + 4 : next_position]
  230. else:
  231. env = line[env_position + 4 : ] # at the end of the line
  232. return env, next_position
  233. #scans pins.h for board name and returns the environment(s) it finds
  234. def get_starting_env(board_name_full, version):
  235. # get environment starting point
  236. if version == 1:
  237. path = 'Marlin/pins.h'
  238. if version == 2:
  239. path = 'Marlin/src/pins/pins.h'
  240. with open(path, 'r') as myfile:
  241. pins_h = myfile.read()
  242. board_name = board_name_full[ 6 : ] # only use the part after "BOARD_" since we're searching the pins.h file
  243. pins_h = pins_h.split('\n')
  244. environment = ''
  245. board_line = ''
  246. cpu_A = ''
  247. cpu_B = ''
  248. i = 0
  249. list_start_found = False
  250. for lines in pins_h:
  251. i = i + 1 # i is always one ahead of the index into pins_h
  252. if 0 < lines.find("Unknown MOTHERBOARD value set in Configuration.h"):
  253. break # no more
  254. if 0 < lines.find('1280'):
  255. list_start_found = True
  256. if list_start_found == False: # skip lines until find start of CPU list
  257. continue
  258. board = lines.find(board_name)
  259. comment_start = lines.find('// ')
  260. cpu_A_loc = comment_start
  261. cpu_B_loc = 0
  262. if board > 0: # need to look at the next line for environment info
  263. cpu_line = pins_h[i]
  264. comment_start = cpu_line.find('// ')
  265. env_A, next_position = get_env_from_line(cpu_line, comment_start) # get name of environment & start of search for next
  266. env_B, next_position = get_env_from_line(cpu_line, next_position) # get next environment, if it exists
  267. env_C, next_position = get_env_from_line(cpu_line, next_position) # get next environment, if it exists
  268. break
  269. return env_A, env_B, env_C
  270. # scans input string for CPUs that the users may need to select from
  271. # returns: CPU name
  272. def get_CPU_name(environment):
  273. CPU_list = ('1280', '2560','644', '1284', 'LPC1768', 'DUE')
  274. CPU_name = ''
  275. for CPU in CPU_list:
  276. if 0 < environment.find(CPU):
  277. return CPU
  278. # get environment to be used for the build
  279. # returns: environment
  280. def get_env(board_name, ver_Marlin):
  281. def no_environment():
  282. print 'ERROR - no environment for this board'
  283. print board_name
  284. raise SystemExit(0) # no environment so quit
  285. def invalid_board():
  286. print 'ERROR - invalid board'
  287. print board_name
  288. raise SystemExit(0) # quit if unable to find board
  289. CPU_question = ( ('1280', '2560', "1280 or 2560 CPU?"), ('644', '1284', "644 or 1284 CPU?") )
  290. if 0 < board_name.find('MELZI') :
  291. get_answer(board_name, "Which flavor of Melzi?", "Melzi (Optiboot bootloader)", "Melzi ")
  292. if 1 == get_answer_val:
  293. target_env = 'melzi_optiboot'
  294. else:
  295. target_env = 'melzi'
  296. else:
  297. env_A, env_B, env_C = get_starting_env(board_name, ver_Marlin)
  298. if env_A == '':
  299. no_environment()
  300. if env_B == '':
  301. return env_A # only one environment so finished
  302. CPU_A = get_CPU_name(env_A)
  303. CPU_B = get_CPU_name(env_B)
  304. for item in CPU_question:
  305. if CPU_A == item[0]:
  306. get_answer(board_name, item[2], item[0], item[1])
  307. if 2 == get_answer_val:
  308. target_env = env_B
  309. else:
  310. target_env = env_A
  311. return target_env
  312. if env_A == 'LPC1768':
  313. if build_type == 'traceback' or (build_type == 'clean' and get_build_last() == 'LPC1768_debug_and_upload'):
  314. target_env = 'LPC1768_debug_and_upload'
  315. else:
  316. target_env = 'LPC1768'
  317. elif env_A == 'DUE':
  318. target_env = 'DUE'
  319. if build_type == 'traceback' or (build_type == 'clean' and get_build_last() == 'DUE_debug'):
  320. target_env = 'DUE_debug'
  321. elif env_B == 'DUE_USB':
  322. get_answer(board_name, "DUE: need download port", "USB (native USB) port", "Programming port ")
  323. if 1 == get_answer_val:
  324. target_env = 'DUE_USB'
  325. else:
  326. target_env = 'DUE'
  327. else:
  328. invalid_board()
  329. if build_type == 'traceback' and not(target_env == 'LPC1768_debug_and_upload' or target_env == 'DUE_debug') and Marlin_ver == 2:
  330. print "ERROR - this board isn't setup for traceback"
  331. print 'board_name: ', board_name
  332. print 'target_env: ', target_env
  333. raise SystemExit(0)
  334. return target_env
  335. # end - get_env
  336. # puts screen text into queue so that the parent thread can fetch the data from this thread
  337. import Queue
  338. IO_queue = Queue.Queue()
  339. def write_to_screen_queue(text, format_tag = 'normal'):
  340. double_in = [text, format_tag]
  341. IO_queue.put(double_in, block = False)
  342. #
  343. # send one line to the terminal screen with syntax highlighting
  344. #
  345. # input: unformatted text, flags from previous run
  346. # returns: formatted text ready to go to the terminal, flags from this run
  347. #
  348. # This routine remembers the status from call to call because previous
  349. # lines can affect how the current line is highlighted
  350. #
  351. # 'static' variables - init here and then keep updating them from within print_line
  352. warning = False
  353. warning_FROM = False
  354. error = False
  355. standard = True
  356. prev_line_COM = False
  357. next_line_warning = False
  358. warning_continue = False
  359. def line_print(line_input):
  360. global warning
  361. global warning_FROM
  362. global error
  363. global standard
  364. global prev_line_COM
  365. global next_line_warning
  366. global warning_continue
  367. # all '0' elements must precede all '1' elements or they'll be skipped
  368. platformio_highlights = [
  369. ['Environment', 0, 'highlight_blue'],
  370. ['[SKIP]', 1, 'warning'],
  371. ['[ERROR]', 1, 'error'],
  372. ['[SUCCESS]', 1, 'highlight_green']
  373. ]
  374. def write_to_screen_with_replace(text, highlights): # search for highlights & split line accordingly
  375. did_something = False
  376. for highlight in highlights:
  377. found = text.find(highlight[0])
  378. if did_something == True:
  379. break
  380. if found >= 0 :
  381. did_something = True
  382. if 0 == highlight[1]:
  383. found_1 = text.find(' ')
  384. found_tab = text.find('\t')
  385. if found_1 < 0 or found_1 > found_tab:
  386. found_1 = found_tab
  387. write_to_screen_queue(text[ : found_1 + 1 ])
  388. for highlight_2 in highlights:
  389. if highlight[0] == highlight_2[0] :
  390. continue
  391. found = text.find(highlight_2[0])
  392. if found >= 0 :
  393. found_space = text.find(' ', found_1 + 1)
  394. found_tab = text.find('\t', found_1 + 1)
  395. if found_space < 0 or found_space > found_tab:
  396. found_space = found_tab
  397. found_right = text.find(']', found + 1)
  398. write_to_screen_queue(text[found_1 + 1 : found_space + 1 ], highlight[2])
  399. write_to_screen_queue(text[found_space + 1 : found + 1 ])
  400. write_to_screen_queue(text[found + 1 : found_right], highlight_2[2])
  401. write_to_screen_queue(text[found_right : ] + '\n')
  402. break
  403. break
  404. if 1 == highlight[1]:
  405. found_right = text.find(']', found + 1)
  406. write_to_screen_queue(text[ : found + 1 ])
  407. write_to_screen_queue(text[found + 1 : found_right ], highlight[2])
  408. write_to_screen_queue(text[found_right : ] + '\n')
  409. break
  410. if did_something == False:
  411. write_to_screen_queue(text + '\n')
  412. # end - write_to_screen_with_replace
  413. # scan the line
  414. max_search = len(line_input)
  415. if max_search > 3 :
  416. max_search = 3
  417. beginning = line_input[:max_search]
  418. # set flags
  419. if 0 < line_input.find(': warning: '): # start of warning block
  420. warning = True
  421. warning_FROM = False
  422. error = False
  423. standard = False
  424. prev_line_COM = False
  425. prev_line_COM = False
  426. warning_continue = True
  427. if beginning == 'War' or \
  428. beginning == '#er' or \
  429. beginning == 'In ' or \
  430. (beginning != 'Com' and prev_line_COM == True and not(beginning == 'Arc' or beginning == 'Lin' or beginning == 'Ind') or \
  431. next_line_warning == True):
  432. warning = True #warning found
  433. warning_FROM = False
  434. error = False
  435. standard = False
  436. prev_line_COM = False
  437. elif beginning == 'Com' or \
  438. beginning == 'Ver' or \
  439. beginning == ' [E' or \
  440. beginning == 'Rem' or \
  441. beginning == 'Bui' or \
  442. beginning == 'Ind' or \
  443. beginning == 'PLA':
  444. warning = False #standard line found
  445. warning_FROM = False
  446. error = False
  447. standard = True
  448. prev_line_COM = False
  449. warning_continue = False
  450. elif beginning == '***':
  451. warning = False # error found
  452. warning_FROM = False
  453. error = True
  454. standard = False
  455. prev_line_COM = False
  456. elif beginning == 'fro' and warning == True : # start of warning /error block
  457. warning_FROM = True
  458. prev_line_COM = False
  459. warning_continue = True
  460. elif 0 < line_input.find(': error:') or \
  461. 0 < line_input.find(': fatal error:'): # start of warning /error block
  462. warning = False # error found
  463. warning_FROM = False
  464. error = True
  465. standard = False
  466. prev_line_COM = False
  467. warning_continue = True
  468. elif warning_continue == True:
  469. warning = True
  470. warning_FROM = False # keep the warning status going until find a standard line
  471. error = False
  472. standard = False
  473. prev_line_COM = False
  474. warning_continue = True
  475. else:
  476. warning = False # unknown so assume standard line
  477. warning_FROM = False
  478. error = False
  479. standard = True
  480. prev_line_COM = False
  481. warning_continue = False
  482. if beginning == 'Com':
  483. prev_line_COM = True
  484. # print based on flags
  485. if standard == True:
  486. write_to_screen_with_replace(line_input, platformio_highlights) #print white on black with substitutions
  487. if warning == True:
  488. write_to_screen_queue(line_input + '\n', 'warning')
  489. if error == True:
  490. write_to_screen_queue(line_input + '\n', 'error')
  491. # end - line_print
  492. def run_PIO(dummy):
  493. ##########################################################################
  494. # #
  495. # run Platformio #
  496. # #
  497. ##########################################################################
  498. # build platformio run -e target_env
  499. # clean platformio run --target clean -e target_env
  500. # upload platformio run --target upload -e target_env
  501. # traceback platformio run --target upload -e target_env
  502. # program platformio run --target program -e target_env
  503. # test platformio test upload -e target_env
  504. # remote platformio remote run --target upload -e target_env
  505. # debug platformio debug -e target_env
  506. global build_type
  507. global target_env
  508. global board_name
  509. print 'build_type: ', build_type
  510. import subprocess
  511. import sys
  512. print 'starting platformio'
  513. if build_type == 'build':
  514. # platformio run -e target_env
  515. # combine stdout & stderr so all compile messages are included
  516. pio_subprocess = subprocess.Popen(['platformio', 'run', '-e', target_env], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  517. elif build_type == 'clean':
  518. # platformio run --target clean -e target_env
  519. # combine stdout & stderr so all compile messages are included
  520. pio_subprocess = subprocess.Popen(['platformio', 'run', '--target', 'clean', '-e', target_env], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  521. elif build_type == 'upload':
  522. # platformio run --target upload -e target_env
  523. # combine stdout & stderr so all compile messages are included
  524. pio_subprocess = subprocess.Popen(['platformio', 'run', '--target', 'upload', '-e', target_env], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  525. elif build_type == 'traceback':
  526. # platformio run --target upload -e target_env - select the debug environment if there is one
  527. # combine stdout & stderr so all compile messages are included
  528. pio_subprocess = subprocess.Popen(['platformio', 'run', '--target', 'upload', '-e', target_env], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  529. elif build_type == 'program':
  530. # platformio run --target program -e target_env
  531. # combine stdout & stderr so all compile messages are included
  532. pio_subprocess = subprocess.Popen(['platformio', 'run', '--target', 'program', '-e', target_env], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  533. elif build_type == 'test':
  534. #platformio test upload -e target_env
  535. # combine stdout & stderr so all compile messages are included
  536. pio_subprocess = subprocess.Popen(['platformio', 'test', 'upload', '-e', target_env], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  537. elif build_type == 'remote':
  538. # platformio remote run --target upload -e target_env
  539. # combine stdout & stderr so all compile messages are included
  540. pio_subprocess = subprocess.Popen(['platformio', 'remote', 'run', '--target', 'program', '-e', target_env], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  541. elif build_type == 'debug':
  542. # platformio debug -e target_env
  543. # combine stdout & stderr so all compile messages are included
  544. pio_subprocess = subprocess.Popen(['platformio', 'debug', '-e', target_env], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  545. else:
  546. print 'ERROR - unknown build type: ', build_type
  547. raise SystemExit(0) # kill everything
  548. # stream output from subprocess and split it into lines
  549. for line in iter(pio_subprocess.stdout.readline, ''):
  550. line_print(line.replace('\n', ''))
  551. # append info used to run PlatformIO
  552. write_to_screen_queue('\nBoard name: ' + board_name + '\n') # put build info at the bottom of the screen
  553. write_to_screen_queue('Build type: ' + build_type + '\n')
  554. write_to_screen_queue('Environment used: ' + target_env + '\n')
  555. # end - run_PIO
  556. ########################################################################
  557. import time
  558. import threading
  559. import Tkinter as tk
  560. import ttk
  561. import Queue
  562. import subprocess
  563. import sys
  564. que = Queue.Queue()
  565. #IO_queue = Queue.Queue()
  566. from Tkinter import Tk, Frame, Text, Scrollbar, Menu
  567. from tkMessageBox import askokcancel
  568. import tkFileDialog
  569. from tkMessageBox import askokcancel
  570. import tkFileDialog
  571. class output_window(Text):
  572. global continue_updates
  573. continue_updates = True
  574. def __init__(self):
  575. self.root = tk.Tk()
  576. self.frame = tk.Frame(self.root)
  577. self.frame.pack(fill='both', expand=True)
  578. # text widget
  579. #self.text = tk.Text(self.frame, borderwidth=3, relief="sunken")
  580. Text.__init__(self, self.frame, borderwidth=3, relief="sunken")
  581. self.config(tabs=(400,)) # configure Text widget tab stops
  582. self.config(background = 'black', foreground = 'white', font= ("consolas", 12), wrap = 'word', undo = 'True')
  583. self.config(height = 24, width = 120)
  584. self.pack(side='left', fill='both', expand=True)
  585. self.tag_config('normal', foreground = 'white')
  586. self.tag_config('warning', foreground = 'yellow' )
  587. self.tag_config('error', foreground = 'red')
  588. self.tag_config('highlight_green', foreground = 'green')
  589. self.tag_config('highlight_blue', foreground = 'cyan')
  590. # self.bind('<Control-Key-a>', self.select_all) # the event happens but the action doesn't
  591. # scrollbar
  592. scrb = tk.Scrollbar(self.frame, orient='vertical', command=self.yview)
  593. self.config(yscrollcommand=scrb.set)
  594. scrb.pack(side='right', fill='y')
  595. # pop-up menu
  596. self.popup = tk.Menu(self, tearoff=0)
  597. self.popup.add_command(label='Cut', command=self._cut)
  598. self.popup.add_command(label='Copy', command=self._copy)
  599. self.popup.add_command(label='Paste', command=self._paste)
  600. self.popup.add_separator()
  601. self.popup.add_command(label='Select All', command=self._select_all)
  602. self.popup.add_command(label='Clear All', command=self._clear_all)
  603. self.popup.add_separator()
  604. self.popup.add_command(label='Save As', command=self._file_save_as)
  605. self.bind('<Button-3>', self._show_popup)
  606. # threading & subprocess section
  607. def start_thread(self, ):
  608. global continue_updates
  609. # create then start a secondary thread to run an arbitrary function
  610. # must have at least one argument
  611. self.secondary_thread = threading.Thread(target = lambda q, arg1: q.put(run_PIO(arg1)), args=(que, ''))
  612. self.secondary_thread.start()
  613. continue_updates = True
  614. # check the Queue in 50ms
  615. self.root.after(50, self.check_thread)
  616. self.root.after(50, self.update)
  617. def check_thread(self): # wait for user to kill the window
  618. global continue_updates
  619. if continue_updates == True:
  620. self.root.after(20, self.check_thread)
  621. def update(self):
  622. global continue_updates
  623. if continue_updates == True:
  624. self.root.after(20, self.update)#method is called every 50ms
  625. temp_text = ['0','0']
  626. if IO_queue.empty():
  627. if not(self.secondary_thread.is_alive()):
  628. continue_updates = False # queue is exhausted and thread is dead so no need for further updates
  629. self.tag_add('sel', '1.0', 'end')
  630. else:
  631. try:
  632. temp_text = IO_queue.get(block = False)
  633. except Queue.Empty:
  634. continue_updates = False # queue is exhausted so no need for further updates
  635. else:
  636. self.insert('end', temp_text[0], temp_text[1])
  637. self.see("end") # make the last line visible (scroll text off the top)
  638. # text editing section
  639. def _file_save_as(self):
  640. self.filename = tkFileDialog.asksaveasfilename(defaultextension = '.txt')
  641. f = open(self.filename, 'w')
  642. f.write(self.get('1.0', 'end'))
  643. f.close()
  644. def copy(self, event):
  645. try:
  646. selection = self.get(*self.tag_ranges('sel'))
  647. self.clipboard_clear()
  648. self.clipboard_append(selection)
  649. except TypeError:
  650. pass
  651. def cut(self, event):
  652. try:
  653. selection = self.get(*self.tag_ranges('sel'))
  654. self.clipboard_clear()
  655. self.clipboard_append(selection)
  656. self.delete(*self.tag_ranges('sel'))
  657. except TypeError:
  658. pass
  659. def _show_popup(self, event):
  660. '''right-click popup menu'''
  661. if self.root.focus_get() != self:
  662. self.root.focus_set()
  663. try:
  664. self.popup.tk_popup(event.x_root, event.y_root, 0)
  665. finally:
  666. self.popup.grab_release()
  667. def _cut(self):
  668. try:
  669. selection = self.get(*self.tag_ranges('sel'))
  670. self.clipboard_clear()
  671. self.clipboard_append(selection)
  672. self.delete(*self.tag_ranges('sel'))
  673. except TypeError:
  674. pass
  675. def cut(self, event):
  676. _cut(self)
  677. def _copy(self):
  678. try:
  679. selection = self.get(*self.tag_ranges('sel'))
  680. self.clipboard_clear()
  681. self.clipboard_append(selection)
  682. except TypeError:
  683. pass
  684. def copy(self, event):
  685. _copy(self)
  686. def _paste(self):
  687. self.insert('insert', self.selection_get(selection='CLIPBOARD'))
  688. def _select_all(self):
  689. self.tag_add('sel', '1.0', 'end')
  690. def select_all(self, event):
  691. self.tag_add('sel', '1.0', 'end')
  692. def _clear_all(self):
  693. '''erases all text'''
  694. isok = askokcancel('Clear All', 'Erase all text?', frame=self,
  695. default='ok')
  696. if isok:
  697. self.delete('1.0', 'end')
  698. def _place_cursor(self): # theme: terminal
  699. '''check the position of the cursor against the last known position
  700. every 15ms and update the cursorblock tag as needed'''
  701. current_index = self.index('insert')
  702. if self.cursor != current_index:
  703. self.cursor = current_index
  704. self.tag_delete('cursorblock')
  705. start = self.index('insert')
  706. end = self.index('insert+1c')
  707. if start[0] != end[0]:
  708. self.insert(start, ' ')
  709. end = self.index('insert')
  710. self.tag_add('cursorblock', start, end)
  711. self.mark_set('insert', self.cursor)
  712. self.after(15, self._place_cursor)
  713. def _blink_cursor(self): # theme: terminal
  714. '''alternate the background color of the cursorblock tagged text
  715. every 600 milliseconds'''
  716. if self.switch == self.fg:
  717. self.switch = self.bg
  718. else:
  719. self.switch = self.fg
  720. self.tag_config('cursorblock', background=self.switch)
  721. self.after(600, self._blink_cursor)
  722. # end - output_window
  723. def main():
  724. ##########################################################################
  725. # #
  726. # main program #
  727. # #
  728. ##########################################################################
  729. global build_type
  730. global target_env
  731. global board_name
  732. board_name, Marlin_ver = get_board_name()
  733. target_env = get_env(board_name, Marlin_ver)
  734. auto_build = output_window()
  735. auto_build.start_thread() # executes the "run_PIO" function
  736. auto_build.root.mainloop()
  737. if __name__ == '__main__':
  738. main()