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

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