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

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