chiark / gitweb /
Merge pull request #323 from smorloc/master
[cura.git] / Cura / util / profile.py
1 from __future__ import absolute_import
2 from __future__ import division
3
4 import os, traceback, math, re, zlib, base64, time, sys, platform, glob, string, stat
5 import cPickle as pickle
6 if sys.version_info[0] < 3:
7         import ConfigParser
8 else:
9         import configparser as ConfigParser
10
11 from Cura.util import resources
12 from Cura.util import version
13
14 #########################################################
15 ## Default settings when none are found.
16 #########################################################
17
18 #Single place to store the defaults, so we have a consistent set of default settings.
19 profileDefaultSettings = {
20         'nozzle_size': '0.4',
21         'layer_height': '0.2',
22         'wall_thickness': '0.8',
23         'solid_layer_thickness': '0.6',
24         'fill_density': '20',
25         'skirt_line_count': '1',
26         'skirt_gap': '3.0',
27         'print_speed': '50',
28         'print_temperature': '220',
29         'print_bed_temperature': '70',
30         'support': 'None',
31         'filament_diameter': '2.89',
32         'filament_density': '1.00',
33         'retraction_min_travel': '5.0',
34         'retraction_enable': 'False',
35         'retraction_speed': '40.0',
36         'retraction_amount': '4.5',
37         'retraction_extra': '0.0',
38         'retract_on_jumps_only': 'True',
39         'travel_speed': '150',
40         'max_z_speed': '3.0',
41         'bottom_layer_speed': '20',
42         'cool_min_layer_time': '5',
43         'fan_enabled': 'True',
44         'fan_layer': '1',
45         'fan_speed': '100',
46         'fan_speed_max': '100',
47         'model_matrix': '1,0,0,0,1,0,0,0,1',
48         'extra_base_wall_thickness': '0.0',
49         'sequence': 'Loops > Perimeter > Infill',
50         'force_first_layer_sequence': 'True',
51         'infill_type': 'Line',
52         'solid_top': 'True',
53         'fill_overlap': '15',
54         'support_rate': '50',
55         'support_distance': '0.5',
56         'support_dual_extrusion': 'False',
57         'joris': 'False',
58         'enable_skin': 'False',
59         'enable_raft': 'False',
60         'cool_min_feedrate': '10',
61         'bridge_speed': '100',
62         'raft_margin': '5',
63         'raft_base_material_amount': '100',
64         'raft_interface_material_amount': '100',
65         'bottom_thickness': '0.3',
66         'hop_on_move': 'False',
67         'plugin_config': '',
68         'object_center_x': '-1',
69         'object_center_y': '-1',
70         
71         'gcode_extension': 'gcode',
72         'alternative_center': '',
73         'clear_z': '0.0',
74         'extruder': '0',
75 }
76 alterationDefault = {
77 #######################################################################################
78         'start.gcode': """;Sliced {filename} at: {day} {date} {time}
79 ;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density}
80 ;Print time: {print_time}
81 ;Filament used: {filament_amount}m {filament_weight}g
82 ;Filament cost: {filament_cost}
83 G21        ;metric values
84 G90        ;absolute positioning
85 M107       ;start with the fan off
86
87 G28 X0 Y0  ;move X/Y to min endstops
88 G28 Z0     ;move Z to min endstops
89 G92 X0 Y0 Z0 E0         ;reset software position to front/left/z=0.0
90
91 G1 Z15.0 F{max_z_speed} ;move the platform down 15mm
92
93 G92 E0                  ;zero the extruded length
94 G1 F200 E3              ;extrude 3mm of feed stock
95 G92 E0                  ;zero the extruded length again
96 G1 F{travel_speed}
97 """,
98 #######################################################################################
99         'end.gcode': """;End GCode
100 M104 S0                     ;extruder heater off
101 M140 S0                     ;heated bed heater off (if you have it)
102
103 G91                                    ;relative positioning
104 G1 E-1 F300                            ;retract the filament a bit before lifting the nozzle, to release some of the pressure
105 G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more
106 G28 X0 Y0                              ;move X/Y to min endstops, so the head is out of the way
107
108 M84                         ;steppers off
109 G90                         ;absolute positioning
110 """,
111 #######################################################################################
112         'support_start.gcode': '',
113         'support_end.gcode': '',
114         'cool_start.gcode': '',
115         'cool_end.gcode': '',
116         'replace.csv': '',
117 #######################################################################################
118         'nextobject.gcode': """;Move to next object on the platform. clear_z is the minimal z height we need to make sure we do not hit any objects.
119 G92 E0
120
121 G91                                    ;relative positioning
122 G1 E-1 F300                            ;retract the filament a bit before lifting the nozzle, to release some of the pressure
123 G1 Z+0.5 E-5 F{travel_speed}           ;move Z up a bit and retract filament even more
124 G90                                    ;absolute positioning
125
126 G1 Z{clear_z} F{max_z_speed}
127 G92 E0
128 G1 X{object_center_x} Y{object_center_x} F{travel_speed}
129 G1 F200 E6
130 G92 E0
131 """,
132 #######################################################################################
133         'switchExtruder.gcode': """;Switch between the current extruder and the next extruder, when printing with multiple extruders.
134 G92 E0
135 G1 E-15 F5000
136 G92 E0
137 T{extruder}
138 G1 E15 F5000
139 G92 E0
140 """,
141 }
142 preferencesDefaultSettings = {
143         'startMode': 'Simple',
144         'lastFile': os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'resources', 'example', 'UltimakerRobot_support.stl')),
145         'machine_width': '205',
146         'machine_depth': '205',
147         'machine_height': '200',
148         'machine_type': 'unknown',
149         'machine_center_is_zero': 'False',
150         'ultimaker_extruder_upgrade': 'False',
151         'has_heated_bed': 'False',
152         'extruder_amount': '1',
153         'extruder_offset_x1': '-22.0',
154         'extruder_offset_y1': '0.0',
155         'extruder_offset_x2': '0.0',
156         'extruder_offset_y2': '0.0',
157         'extruder_offset_x3': '0.0',
158         'extruder_offset_y3': '0.0',
159         'filament_density': '1300',
160         'steps_per_e': '0',
161         'serial_port': 'AUTO',
162         'serial_port_auto': '',
163         'serial_baud': 'AUTO',
164         'serial_baud_auto': '',
165         'slicer': 'Cura (Skeinforge based)',
166         'save_profile': 'False',
167         'filament_cost_kg': '0',
168         'filament_cost_meter': '0',
169         'sdpath': '',
170         'sdshortnames': 'False',
171         'check_for_updates': 'True',
172
173         'planner_always_autoplace': 'True',
174         'extruder_head_size_min_x': '75.0',
175         'extruder_head_size_min_y': '18.0',
176         'extruder_head_size_max_x': '18.0',
177         'extruder_head_size_max_y': '35.0',
178         'extruder_head_size_height': '60.0',
179         
180         'model_colour': '#72CB30',
181         'model_colour2': '#CB3030',
182         'model_colour3': '#DDD93C',
183         'model_colour4': '#4550D3',
184 }
185
186 #########################################################
187 ## Profile and preferences functions
188 #########################################################
189
190 ## Profile functions
191 def getBasePath():
192         if platform.system() == "Windows":
193                 basePath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
194                 #If we have a frozen python install, we need to step out of the library.zip
195                 if hasattr(sys, 'frozen'):
196                         basePath = os.path.normpath(os.path.join(basePath, ".."))
197         else:
198                 basePath = os.path.expanduser('~/.cura/%s' % version.getVersion(False))
199         if not os.path.isdir(basePath):
200                 os.makedirs(basePath)
201         return basePath
202
203 def getDefaultProfilePath():
204         return os.path.join(getBasePath(), 'current_profile.ini')
205
206 def loadGlobalProfile(filename):
207         #Read a configuration file as global config
208         global globalProfileParser
209         globalProfileParser = ConfigParser.ConfigParser()
210         globalProfileParser.read(filename)
211
212 def resetGlobalProfile():
213         #Read a configuration file as global config
214         global globalProfileParser
215         globalProfileParser = ConfigParser.ConfigParser()
216
217         if getPreference('machine_type') == 'ultimaker':
218                 putProfileSetting('nozzle_size', '0.4')
219                 if getPreference('ultimaker_extruder_upgrade') == 'True':
220                         putProfileSetting('retraction_enable', 'True')
221         else:
222                 putProfileSetting('nozzle_size', '0.5')
223
224 def saveGlobalProfile(filename):
225         #Save the current profile to an ini file
226         globalProfileParser.write(open(filename, 'w'))
227
228 def loadGlobalProfileFromString(options):
229         global globalProfileParser
230         globalProfileParser = ConfigParser.ConfigParser()
231         globalProfileParser.add_section('profile')
232         globalProfileParser.add_section('alterations')
233         options = base64.b64decode(options)
234         options = zlib.decompress(options)
235         (profileOpts, alt) = options.split('\f', 1)
236         for option in profileOpts.split('\b'):
237                 if len(option) > 0:
238                         (key, value) = option.split('=', 1)
239                         globalProfileParser.set('profile', key, value)
240         for option in alt.split('\b'):
241                 if len(option) > 0:
242                         (key, value) = option.split('=', 1)
243                         globalProfileParser.set('alterations', key, value)
244
245 def getGlobalProfileString():
246         global globalProfileParser
247         if not globals().has_key('globalProfileParser'):
248                 loadGlobalProfile(getDefaultProfilePath())
249         
250         p = []
251         alt = []
252         tempDone = []
253         if globalProfileParser.has_section('profile'):
254                 for key in globalProfileParser.options('profile'):
255                         if key in tempOverride:
256                                 p.append(key + "=" + tempOverride[key])
257                                 tempDone.append(key)
258                         else:
259                                 p.append(key + "=" + globalProfileParser.get('profile', key))
260         if globalProfileParser.has_section('alterations'):
261                 for key in globalProfileParser.options('alterations'):
262                         if key in tempOverride:
263                                 p.append(key + "=" + tempOverride[key])
264                                 tempDone.append(key)
265                         else:
266                                 alt.append(key + "=" + globalProfileParser.get('alterations', key))
267         for key in tempOverride:
268                 if key not in tempDone:
269                         p.append(key + "=" + tempOverride[key])
270         ret = '\b'.join(p) + '\f' + '\b'.join(alt)
271         ret = base64.b64encode(zlib.compress(ret, 9))
272         return ret
273
274 def getProfileSetting(name):
275         if name in tempOverride:
276                 return unicode(tempOverride[name], "utf-8")
277         #Check if we have a configuration file loaded, else load the default.
278         if not globals().has_key('globalProfileParser'):
279                 loadGlobalProfile(getDefaultProfilePath())
280         if not globalProfileParser.has_option('profile', name):
281                 if name in profileDefaultSettings:
282                         default = profileDefaultSettings[name]
283                 else:
284                         print("Missing default setting for: '" + name + "'")
285                         profileDefaultSettings[name] = ''
286                         default = ''
287                 if not globalProfileParser.has_section('profile'):
288                         globalProfileParser.add_section('profile')
289                 globalProfileParser.set('profile', name, str(default))
290                 #print(name + " not found in profile, so using default: " + str(default))
291                 return default
292         return globalProfileParser.get('profile', name)
293
294 def getProfileSettingFloat(name):
295         try:
296                 setting = getProfileSetting(name).replace(',', '.')
297                 return float(eval(setting, {}, {}))
298         except (ValueError, SyntaxError, TypeError):
299                 return 0.0
300
301 def putProfileSetting(name, value):
302         #Check if we have a configuration file loaded, else load the default.
303         if not globals().has_key('globalProfileParser'):
304                 loadGlobalProfile(getDefaultProfilePath())
305         if not globalProfileParser.has_section('profile'):
306                 globalProfileParser.add_section('profile')
307         globalProfileParser.set('profile', name, str(value))
308
309 def isProfileSetting(name):
310         if name in profileDefaultSettings:
311                 return True
312         return False
313
314 ## Preferences functions
315 global globalPreferenceParser
316 globalPreferenceParser = None
317
318 def getPreferencePath():
319         return os.path.join(getBasePath(), 'preferences.ini')
320
321 def getPreferenceFloat(name):
322         try:
323                 setting = getPreference(name).replace(',', '.')
324                 return float(eval(setting, {}, {}))
325         except (ValueError, SyntaxError, TypeError):
326                 return 0.0
327
328 def getPreferenceColour(name):
329         colorString = getPreference(name)
330         return [float(int(colorString[1:3], 16)) / 255, float(int(colorString[3:5], 16)) / 255, float(int(colorString[5:7], 16)) / 255, 1.0]
331
332 def getPreference(name):
333         if name in tempOverride:
334                 return unicode(tempOverride[name])
335         global globalPreferenceParser
336         if globalPreferenceParser is None:
337                 globalPreferenceParser = ConfigParser.ConfigParser()
338                 globalPreferenceParser.read(getPreferencePath())
339         if not globalPreferenceParser.has_option('preference', name):
340                 if name in preferencesDefaultSettings:
341                         default = preferencesDefaultSettings[name]
342                 else:
343                         print("Missing default setting for: '" + name + "'")
344                         preferencesDefaultSettings[name] = ''
345                         default = ''
346                 if not globalPreferenceParser.has_section('preference'):
347                         globalPreferenceParser.add_section('preference')
348                 globalPreferenceParser.set('preference', name, str(default))
349                 #print(name + " not found in preferences, so using default: " + str(default))
350                 return default
351         return unicode(globalPreferenceParser.get('preference', name), "utf-8")
352
353 def putPreference(name, value):
354         #Check if we have a configuration file loaded, else load the default.
355         global globalPreferenceParser
356         if globalPreferenceParser == None:
357                 globalPreferenceParser = ConfigParser.ConfigParser()
358                 globalPreferenceParser.read(getPreferencePath())
359         if not globalPreferenceParser.has_section('preference'):
360                 globalPreferenceParser.add_section('preference')
361         globalPreferenceParser.set('preference', name, unicode(value).encode("utf-8"))
362         globalPreferenceParser.write(open(getPreferencePath(), 'w'))
363
364 def isPreference(name):
365         if name in preferencesDefaultSettings:
366                 return True
367         return False
368
369 ## Temp overrides for multi-extruder slicing and the project planner.
370 tempOverride = {}
371 def setTempOverride(name, value):
372         tempOverride[name] = unicode(value).encode("utf-8")
373 def clearTempOverride(name):
374         del tempOverride[name]
375 def resetTempOverride():
376         tempOverride.clear()
377
378 #########################################################
379 ## Utility functions to calculate common profile values
380 #########################################################
381 def calculateEdgeWidth():
382         wallThickness = getProfileSettingFloat('wall_thickness')
383         nozzleSize = getProfileSettingFloat('nozzle_size')
384         
385         if wallThickness < nozzleSize:
386                 return wallThickness
387
388         lineCount = int(wallThickness / nozzleSize + 0.0001)
389         lineWidth = wallThickness / lineCount
390         lineWidthAlt = wallThickness / (lineCount + 1)
391         if lineWidth > nozzleSize * 1.5:
392                 return lineWidthAlt
393         return lineWidth
394
395 def calculateLineCount():
396         wallThickness = getProfileSettingFloat('wall_thickness')
397         nozzleSize = getProfileSettingFloat('nozzle_size')
398         
399         if wallThickness < nozzleSize:
400                 return 1
401
402         lineCount = int(wallThickness / nozzleSize + 0.0001)
403         lineWidth = wallThickness / lineCount
404         lineWidthAlt = wallThickness / (lineCount + 1)
405         if lineWidth > nozzleSize * 1.5:
406                 return lineCount + 1
407         return lineCount
408
409 def calculateSolidLayerCount():
410         layerHeight = getProfileSettingFloat('layer_height')
411         solidThickness = getProfileSettingFloat('solid_layer_thickness')
412         return int(math.ceil(solidThickness / layerHeight - 0.0001))
413
414 def getMachineCenterCoords():
415         if getPreference('machine_center_is_zero') == 'True':
416                 return [0, 0]
417         return [getPreferenceFloat('machine_width') / 2, getPreferenceFloat('machine_depth') / 2]
418
419 def getObjectMatrix():
420         scale = getProfileSettingFloat('model_scale')
421         return map(lambda x: float(x) * scale, getProfileSetting('model_matrix').split(','))
422
423 #########################################################
424 ## Alteration file functions
425 #########################################################
426 def replaceTagMatch(m):
427         pre = m.group(1)
428         tag = m.group(2)
429         if tag == 'time':
430                 return pre + time.strftime('%H:%M:%S').encode('utf-8', 'replace')
431         if tag == 'date':
432                 return pre + time.strftime('%d %b %Y').encode('utf-8', 'replace')
433         if tag == 'day':
434                 return pre + time.strftime('%a').encode('utf-8', 'replace')
435         if tag == 'print_time':
436                 return pre + '#P_TIME#'
437         if tag == 'filament_amount':
438                 return pre + '#F_AMNT#'
439         if tag == 'filament_weight':
440                 return pre + '#F_WGHT#'
441         if tag == 'filament_cost':
442                 return pre + '#F_COST#'
443         if pre == 'F' and tag in ['print_speed', 'retraction_speed', 'travel_speed', 'max_z_speed', 'bottom_layer_speed', 'cool_min_feedrate']:
444                 f = getProfileSettingFloat(tag) * 60
445         elif isProfileSetting(tag):
446                 f = getProfileSettingFloat(tag)
447         elif isPreference(tag):
448                 f = getProfileSettingFloat(tag)
449         else:
450                 return '%s?%s?' % (pre, tag)
451         if (f % 1) == 0:
452                 return pre + str(int(f))
453         return pre + str(f)
454
455 def replaceGCodeTags(filename, gcodeInt):
456         f = open(filename, 'r+')
457         data = f.read(2048)
458         data = data.replace('#P_TIME#', ('%5d:%02d' % (int(gcodeInt.totalMoveTimeMinute / 60), int(gcodeInt.totalMoveTimeMinute % 60)))[-8:])
459         data = data.replace('#F_AMNT#', ('%8.2f' % (gcodeInt.extrusionAmount / 1000))[-8:])
460         data = data.replace('#F_WGHT#', ('%8.2f' % (gcodeInt.calculateWeight() * 1000))[-8:])
461         cost = gcodeInt.calculateCost()
462         if cost is None:
463                 cost = 'Unknown'
464         data = data.replace('#F_COST#', ('%8s' % (cost.split(' ')[0]))[-8:])
465         f.seek(0)
466         f.write(data)
467         f.close()
468
469 ### Get aleration raw contents. (Used internally in Cura)
470 def getAlterationFile(filename):
471         #Check if we have a configuration file loaded, else load the default.
472         if not globals().has_key('globalProfileParser'):
473                 loadGlobalProfile(getDefaultProfilePath())
474         
475         if not globalProfileParser.has_option('alterations', filename):
476                 if filename in alterationDefault:
477                         default = alterationDefault[filename]
478                 else:
479                         print("Missing default alteration for: '" + filename + "'")
480                         alterationDefault[filename] = ''
481                         default = ''
482                 if not globalProfileParser.has_section('alterations'):
483                         globalProfileParser.add_section('alterations')
484                 #print("Using default for: %s" % (filename))
485                 globalProfileParser.set('alterations', filename, default)
486         return unicode(globalProfileParser.get('alterations', filename), "utf-8")
487
488 def setAlterationFile(filename, value):
489         #Check if we have a configuration file loaded, else load the default.
490         if not globals().has_key('globalProfileParser'):
491                 loadGlobalProfile(getDefaultProfilePath())
492         if not globalProfileParser.has_section('alterations'):
493                 globalProfileParser.add_section('alterations')
494         globalProfileParser.set('alterations', filename, value.encode("utf-8"))
495         saveGlobalProfile(getDefaultProfilePath())
496
497 ### Get the alteration file for output. (Used by Skeinforge)
498 def getAlterationFileContents(filename):
499         prefix = ''
500         postfix = ''
501         alterationContents = getAlterationFile(filename)
502         if filename == 'start.gcode':
503                 #For the start code, hack the temperature and the steps per E value into it. So the temperature is reached before the start code extrusion.
504                 #We also set our steps per E here, if configured.
505                 eSteps = getPreferenceFloat('steps_per_e')
506                 if eSteps > 0:
507                         prefix += 'M92 E%f\n' % (eSteps)
508                 temp = getProfileSettingFloat('print_temperature')
509                 bedTemp = 0
510                 if getPreference('has_heated_bed') == 'True':
511                         bedTemp = getProfileSettingFloat('print_bed_temperature')
512                 
513                 if bedTemp > 0 and not '{print_bed_temperature}' in alterationContents:
514                         prefix += 'M140 S%f\n' % (bedTemp)
515                 if temp > 0 and not '{print_temperature}' in alterationContents:
516                         prefix += 'M109 S%f\n' % (temp)
517                 if bedTemp > 0 and not '{print_bed_temperature}' in alterationContents:
518                         prefix += 'M190 S%f\n' % (bedTemp)
519         elif filename == 'end.gcode':
520                 #Append the profile string to the end of the GCode, so we can load it from the GCode file later.
521                 postfix = ';CURA_PROFILE_STRING:%s\n' % (getGlobalProfileString())
522         elif filename == 'replace.csv':
523                 #Always remove the extruder on/off M codes. These are no longer needed in 5D printing.
524                 prefix = 'M101\nM103\n'
525         elif filename == 'support_start.gcode' or filename == 'support_end.gcode':
526                 #Add support start/end code 
527                 if getProfileSetting('support_dual_extrusion') == 'True' and int(getPreference('extruder_amount')) > 1:
528                         if filename == 'support_start.gcode':
529                                 setTempOverride('extruder', '1')
530                         else:
531                                 setTempOverride('extruder', '0')
532                         alterationContents = getAlterationFileContents('switchExtruder.gcode')
533                         clearTempOverride('extruder')
534                 else:
535                         alterationContents = ''
536         return unicode(prefix + re.sub("(.)\{([^\}]*)\}", replaceTagMatch, alterationContents).rstrip() + '\n' + postfix).strip().encode('utf-8') + '\n'
537
538 ###### PLUGIN #####
539
540 def getPluginConfig():
541         try:
542                 return pickle.loads(getProfileSetting('plugin_config'))
543         except:
544                 return []
545
546 def setPluginConfig(config):
547         putProfileSetting('plugin_config', pickle.dumps(config))
548
549 def getPluginBasePaths():
550         ret = []
551         if platform.system() != "Windows":
552                 ret.append(os.path.expanduser('~/.cura/plugins/'))
553         if platform.system() == "Darwin" and hasattr(sys, 'frozen'):
554                 ret.append(os.path.normpath(os.path.join(resources.resourceBasePath, "Cura/plugins")))
555         else:
556                 ret.append(os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'plugins')))
557         return ret
558
559 def getPluginList():
560         ret = []
561         for basePath in getPluginBasePaths():
562                 for filename in glob.glob(os.path.join(basePath, '*.py')):
563                         filename = os.path.basename(filename)
564                         if filename.startswith('_'):
565                                 continue
566                         with open(os.path.join(basePath, filename), "r") as f:
567                                 item = {'filename': filename, 'name': None, 'info': None, 'type': None, 'params': []}
568                                 for line in f:
569                                         line = line.strip()
570                                         if not line.startswith('#'):
571                                                 break
572                                         line = line[1:].split(':', 1)
573                                         if len(line) != 2:
574                                                 continue
575                                         if line[0].upper() == 'NAME':
576                                                 item['name'] = line[1].strip()
577                                         elif line[0].upper() == 'INFO':
578                                                 item['info'] = line[1].strip()
579                                         elif line[0].upper() == 'TYPE':
580                                                 item['type'] = line[1].strip()
581                                         elif line[0].upper() == 'DEPEND':
582                                                 pass
583                                         elif line[0].upper() == 'PARAM':
584                                                 m = re.match('([a-zA-Z]*)\(([a-zA-Z_]*)(?::([^\)]*))?\) +(.*)', line[1].strip())
585                                                 if m is not None:
586                                                         item['params'].append({'name': m.group(1), 'type': m.group(2), 'default': m.group(3), 'description': m.group(4)})
587                                         else:
588                                                 print "Unknown item in effect meta data: %s %s" % (line[0], line[1])
589                                 if item['name'] != None and item['type'] == 'postprocess':
590                                         ret.append(item)
591         return ret
592
593 def runPostProcessingPlugins(gcodefilename):
594         pluginConfigList = getPluginConfig()
595         pluginList = getPluginList()
596         
597         for pluginConfig in pluginConfigList:
598                 plugin = None
599                 for pluginTest in pluginList:
600                         if pluginTest['filename'] == pluginConfig['filename']:
601                                 plugin = pluginTest
602                 if plugin is None:
603                         continue
604                 
605                 pythonFile = None
606                 for basePath in getPluginBasePaths():
607                         testFilename = os.path.join(basePath, pluginConfig['filename'])
608                         if os.path.isfile(testFilename):
609                                 pythonFile = testFilename
610                 if pythonFile is None:
611                         continue
612                 
613                 locals = {'filename': gcodefilename}
614                 for param in plugin['params']:
615                         value = param['default']
616                         if param['name'] in pluginConfig['params']:
617                                 value = pluginConfig['params'][param['name']]
618                         
619                         if param['type'] == 'float':
620                                 try:
621                                         value = float(value)
622                                 except:
623                                         value = float(param['default'])
624                         
625                         locals[param['name']] = value
626                 try:
627                         execfile(pythonFile, locals)
628                 except:
629                         locationInfo = traceback.extract_tb(sys.exc_info()[2])[-1]
630                         return "%s: '%s' @ %s:%s:%d" % (str(sys.exc_info()[0].__name__), str(sys.exc_info()[1]), os.path.basename(locationInfo[0]), locationInfo[2], locationInfo[1])
631         return None
632
633 def getSDcardDrives():
634         drives = ['']
635         if platform.system() == "Windows":
636                 from ctypes import windll
637                 bitmask = windll.kernel32.GetLogicalDrives()
638                 for letter in string.uppercase:
639                         if bitmask & 1:
640                                 drives.append(letter + ':/')
641                         bitmask >>= 1
642         if platform.system() == "Darwin":
643                 drives = []
644                 for volume in glob.glob('/Volumes/*'):
645                         if stat.S_ISLNK(os.lstat(volume).st_mode):
646                                 continue
647                         drives.append(volume)
648         return drives