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 46KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280
  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. #
  332. # move custom board definitions from project folder to PlatformIO
  333. #
  334. def copy_boards_dir():
  335. temp = os.environ
  336. for key in temp:
  337. if 0 <= os.environ[key].find('.platformio'):
  338. part = os.environ[key].split(';')
  339. for part2 in part:
  340. if 0 <= part2.find('.platformio'):
  341. path = part2
  342. break
  343. PIO_path = path[ : path.find('.platformio') + 11]
  344. # import sys
  345. # import subprocess
  346. # pio_subprocess = subprocess.Popen(['platformio', 'run', '-t', 'envdump'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  347. #
  348. # # stream output from subprocess and split it into lines
  349. # for line in iter(pio_subprocess.stdout.readline, ''):
  350. # if 0 <= line.find('PIOHOME_DIR'):
  351. # start = line.find(':') + 3
  352. # end = line.find(',') - 1
  353. # PIO_path = line[start:end]
  354. PIO_path = PIO_path.replace("\\", "/")
  355. PIO_path = PIO_path.replace("//", "/") + '/boards'
  356. board_path = 'buildroot/share/PlatformIO/boards'
  357. from distutils.dir_util import copy_tree
  358. copy_tree(board_path, PIO_path)
  359. # end copy_boards_dir
  360. # gets the last build environment
  361. def get_build_last():
  362. env_last = ''
  363. DIR_PWD = os.listdir('.')
  364. if '.pioenvs' in DIR_PWD:
  365. date_last = 0.0
  366. DIR__pioenvs = os.listdir('.pioenvs')
  367. for name in DIR__pioenvs:
  368. if 0 <= name.find('.') or 0 <= name.find('-'): # skip files in listing
  369. continue
  370. DIR_temp = os.listdir('.pioenvs/' + name)
  371. for names_temp in DIR_temp:
  372. if 0 == names_temp.find('firmware.'):
  373. date_temp = os.path.getmtime('.pioenvs/' + name + '/' + names_temp)
  374. if date_temp > date_last:
  375. date_last = date_temp
  376. env_last = name
  377. return env_last
  378. # gets the board being built from the Configuration.h file
  379. # returns: board name, major version of Marlin being used (1 or 2)
  380. def get_board_name():
  381. board_name = ''
  382. # get board name
  383. with open('Marlin/Configuration.h', 'r') as myfile:
  384. Configuration_h = myfile.read()
  385. Configuration_h = Configuration_h.split('\n')
  386. Marlin_ver = 0 # set version to invalid number
  387. for lines in Configuration_h:
  388. if 0 == lines.find('#define CONFIGURATION_H_VERSION 01'):
  389. Marlin_ver = 1
  390. if 0 == lines.find('#define CONFIGURATION_H_VERSION 02'):
  391. Marlin_ver = 2
  392. board = lines.find(' BOARD_') + 1
  393. motherboard = lines.find(' MOTHERBOARD ') + 1
  394. define = lines.find('#define ')
  395. comment = lines.find('//')
  396. if (comment == -1 or comment > board) and \
  397. board > motherboard and \
  398. motherboard > define and \
  399. define >= 0 :
  400. spaces = lines.find(' ', board) # find the end of the board substring
  401. if spaces == -1:
  402. board_name = lines[board : ]
  403. else:
  404. board_name = lines[board : spaces]
  405. break
  406. return board_name, Marlin_ver
  407. # extract first environment name it finds after the start position
  408. # returns: environment name and position to start the next search from
  409. def get_env_from_line(line, start_position):
  410. env = ''
  411. next_position = -1
  412. env_position = line.find('env:', start_position)
  413. if 0 < env_position:
  414. next_position = line.find(' ', env_position + 4)
  415. if 0 < next_position:
  416. env = line[env_position + 4 : next_position]
  417. else:
  418. env = line[env_position + 4 : ] # at the end of the line
  419. return env, next_position
  420. #scans pins.h for board name and returns the environment(s) it finds
  421. def get_starting_env(board_name_full, version):
  422. # get environment starting point
  423. if version == 1:
  424. path = 'Marlin/pins.h'
  425. if version == 2:
  426. path = 'Marlin/src/pins/pins.h'
  427. with open(path, 'r') as myfile:
  428. pins_h = myfile.read()
  429. env_A = ''
  430. env_B = ''
  431. env_C = ''
  432. board_name = board_name_full[ 6 : ] # only use the part after "BOARD_" since we're searching the pins.h file
  433. pins_h = pins_h.split('\n')
  434. environment = ''
  435. board_line = ''
  436. cpu_A = ''
  437. cpu_B = ''
  438. i = 0
  439. list_start_found = False
  440. for lines in pins_h:
  441. i = i + 1 # i is always one ahead of the index into pins_h
  442. if 0 < lines.find("Unknown MOTHERBOARD value set in Configuration.h"):
  443. break # no more
  444. if 0 < lines.find('1280'):
  445. list_start_found = True
  446. if list_start_found == False: # skip lines until find start of CPU list
  447. continue
  448. board = lines.find(board_name)
  449. comment_start = lines.find('// ')
  450. cpu_A_loc = comment_start
  451. cpu_B_loc = 0
  452. if board > 0: # need to look at the next line for environment info
  453. cpu_line = pins_h[i]
  454. comment_start = cpu_line.find('// ')
  455. env_A, next_position = get_env_from_line(cpu_line, comment_start) # get name of environment & start of search for next
  456. env_B, next_position = get_env_from_line(cpu_line, next_position) # get next environment, if it exists
  457. env_C, next_position = get_env_from_line(cpu_line, next_position) # get next environment, if it exists
  458. break
  459. return env_A, env_B, env_C
  460. # scans input string for CPUs that the users may need to select from
  461. # returns: CPU name
  462. def get_CPU_name(environment):
  463. CPU_list = ('1280', '2560','644', '1284', 'LPC1768', 'DUE')
  464. CPU_name = ''
  465. for CPU in CPU_list:
  466. if 0 < environment.find(CPU):
  467. return CPU
  468. # get environment to be used for the build
  469. # returns: environment
  470. def get_env(board_name, ver_Marlin):
  471. def no_environment():
  472. print 'ERROR - no environment for this board'
  473. print board_name
  474. raise SystemExit(0) # no environment so quit
  475. def invalid_board():
  476. print 'ERROR - invalid board'
  477. print board_name
  478. raise SystemExit(0) # quit if unable to find board
  479. CPU_question = ( ('1280', '2560', " 1280 or 2560 CPU? "), ('644', '1284', " 644 or 1284 CPU? ") )
  480. if 0 < board_name.find('MELZI') :
  481. get_answer(' ' + board_name + ' ', " Which flavor of Melzi? ", "Melzi (Optiboot bootloader)", "Melzi ")
  482. if 1 == get_answer_val:
  483. target_env = 'melzi_optiboot'
  484. else:
  485. target_env = 'melzi'
  486. else:
  487. env_A, env_B, env_C = get_starting_env(board_name, ver_Marlin)
  488. if env_A == '':
  489. no_environment()
  490. if env_B == '':
  491. return env_A # only one environment so finished
  492. CPU_A = get_CPU_name(env_A)
  493. CPU_B = get_CPU_name(env_B)
  494. for item in CPU_question:
  495. if CPU_A == item[0]:
  496. get_answer(' ' + board_name + ' ', item[2], item[0], item[1])
  497. if 2 == get_answer_val:
  498. target_env = env_B
  499. else:
  500. target_env = env_A
  501. return target_env
  502. if env_A == 'LPC1768':
  503. if build_type == 'traceback' or (build_type == 'clean' and get_build_last() == 'LPC1768_debug_and_upload'):
  504. target_env = 'LPC1768_debug_and_upload'
  505. else:
  506. target_env = 'LPC1768'
  507. elif env_A == 'DUE':
  508. target_env = 'DUE'
  509. if build_type == 'traceback' or (build_type == 'clean' and get_build_last() == 'DUE_debug'):
  510. target_env = 'DUE_debug'
  511. elif env_B == 'DUE_USB':
  512. get_answer(' ' + board_name + ' ', " DUE: need download port ", "USB (native USB) port", "Programming port ")
  513. if 1 == get_answer_val:
  514. target_env = 'DUE_USB'
  515. else:
  516. target_env = 'DUE'
  517. else:
  518. invalid_board()
  519. if build_type == 'traceback' and not(target_env == 'LPC1768_debug_and_upload' or target_env == 'DUE_debug') and Marlin_ver == 2:
  520. print "ERROR - this board isn't setup for traceback"
  521. print 'board_name: ', board_name
  522. print 'target_env: ', target_env
  523. raise SystemExit(0)
  524. return target_env
  525. # end - get_env
  526. # puts screen text into queue so that the parent thread can fetch the data from this thread
  527. import Queue
  528. IO_queue = Queue.Queue()
  529. PIO_queue = Queue.Queue()
  530. def write_to_screen_queue(text, format_tag = 'normal'):
  531. double_in = [text, format_tag]
  532. IO_queue.put(double_in, block = False)
  533. #
  534. # send one line to the terminal screen with syntax highlighting
  535. #
  536. # input: unformatted text, flags from previous run
  537. # returns: formatted text ready to go to the terminal, flags from this run
  538. #
  539. # This routine remembers the status from call to call because previous
  540. # lines can affect how the current line is highlighted
  541. #
  542. # 'static' variables - init here and then keep updating them from within print_line
  543. warning = False
  544. warning_FROM = False
  545. error = False
  546. standard = True
  547. prev_line_COM = False
  548. next_line_warning = False
  549. warning_continue = False
  550. line_counter = 0
  551. def line_print(line_input):
  552. global warning
  553. global warning_FROM
  554. global error
  555. global standard
  556. global prev_line_COM
  557. global next_line_warning
  558. global warning_continue
  559. global line_counter
  560. # all '0' elements must precede all '1' elements or they'll be skipped
  561. platformio_highlights = [
  562. ['Environment', 0, 'highlight_blue'],
  563. ['[SKIP]', 1, 'warning'],
  564. ['[ERROR]', 1, 'error'],
  565. ['[SUCCESS]', 1, 'highlight_green']
  566. ]
  567. def write_to_screen_with_replace(text, highlights): # search for highlights & split line accordingly
  568. did_something = False
  569. for highlight in highlights:
  570. found = text.find(highlight[0])
  571. if did_something == True:
  572. break
  573. if found >= 0 :
  574. did_something = True
  575. if 0 == highlight[1]:
  576. found_1 = text.find(' ')
  577. found_tab = text.find('\t')
  578. if found_1 < 0 or found_1 > found_tab:
  579. found_1 = found_tab
  580. write_to_screen_queue(text[ : found_1 + 1 ])
  581. for highlight_2 in highlights:
  582. if highlight[0] == highlight_2[0] :
  583. continue
  584. found = text.find(highlight_2[0])
  585. if found >= 0 :
  586. found_space = text.find(' ', found_1 + 1)
  587. found_tab = text.find('\t', found_1 + 1)
  588. if found_space < 0 or found_space > found_tab:
  589. found_space = found_tab
  590. found_right = text.find(']', found + 1)
  591. write_to_screen_queue(text[found_1 + 1 : found_space + 1 ], highlight[2])
  592. write_to_screen_queue(text[found_space + 1 : found + 1 ])
  593. write_to_screen_queue(text[found + 1 : found_right], highlight_2[2])
  594. write_to_screen_queue(text[found_right : ] + '\n')
  595. break
  596. break
  597. if 1 == highlight[1]:
  598. found_right = text.find(']', found + 1)
  599. write_to_screen_queue(text[ : found + 1 ])
  600. write_to_screen_queue(text[found + 1 : found_right ], highlight[2])
  601. write_to_screen_queue(text[found_right : ] + '\n')
  602. break
  603. if did_something == False:
  604. r_loc = text.find('\r') + 1
  605. if r_loc > 0 and r_loc < len(text): # need to split this line
  606. text = text.split('\r')
  607. for line in text:
  608. write_to_screen_queue(line + '\n')
  609. else:
  610. write_to_screen_queue(text + '\n')
  611. # end - write_to_screen_with_replace
  612. # scan the line
  613. line_counter = line_counter + 1
  614. max_search = len(line_input)
  615. if max_search > 3 :
  616. max_search = 3
  617. beginning = line_input[:max_search]
  618. # set flags
  619. if 0 < line_input.find(': warning: '): # start of warning block
  620. warning = True
  621. warning_FROM = False
  622. error = False
  623. standard = False
  624. prev_line_COM = False
  625. prev_line_COM = False
  626. warning_continue = True
  627. if 0 < line_input.find('Thank you') or 0 < line_input.find('SUMMARY') :
  628. warning = False #standard line found
  629. warning_FROM = False
  630. error = False
  631. standard = True
  632. prev_line_COM = False
  633. warning_continue = False
  634. elif beginning == 'War' or \
  635. beginning == '#er' or \
  636. beginning == 'In ' or \
  637. (beginning != 'Com' and prev_line_COM == True and not(beginning == 'Arc' or beginning == 'Lin' or beginning == 'Ind') or \
  638. next_line_warning == True):
  639. warning = True #warning found
  640. warning_FROM = False
  641. error = False
  642. standard = False
  643. prev_line_COM = False
  644. elif beginning == 'Com' or \
  645. beginning == 'Ver' or \
  646. beginning == ' [E' or \
  647. beginning == 'Rem' or \
  648. beginning == 'Bui' or \
  649. beginning == 'Ind' or \
  650. beginning == 'PLA':
  651. warning = False #standard line found
  652. warning_FROM = False
  653. error = False
  654. standard = True
  655. prev_line_COM = False
  656. warning_continue = False
  657. elif beginning == '***':
  658. warning = False # error found
  659. warning_FROM = False
  660. error = True
  661. standard = False
  662. prev_line_COM = False
  663. elif 0 < line_input.find(': error:') or \
  664. 0 < line_input.find(': fatal error:'): # start of warning /error block
  665. warning = False # error found
  666. warning_FROM = False
  667. error = True
  668. standard = False
  669. prev_line_COM = False
  670. warning_continue = True
  671. elif beginning == 'fro' and warning == True or \
  672. beginning == '.pi' : # start of warning /error block
  673. warning_FROM = True
  674. prev_line_COM = False
  675. warning_continue = True
  676. elif warning_continue == True:
  677. warning = True
  678. warning_FROM = False # keep the warning status going until find a standard line or an error
  679. error = False
  680. standard = False
  681. prev_line_COM = False
  682. warning_continue = True
  683. else:
  684. warning = False # unknown so assume standard line
  685. warning_FROM = False
  686. error = False
  687. standard = True
  688. prev_line_COM = False
  689. warning_continue = False
  690. if beginning == 'Com':
  691. prev_line_COM = True
  692. # print based on flags
  693. if standard == True:
  694. write_to_screen_with_replace(line_input, platformio_highlights) #print white on black with substitutions
  695. if warning == True:
  696. write_to_screen_queue(line_input + '\n', 'warning')
  697. if error == True:
  698. write_to_screen_queue(line_input + '\n', 'error')
  699. # end - line_print
  700. def run_PIO(dummy):
  701. ##########################################################################
  702. # #
  703. # run Platformio #
  704. # #
  705. ##########################################################################
  706. # build platformio run -e target_env
  707. # clean platformio run --target clean -e target_env
  708. # upload platformio run --target upload -e target_env
  709. # traceback platformio run --target upload -e target_env
  710. # program platformio run --target program -e target_env
  711. # test platformio test upload -e target_env
  712. # remote platformio remote run --target upload -e target_env
  713. # debug platformio debug -e target_env
  714. global build_type
  715. global target_env
  716. global board_name
  717. print 'build_type: ', build_type
  718. import subprocess
  719. import sys
  720. print 'starting platformio'
  721. if build_type == 'build':
  722. # platformio run -e target_env
  723. # combine stdout & stderr so all compile messages are included
  724. pio_subprocess = subprocess.Popen(['platformio', 'run', '-e', target_env], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  725. elif build_type == 'clean':
  726. # platformio run --target clean -e target_env
  727. # combine stdout & stderr so all compile messages are included
  728. pio_subprocess = subprocess.Popen(['platformio', 'run', '--target', 'clean', '-e', target_env], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  729. elif build_type == 'upload':
  730. # platformio run --target upload -e target_env
  731. # combine stdout & stderr so all compile messages are included
  732. pio_subprocess = subprocess.Popen(['platformio', 'run', '--target', 'upload', '-e', target_env], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  733. elif build_type == 'traceback':
  734. # platformio run --target upload -e target_env - select the debug environment if there is one
  735. # combine stdout & stderr so all compile messages are included
  736. pio_subprocess = subprocess.Popen(['platformio', 'run', '--target', 'upload', '-e', target_env], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  737. elif build_type == 'program':
  738. # platformio run --target program -e target_env
  739. # combine stdout & stderr so all compile messages are included
  740. pio_subprocess = subprocess.Popen(['platformio', 'run', '--target', 'program', '-e', target_env], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  741. elif build_type == 'test':
  742. #platformio test upload -e target_env
  743. # combine stdout & stderr so all compile messages are included
  744. pio_subprocess = subprocess.Popen(['platformio', 'test', 'upload', '-e', target_env], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  745. elif build_type == 'remote':
  746. # platformio remote run --target upload -e target_env
  747. # combine stdout & stderr so all compile messages are included
  748. pio_subprocess = subprocess.Popen(['platformio', 'remote', 'run', '--target', 'program', '-e', target_env], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  749. elif build_type == 'debug':
  750. # platformio debug -e target_env
  751. # combine stdout & stderr so all compile messages are included
  752. pio_subprocess = subprocess.Popen(['platformio', 'debug', '-e', target_env], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  753. else:
  754. print 'ERROR - unknown build type: ', build_type
  755. raise SystemExit(0) # kill everything
  756. # stream output from subprocess and split it into lines
  757. for line in iter(pio_subprocess.stdout.readline, ''):
  758. line_print(line.replace('\n', ''))
  759. # append info used to run PlatformIO
  760. write_to_screen_queue('\nBoard name: ' + board_name + '\n') # put build info at the bottom of the screen
  761. write_to_screen_queue('Build type: ' + build_type + '\n')
  762. write_to_screen_queue('Environment used: ' + target_env + '\n')
  763. # end - run_PIO
  764. ########################################################################
  765. import time
  766. import threading
  767. import Tkinter as tk
  768. import ttk
  769. import Queue
  770. import subprocess
  771. import sys
  772. que = Queue.Queue()
  773. #IO_queue = Queue.Queue()
  774. from Tkinter import Tk, Frame, Text, Scrollbar, Menu
  775. from tkMessageBox import askokcancel
  776. import tkFileDialog
  777. from tkMessageBox import askokcancel
  778. import tkFileDialog
  779. class output_window(Text):
  780. # based on Super Text
  781. global continue_updates
  782. continue_updates = True
  783. global search_position
  784. search_position = '' # start with invalid search position
  785. global error_found
  786. error_found = False # are there any errors?
  787. def __init__(self):
  788. self.root = tk.Tk()
  789. self.frame = tk.Frame(self.root)
  790. self.frame.pack(fill='both', expand=True)
  791. # text widget
  792. #self.text = tk.Text(self.frame, borderwidth=3, relief="sunken")
  793. Text.__init__(self, self.frame, borderwidth=3, relief="sunken")
  794. self.config(tabs=(400,)) # configure Text widget tab stops
  795. self.config(background = 'black', foreground = 'white', font= ("consolas", 12), wrap = 'word', undo = 'True')
  796. # self.config(background = 'black', foreground = 'white', font= ("consolas", 12), wrap = 'none', undo = 'True')
  797. self.config(height = 24, width = 100)
  798. self.config(insertbackground = 'pale green') # keyboard insertion point
  799. self.pack(side='left', fill='both', expand=True)
  800. self.tag_config('normal', foreground = 'white')
  801. self.tag_config('warning', foreground = 'yellow' )
  802. self.tag_config('error', foreground = 'red')
  803. self.tag_config('highlight_green', foreground = 'green')
  804. self.tag_config('highlight_blue', foreground = 'cyan')
  805. self.tag_config('error_highlight_inactive', background = 'dim gray')
  806. self.tag_config('error_highlight_active', background = 'light grey')
  807. self.bind_class("Text","<Control-a>", self.select_all) # required in windows, works in others
  808. self.bind_all("<Control-Shift-E>", self.scroll_errors)
  809. self.bind_class("<Control-Shift-R>", self.rebuild)
  810. # scrollbar
  811. scrb = tk.Scrollbar(self.frame, orient='vertical', command=self.yview)
  812. self.config(yscrollcommand=scrb.set)
  813. scrb.pack(side='right', fill='y')
  814. # self.scrb_Y = tk.Scrollbar(self.frame, orient='vertical', command=self.yview)
  815. # self.scrb_Y.config(yscrollcommand=self.scrb_Y.set)
  816. # self.scrb_Y.pack(side='right', fill='y')
  817. #
  818. # self.scrb_X = tk.Scrollbar(self.frame, orient='horizontal', command=self.xview)
  819. # self.scrb_X.config(xscrollcommand=self.scrb_X.set)
  820. # self.scrb_X.pack(side='bottom', fill='x')
  821. # 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
  822. # self.config(xscrollcommand=scrb_X.set)
  823. # scrb_X.pack(side='bottom', fill='x')
  824. #
  825. # scrb= tk.Scrollbar(self, orient='vertical', command=self.yview)
  826. # self.config(yscrollcommand=scrb.set)
  827. # scrb.pack(side='right', fill='y')
  828. # self.config(height = 240, width = 1000) # didn't get the size baCK TO NORMAL
  829. # self.pack(side='left', fill='both', expand=True) # didn't get the size baCK TO NORMAL
  830. # pop-up menu
  831. self.popup = tk.Menu(self, tearoff=0)
  832. self.popup.add_command(label='Copy', command=self._copy)
  833. self.popup.add_command(label='Paste', command=self._paste)
  834. self.popup.add_separator()
  835. self.popup.add_command(label='Cut', command=self._cut)
  836. self.popup.add_separator()
  837. self.popup.add_command(label='Select All', command=self._select_all)
  838. self.popup.add_command(label='Clear All', command=self._clear_all)
  839. self.popup.add_separator()
  840. self.popup.add_command(label='Save As', command=self._file_save_as)
  841. self.popup.add_separator()
  842. # self.popup.add_command(label='Repeat Build(CTL-shift-r)', command=self._rebuild)
  843. self.popup.add_command(label='Repeat Build', command=self._rebuild)
  844. self.popup.add_separator()
  845. self.popup.add_command(label='Scroll Errors (CTL-shift-e)', command=self._scroll_errors)
  846. self.popup.add_separator()
  847. self.popup.add_command(label='Open File at Cursor', command=self._open_selected_file)
  848. if current_OS == 'Darwin': # MAC
  849. self.bind('<Button-2>', self._show_popup) # macOS only
  850. else:
  851. self.bind('<Button-3>', self._show_popup) # Windows & Linux
  852. # threading & subprocess section
  853. def start_thread(self, ):
  854. global continue_updates
  855. # create then start a secondary thread to run an arbitrary function
  856. # must have at least one argument
  857. self.secondary_thread = threading.Thread(target = lambda q, arg1: q.put(run_PIO(arg1)), args=(que, ''))
  858. self.secondary_thread.start()
  859. continue_updates = True
  860. # check the Queue in 50ms
  861. self.root.after(50, self.check_thread)
  862. self.root.after(50, self.update)
  863. def check_thread(self): # wait for user to kill the window
  864. global continue_updates
  865. if continue_updates == True:
  866. self.root.after(10, self.check_thread)
  867. def update(self):
  868. global continue_updates
  869. if continue_updates == True:
  870. self.root.after(10, self.update)#method is called every 50ms
  871. temp_text = ['0','0']
  872. if IO_queue.empty():
  873. if not(self.secondary_thread.is_alive()):
  874. continue_updates = False # queue is exhausted and thread is dead so no need for further updates
  875. else:
  876. try:
  877. temp_text = IO_queue.get(block = False)
  878. except Queue.Empty:
  879. continue_updates = False # queue is exhausted so no need for further updates
  880. else:
  881. self.insert('end', temp_text[0], temp_text[1])
  882. self.see("end") # make the last line visible (scroll text off the top)
  883. # text editing section
  884. def _scroll_errors(self):
  885. global search_position
  886. global error_found
  887. if search_position == '': # first time so highlight all errors
  888. countVar = tk.IntVar()
  889. search_position = '1.0'
  890. search_count = 0
  891. while not(search_position == '') and search_count < 100:
  892. search_position = self.search("error", search_position, stopindex="end", count=countVar, nocase=1)
  893. search_count = search_count + 1
  894. if not(search_position == ''):
  895. error_found = True
  896. end_pos = '{}+{}c'.format(search_position, 5)
  897. self.tag_add("error_highlight_inactive", search_position, end_pos)
  898. search_position = '{}+{}c'.format(search_position, 1) # point to the next character for new search
  899. else:
  900. break
  901. if error_found:
  902. if search_position == '':
  903. search_position = self.search("error", '1.0', stopindex="end", nocase=1) # new search
  904. else: # remove active highlight
  905. end_pos = '{}+{}c'.format(search_position, 5)
  906. start_pos = '{}+{}c'.format(search_position, -1)
  907. self.tag_remove("error_highlight_active", start_pos, end_pos)
  908. search_position = self.search("error", search_position, stopindex="end", nocase=1) # finds first occurrence AGAIN on the first time through
  909. if search_position == "": # wrap around
  910. search_position = self.search("error", '1.0', stopindex="end", nocase=1)
  911. end_pos = '{}+{}c'.format(search_position, 5)
  912. self.tag_add("error_highlight_active", search_position, end_pos) # add active highlight
  913. self.see(search_position)
  914. search_position = '{}+{}c'.format(search_position, 1) # point to the next character for new search
  915. def scroll_errors(self, event):
  916. self._scroll_errors()
  917. def _rebuild(self):
  918. #global board_name
  919. #global Marlin_ver
  920. #global target_env
  921. #board_name, Marlin_ver = get_board_name()
  922. #target_env = get_env(board_name, Marlin_ver)
  923. self.start_thread()
  924. def rebuild(self, event):
  925. print "event happened"
  926. self._rebuild()
  927. def _open_selected_file(self):
  928. current_line = self.index('insert')
  929. line_start = current_line[ : current_line.find('.')] + '.0'
  930. line_end = current_line[ : current_line.find('.')] + '.200'
  931. self.mark_set("path_start", line_start)
  932. self.mark_set("path_end", line_end)
  933. path = self.get("path_start", "path_end")
  934. from_loc = path.find('from ')
  935. colon_loc = path.find(': ')
  936. if 0 <= from_loc and ((colon_loc == -1) or (from_loc < colon_loc)) :
  937. path = path [ from_loc + 5 : ]
  938. if 0 <= colon_loc:
  939. path = path [ : colon_loc ]
  940. if 0 <= path.find('\\') or 0 <= path.find('/'): # make sure it really contains a path
  941. open_file(path)
  942. def _file_save_as(self):
  943. self.filename = tkFileDialog.asksaveasfilename(defaultextension = '.txt')
  944. f = open(self.filename, 'w')
  945. f.write(self.get('1.0', 'end'))
  946. f.close()
  947. def copy(self, event):
  948. try:
  949. selection = self.get(*self.tag_ranges('sel'))
  950. self.clipboard_clear()
  951. self.clipboard_append(selection)
  952. except TypeError:
  953. pass
  954. def cut(self, event):
  955. try:
  956. selection = self.get(*self.tag_ranges('sel'))
  957. self.clipboard_clear()
  958. self.clipboard_append(selection)
  959. self.delete(*self.tag_ranges('sel'))
  960. except TypeError:
  961. pass
  962. def _show_popup(self, event):
  963. '''right-click popup menu'''
  964. if self.root.focus_get() != self:
  965. self.root.focus_set()
  966. try:
  967. self.popup.tk_popup(event.x_root, event.y_root, 0)
  968. finally:
  969. self.popup.grab_release()
  970. def _cut(self):
  971. try:
  972. selection = self.get(*self.tag_ranges('sel'))
  973. self.clipboard_clear()
  974. self.clipboard_append(selection)
  975. self.delete(*self.tag_ranges('sel'))
  976. except TypeError:
  977. pass
  978. def cut(self, event):
  979. self._cut()
  980. def _copy(self):
  981. try:
  982. selection = self.get(*self.tag_ranges('sel'))
  983. self.clipboard_clear()
  984. self.clipboard_append(selection)
  985. except TypeError:
  986. pass
  987. def copy(self, event):
  988. self._copy()
  989. def _paste(self):
  990. self.insert('insert', self.selection_get(selection='CLIPBOARD'))
  991. def _select_all(self):
  992. self.tag_add('sel', '1.0', 'end')
  993. def select_all(self, event):
  994. self.tag_add('sel', '1.0', 'end')
  995. def _clear_all(self):
  996. '''erases all text'''
  997. isok = askokcancel('Clear All', 'Erase all text?', frame=self,
  998. default='ok')
  999. if isok:
  1000. self.delete('1.0', 'end')
  1001. # end - output_window
  1002. def main():
  1003. ##########################################################################
  1004. # #
  1005. # main program #
  1006. # #
  1007. ##########################################################################
  1008. global build_type
  1009. global target_env
  1010. global board_name
  1011. board_name, Marlin_ver = get_board_name()
  1012. target_env = get_env(board_name, Marlin_ver)
  1013. os.environ["BUILD_TYPE"] = build_type # let sub processes know what is happening
  1014. os.environ["TARGET_ENV"] = target_env
  1015. os.environ["BOARD_NAME"] = board_name
  1016. auto_build = output_window()
  1017. if 0 <= target_env.find('USB1286'):
  1018. copy_boards_dir() # copy custom boards over to PlatformIO if using custom board
  1019. # causes 3-5 second delay in main window appearing
  1020. auto_build.start_thread() # executes the "run_PIO" function
  1021. auto_build.root.mainloop()
  1022. if __name__ == '__main__':
  1023. main()