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

auto_build.py 45KB

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