My Marlin configs for Fabrikator Mini and CTC i3 Pro B
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

auto_build.py 45KB

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