Improved slicing and file management

- File management is prepared to support folders (UI still lacking support)
- STL files are now first class citizens
  - can be managed via the file list (and filtered from it)
  - can be sliced on demand
- Slicing now happens via plugins
- Added Cura plugin
  - uses CuraEngine directly instead of full Cura installation
  - Cura profile importer for importing profiles from regular Cura installs via settings dialog
  - TODO: UI for editing profiles
- API for slicing and slicing profile management
This commit is contained in:
Gina Häußge committed 2014-10-06 17:34:07 +02:00
1 parent af94b770f9
commit cd973adedf
56 files changed
+147756 -1010

No files matched your search

-1
View File
@@ -4,7 +4,6 @@
*.pyc
*.zip
*.exe
*.gcode
*.swp
darwin-Cura-*
win32-Cura-*
+8 -1
View File
@@ -28,9 +28,16 @@
* Start counting the layers at 1 instead of 0 in the GCODE viewer
* Upgraded [Font Awesome](https://fortawesome.github.io/Font-Awesome/) to version 3.2.1
* Better error reporting for timelapse rendering and system commands
* Supports
* Custom control can now be defined so that they show a Confirm dialog with configurable text before executing
([#532](https://github.com/foosel/OctoPrint/issues/532) and [#590](https://github.com/foosel/OctoPrint/pull/590))
* Slicing has been greatly improved and now allows for a definition of slicing profiles to use for slicing plus overrides
which can be defined per slicing job. Slicers themselves are integrated into the system via ``SlicingPlugins``. Please
note that the [Cura integration](https://github.com/daid/Cura) has changed in such a way that OctoPrint now calls the
[CuraEngine](https://github.com/Ultimaker/CuraEngine) directly instead of depending on the full Cura installation. See
[the wiki](https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura) for instructions on how to change your setup to
accommodate the new integration.
* File management now supports STL files as first class citizens (including UI adjustments to allow management of
uploaded STL files including removal and reslicing) and also allows folders (not yet supported by UI)
### Bug Fixes
+48 -1
View File
@@ -304,7 +304,19 @@ Issue a file command
is not operational when this parameter is present and set to ``true``, the request will fail with a response
of ``409 Conflict``.
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
slice
Slices an STL file into GCODE. Note that this is an asynchronous operation that will take place in the background
after the response has been sent back to the client. Additional parameters are:
* ``slicer``: The slicing engine to use, defaults to ``cura`` if not set, which is also the only supported slicer right now.
* ``gcode``: Name of the GCODE file to generated, in the same location as the STL file. Defaults to the STL file name
with extension ``.gco`` if not set.
* ``profile``: Name of the slicing profile to use, if not set the default slicing profile of the slicer will be used.
* ``profile.*``: Override parameters, the ``profile.`` prefix will be stripped and the matching profile key will
be overridden with the supplied value. Use this if you want to specify things that change often like a different
temperature, filament diameter or infill percentage. Profile keys are slicer specific.
Upon success, a status code of :http:statuscode:`204` and an empty body is returned, unless specified otherwise.
**Example Select Request**
@@ -324,6 +336,39 @@ Issue a file command
HTTP/1.1 204 No Content
**Example Slice Request**
.. sourcecode:: http
POST /api/files/local/some_model.stl HTTP/1.1
Host: example.com
Content-Type: application/json
X-Api-Key: abcdef...
{
"command": "slice",
"slicer": "cura",
"gcode": "some_model.first_try.gcode",
"profile": "high_quality",
"profile.infill": 75,
"profile.fill_density": 15
}
.. sourcecode:: http
HTTP/1.1 202 Accepted
Content-Type: application/json
{
"origin": "local",
"name": "some_model.first_try.gcode",
"refs": {
"download": "http://example.com/downloads/files/local/some_model.first_try.gcode",
"resource": "http://example.com/api/files/local/some_model.first_try.gcode"
}
}
:param target: The target location on which to delete the file, either ``local`` (for OctoPrint's ``uploads``
folder) or ``sdcard`` for the printer's SD card (if available)
:param filename: The filename of the file for which to issue the command
@@ -331,7 +376,9 @@ Issue a file command
:json boolean print: ``select`` command: Optional, whether to start printing the file directly after selection,
defaults to ``false``.
:statuscode 200: No error
:statuscode 202: No error for a ``slice`` command.
:statuscode 400: If the `command` is unknown or the request is otherwise invalid
:statuscode 415: If a ``slice`` command was issued against something other than an STL file.
:statuscode 404: If `target` is neither ``local`` nor ``sdcard`` or the requested file was not found
:statuscode 409: If a selected file is supposed to start printing directly but the printer is not operational.
+1
View File
@@ -14,5 +14,6 @@ API Documentation
printer.rst
job.rst
logs.rst
slicing.rst
push.rst
datamodel.rst
+1 -1
View File
@@ -783,7 +783,7 @@ Full State Response
- The printer's sd state data
* - ``state``
- 0..1
- :ref:`Printer State <sec-api-printer-datamodel-printerstate>`
- :ref:`Printer State <sec-api-datamodel-printer-state>`
- The printer's general state
.. _sec-api-printer-datamodel-temps:
+336
View File
@@ -0,0 +1,336 @@
.. _sec-api-slicing:
*******
Slicing
*******
.. warning::
The interface documented here is the status quo that might be changed while the interfaces are streamlined for
a more general consumption. If you happen to want to develop against it, you should drop me an email to make sure I can give you a heads-up when
something changes.
.. contents::
The Slicing API on one hand offers methods for managing slicing profiles stored within OctoPrint, on the other hand
it will be extended in the future to also allow for multi extruder slicing (which currently is not possible with the
``slice`` command of the :ref:`File operations API <sec-api-fileops-filecommand>` and other things.
.. _sec-api-slicing-listall:
List All Slicers and Slicing Profiles
=====================================
.. http:get:: /api/slicing
Returns a list of all available slicing profiles for all registered slicers in the system.
Returns a :http:statuscode:`200` response with a :ref:`Slicer list <sec-api-slicing-datamodel-slicerlist>`
as the body upon successful completion.
**Example**
.. sourcecode:: http
GET /api/slicing/profiles HTTP/1.1
Host: example.com
X-Api-Key: abcdef...
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: application/json
{
"cura": {
"key": "cura",
"displayName": "CuraEngine",
"default": true,
"profiles": {
"high_quality": {
"key": "high_quality",
"displayName": "High Quality",
"default": false,
"resource": "http://example.com/api/slicing/cura/profiles/high_quality"
},
"medium_quality": {
"key": "medium_quality",
"displayName": "Medium Quality",
"default": true,
"resource": "http://example.com/api/slicing/cura/profiles/medium_quality"
},
...
}
},
...
}
:statuscode 200: No error
.. _sec-api-slicing-list:
List Slicing Profiles of a Specific Slicer
==========================================
.. http:get:: /api/slicing/(string:slicer)/profiles
Returns a list of all available slicing profiles for the requested slicer.
Returns a :http:statuscode:`200` response with a :ref:`Profile list <sec-api-slicing-datamodel-profilelist>`
as the body upon successful completion.
**Example**
.. sourcecode:: http
GET /api/slicing/cura/profiles HTTP/1.1
Host: example.com
X-Api-Key: abcdef...
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: application/json
{
"high_quality": {
"key": "high_quality",
"displayName": "High Quality",
"default": false,
"resource": "http://example.com/api/slicing/cura/profiles/high_quality"
},
"medium_quality": {
"key": "medium_quality",
"displayName": "Medium Quality",
"default": true,
"resource": "http://example.com/api/slicing/cura/profiles/medium_quality"
},
...
}
:param slicer: The identifying key of the slicer for which to list the available profiles.
:statuscode 200: No error
:statuscode 404: If the ``slicer`` was unknown to the system.
.. _sec-api-slicing-listspecific:
Retrieve Specific Profile
=========================
.. http:get:: /api/slicing/(string:slicer)/profiles/(string:key)
Retrieves the specified profile from the system.
Returns a :http:statuscode:`200` response with a :ref:`full Profile <sec-api-slicing-datamodel-profile>`
as the body upon successful completion.
**Example**
.. sourcecode:: http
GET /api/slicing/cura/profiles/quick_test HTTP/1.1
Host: example.com
X-Api-Key: abcdef...
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: application/json
{
"displayName": "Just a test",
"description": "This is just a test",
"resource": "http://example.com/api/slicing/cura/profiles/quick_test",
"data": {
"bottom_layer_speed": 20.0,
"bottom_thickness": 0.3,
"brim_line_count": 20,
"cool_head_lift": false,
"cool_min_feedrate": 10.0,
"cool_min_layer_time": 5.0,
...
}
}
:param slicer: The identifying key of the slicer for which to list the available profiles.
:param name: The identifying key of the profile to retrieve
:statuscode 200: No error
:statuscode 404: If the ``slicer`` or the profile was unknown to the system.
.. _sec-api-slicing-add:
Add Slicing Profile
===================
.. http:put:: /api/slicing/(string:slicer)/profiles/(string:key)
Adds a new slicing profile for the given ``slicer`` to the system. If the profile identified by ``key`` already exists,
it will be overwritten.
Expects a :ref:`Profile <sec-api-slicing-datamodel-profile>` as body.
Returns a :http:statuscode:`201` and an :ref:`abridged Profile <sec-api-slicing-datamodel-profile>` in the body
upon successful completion.
**Example**
.. sourcecode:: http
PUT /api/slicing/cura/profiles/quick_test HTTP/1.1
Host: example.com
X-Api-Key: abcdef...
Content-Type: application/json
{
"displayName": "Just a test",
"description": "This is just a test to show how to create a cura profile with a different layer height and skirt count",
"data": {
"layer_height": 0.2,
"skirt_line_count": 3
}
}
.. sourcecode:: http
HTTP/1.1 201 Created
Content-Type: application/json
Location: http://example.com/api/slicing/cura/profiles/quick_test
{
"displayName": "Just a test",
"description": "This is just a test to show how to create a cura profile with a different layer height and skirt count",
"resource": "http://example.com/api/slicing/cura/profiles/quick_test"
}
:param slicer: The identifying key of the slicer for which to add the profile
:param key: The identifying key of the new profile
:statuscode 201: No error
:statuscode 404: If the ``slicer`` was unknown to the system.
.. _sec-api-slicing-delete:
Delete Slicing Profile
======================
.. http:delete:: /api/slicing/(string:slicer)/profiles/(string:key)
Delete the slicing profile identified by ``key`` for the slicer ``slicer``.
:param slicer: The identifying key of the slicer for which to delete the profile
:param key: The identifying key of the profile to delete
:statuscode 204: No error
:statuscode 404: If the ``slicer`` was unknown to the system.
.. _sec-api-slicing-datamodel:
Datamodel
=========
.. _sec-api-slicing-datamodel-slicerlist:
Slicer list
-----------
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``<slicer key>``
- 0..*
- :ref:`Slicer <sec-api-slicing-datamodel-slicer>`
- Information about a slicer registered in the system, incl. stored profiles without ``data``.
.. _sec-api-slicing-datamodel-slicer:
Slicer
------
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``key``
- 1
- ``string``
- Identifier of the slicer
* - ``displayName``
- 0..1
- ``string``
- Display name of the slicer
* - ``default``
- 1
- ``boolean``
- Whether the slicer is the default slicer to use (``true``) or not (``false``).
* - ``profiles``
- 0..*
- :ref:`Profile list <sec-api-slicing-datamodel-profilelist>`
- Slicing profiles available for this slicer, mapped by their ``key``
.. _sec-api-slicing-datamodel-profilelist:
Profile list
------------
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``<profile key>``
- 0..1
- :ref:`Profile <sec-api-slicing-datamodel-profile>`
- Information about a profile stored in the system, ``data`` field will be left out.
.. _sec-api-slicing-datamodel-profile:
Profile
-------
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``key``
- 1
- ``string``
- Identifier of the profile
* - ``displayName``
- 0..1
- ``string``
- Display name of the profile
* - ``description``
- 0..1
- ``string``
- Description of the profile
* - ``default``
- 0..1
- ``boolean``
- Whether this is the default profile to be used with this slicer (``true``) or not (``false``). Will always be
returned in responses but can be left out of save/update requests.
* - ``resource``
- 0..1
- ``URL``
- Resource URL of the profile, will always be returned in responses but can be left out of save/update requests.
* - ``data``
- 0..1
- Object
- The actual profile data, including any default values if the profile was retrieved from the server. May contain
only the keys differing from the defaults when saving/updating a profile. The keys to be found in here a slicer
specific. Will be left out for list responses.
+6 -5
View File
@@ -12,17 +12,18 @@
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('../src/'))
import octoprint._version
from datetime import date
year_since = 2013
year_current = date.today().year
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
+8 -1
View File
@@ -132,7 +132,14 @@ UpdatedFiles
Payload:
* ``type``: the type of file list that was modified, currently only ``gcode`` is supported here
* ``type``: the type of file list that was modified. Currently only ``printables`` and ``gcode`` (DEPRECATED) are supported here.
.. note::
The type ``gcode`` has been renamed to ``printables`` with the introduction of a new file management layer that
supports STL files as first class citizens as well. For reasons of backwards compatibility the ``UpdatedFiles``
event for printable files will be fired twice, once with ``type`` set to ``gcode``, once set to ``printables``.
Support for the ``gcode`` type will be removed in the next release after version 1.2.0.
MetadataAnalysisStarted
The metadata analysis of a GCODE file has started.
+9
View File
@@ -133,6 +133,15 @@ class EventManager(object):
self._queue.put((event, payload), 0)
if event == Events.UPDATED_FILES and "type" in payload and payload["type"] == "printables":
# when sending UpdatedFiles with type "printables", also send another event with deprecated type "gcode"
# TODO v1.3.0 Remove again
import copy
legacy_payload = copy.deepcopy(payload)
legacy_payload["type"] = "gcode"
self._queue.put((event, legacy_payload), 0)
def subscribe(self, event, callback):
"""
Subscribe a listener to an event -- pass in the event name (as a string) and the callback object
+273 -1
View File
@@ -1,3 +1,275 @@
# coding=utf-8
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import logging
import os
from octoprint.events import eventManager, Events
from .destinations import FileDestinations
from .analysis import QueueEntry, AnalysisQueue
from .storage import LocalFileStorage
extensions = dict(
# extensions for 3d model files
model=dict(
stl=["stl"]
),
# extensions for printable machine code
machinecode=dict(
gcode=["gcode", "gco", "g"]
)
)
def get_extensions(type, subtree=None):
if not subtree:
subtree = extensions
for key, value in subtree.items():
if key == type:
return get_all_extensions(subtree=value)
elif isinstance(value, dict):
sub_extensions = get_extensions(type, subtree=value)
if sub_extensions:
return sub_extensions
return None
def get_all_extensions(subtree=None):
if not subtree:
subtree = extensions
result = []
if isinstance(subtree, dict):
for key, value in subtree.items():
if isinstance(value, dict):
result += get_all_extensions(value)
elif isinstance(value, (list, tuple)):
result += value
elif isinstance(subtree, (list, tuple)):
result = subtree
return result
def get_path_for_extension(extension, subtree=None):
if not subtree:
subtree = extensions
for key, value in subtree.items():
if isinstance(value, (list, tuple)) and extension in value:
return [key]
elif isinstance(value, dict):
path = get_path_for_extension(extension, subtree=value)
if path:
return [key] + path
return None
all_extensions = get_all_extensions()
def valid_extension(extension, type=None):
if not type:
return extension in all_extensions
else:
extensions = get_extensions(type)
if extensions:
return extension in extensions
def valid_file_type(filename, type=None):
_, extension = os.path.splitext(filename)
extension = extension[1:].lower()
return valid_extension(extension, type=type)
def get_file_type(filename):
_, extension = os.path.splitext(filename)
extension = extension[1:].lower()
return get_path_for_extension(extension)
class FileManager(object):
def __init__(self, analysis_queue, slicing_manager, initial_storage_managers=None):
self._logger = logging.getLogger(__name__)
self._analysis_queue = analysis_queue
self._analysis_queue.register_finish_callback(self._on_analysis_finished)
self._storage_managers = dict()
if initial_storage_managers:
self._storage_managers.update(initial_storage_managers)
self._slicing_manager = slicing_manager
for storage_type, storage_manager in self._storage_managers.items():
self._determine_analysis_backlog(storage_type, storage_manager)
def _determine_analysis_backlog(self, storage_type, storage_manager):
self._logger.info("Adding backlog items from {storage_type} to analysis queue".format(**locals()))
for entry, path in storage_manager.analysis_backlog:
file_type = get_file_type(path)[-1]
queue_entry = QueueEntry(entry, file_type, storage_type, path)
self._analysis_queue.enqueue(queue_entry, high_priority=False)
def add_storage(self, storage_type, storage_manager):
self._storage_managers[storage_type] = storage_manager
self._determine_analysis_backlog(storage_type, storage_manager)
def remove_storage(self, type):
if not type in self._storage_managers:
return
del self._storage_managers[type]
@property
def slicing_enabled(self):
return self._slicing_manager.slicing_enabled
@property
def registered_slicers(self):
return self._slicing_manager.registered_slicers
@property
def default_slicer(self):
return self._slicing_manager.default_slicer
def slice(self, slicer_name, source_location, source_path, dest_location, dest_path, profile=None, overrides=None, callback=None, callback_args=None):
absolute_source_path = self.get_absolute_path(source_location, source_path)
def stlProcessed(source_location, source_path, tmp_path, dest_location, dest_path, start_time, callback, callback_args, _error=None):
try:
if _error:
eventManager().fire(Events.SLICING_FAILED, {"stl": source_path, "gcode": dest_path, "reason": _error})
else:
source_meta = self.get_metadata(source_location, source_path)
hash = source_meta["hash"]
class Wrapper(object):
def __init__(self, stl_name, temp_path, hash):
self.stl_name = stl_name
self.temp_path = temp_path
self.hash = hash
def save(self, absolute_dest_path):
with open(absolute_dest_path, "w") as d:
d.write(";Generated from {stl_name} {hash}\r".format(**vars(self)))
with open(tmp_path, "r") as s:
import shutil
shutil.copyfileobj(s, d)
links = [("model", dict(name=source_path))]
_, stl_name = self.split_path(source_location, source_path)
file_obj = Wrapper(stl_name, temp_path, hash)
self.add_file(dest_location, dest_path, file_obj, links=links, allow_overwrite=True)
end_time = time.time()
eventManager().fire(Events.SLICING_DONE, {"stl": source_path, "gcode": dest_path, "time": end_time - start_time})
if callback is not None:
if callback_args is None:
callback_args = ()
callback(*callback_args)
finally:
os.remove(tmp_path)
import time
start_time = time.time()
eventManager().fire(Events.SLICING_STARTED, {"stl": source_path, "gcode": dest_path})
import tempfile
f = tempfile.NamedTemporaryFile(suffix=".gco", delete=False)
temp_path = f.name
f.close()
args = (source_location, source_path, temp_path, dest_location, dest_path, start_time, callback, callback_args)
return self._slicing_manager.slice(slicer_name, absolute_source_path, temp_path, profile, stlProcessed, callback_args=args, overrides=overrides)
def file_exists(self, destination, path):
return self._storage(destination).file_exists(path)
def list_files(self, destinations=None, path=None, filter=None, recursive=None):
if not destinations:
destinations = self._storage_managers.keys()
if isinstance(destinations, (str, unicode, basestring)):
destinations = [destinations]
result = dict()
for dst in destinations:
result[dst] = self._storage_managers[dst].list_files(path=path, filter=filter, recursive=recursive)
return result
def add_file(self, destination, path, file_object, links=None, allow_overwrite=False):
file_path = self._storage(destination).add_file(path, file_object, links=links, allow_overwrite=allow_overwrite)
absolute_path = self._storage(destination).get_absolute_path(file_path)
file_type = get_file_type(file_path[-1])
queue_entry = QueueEntry(file_path, file_type, destination, absolute_path)
self._analysis_queue.enqueue(queue_entry, high_priority=True)
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
return file_path
def remove_file(self, destination, path):
self._storage(destination).remove_file(path)
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
def add_folder(self, destination, path, ignore_existing=True):
folder_path = self._storage(destination).add_folder(path, ignore_existing=ignore_existing)
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
return folder_path
def remove_folder(self, destination, path, recursive=True):
self._storage(destination).remove_folder(path, recursive=recursive)
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
def get_metadata(self, destination, path):
return self._storage(destination).get_metadata(path)
def add_link(self, destination, path, rel, data):
self._storage(destination).add_link(path, rel, data)
def remove_link(self, destination, path, rel, data):
self._storage(destination).remove_link(path, rel, data)
def log_print(self, destination, path, timestamp, print_time, success):
self._storage(destination).add_history(path, dict(timestamp=timestamp, printTime=print_time, success=success))
def set_additional_metadata(self, destination, path, key, data, overwrite=False, merge=False):
self._storage(destination).set_additional_metadata(path, key, data, overwrite=overwrite, merge=merge)
def remove_additional_metadata(self, destination, path, key):
self._storage(destination).remove_additional_metadata(path, key)
def get_absolute_path(self, destination, path):
return self._storage(destination).get_absolute_path(path)
def sanitize(self, destination, path):
return self._storage(destination).sanitize(path)
def sanitize_name(self, destination, name):
return self._storage(destination).sanitize_name(name)
def sanitize_path(self, destination, path):
return self._storage(destination).sanitize_path(path)
def split_path(self, destination, path):
return self._storage(destination).split_path(path)
def join_path(self, destination, *path):
return self._storage(destination).join_path(*path)
def rel_path(self, destination, path):
return self._storage(destination).rel_path(path)
def _storage(self, destination):
if not destination in self._storage_managers:
raise RuntimeError("No storage configured for destination {destination}".format(**locals()))
return self._storage_managers[destination]
def _on_analysis_finished(self, entry, result):
if not entry.location in self._storage_managers:
return
storage_manager = self._storage_managers[entry.location]
storage_manager.set_additional_metadata(entry.path, "analysis", result)
+166
View File
@@ -0,0 +1,166 @@
# coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import logging
import Queue as queue
import os
import threading
import collections
from octoprint.events import Events, eventManager
import octoprint.util.gcodeInterpreter as gcodeInterpreter
class QueueEntry(collections.namedtuple("QueueEntry", "path, type, location, absolute_path")):
def __str__(self):
return "{location}:{path}".format(location=self.location, path=self.path)
class AnalysisQueue(object):
def __init__(self):
self._logger = logging.getLogger(__name__)
self._callbacks = []
self._queues = dict(
gcode=GcodeAnalysisQueue(self._analysis_finished)
)
def register_finish_callback(self, callback):
self._callbacks.append(callback)
def unregister_finish_callback(self, callback):
self._callbacks.remove(callback)
def enqueue(self, entry, high_priority=False):
if not entry.type in self._queues:
return
self._queues[entry.type].enqueue(entry, high_priority=high_priority)
def pause(self):
for queue in self._queues.values():
queue.pause()
def resume(self):
for queue in self._queues.values():
queue.resume()
def _analysis_finished(self, entry, result):
for callback in self._callbacks:
callback(entry, result)
eventManager().fire(Events.METADATA_ANALYSIS_FINISHED, {"file": entry.path, "result": result})
class AbstractAnalysisQueue(object):
def __init__(self, finished_callback):
self._logger = logging.getLogger(__name__)
self._finished_callback = finished_callback
self._active = threading.Event()
self._active.set()
self._currentFile = None
self._currentProgress = None
self._queue = queue.PriorityQueue()
self._current = None
self._worker = threading.Thread(target=self._work)
self._worker.daemon = True
self._worker.start()
def enqueue(self, entry, high_priority=False):
if high_priority:
self._logger.debug("Adding entry {entry} to analysis queue with high priority".format(entry=entry))
prio = 0
else:
self._logger.debug("Adding entry {entry} to analysis queue with low priority".format(entry=entry))
prio = 100
self._queue.put((prio, entry))
def pause(self):
self._logger.debug("Pausing analysis")
self._active.clear()
if self._current is not None:
self._logger.debug("Aborting running analysis, will restart when analyzer is resumed")
self._do_abort()
def resume(self):
self._logger.debug("Resuming analyzer")
self._active.set()
def _work(self):
aborted = None
while True:
if aborted is not None:
entry = aborted
aborted = None
self._logger.debug("Got an aborted analysis job for entry {entry}, processing this instead of first item in queue".format(**locals()))
else:
(priority, entry) = self._queue.get()
self._logger.debug("Processing entry {entry} from queue (priority {priority})".format(**locals()))
self._active.wait()
try:
self._analyze(entry)
self._queue.task_done()
except gcodeInterpreter.AnalysisAborted:
aborted = entry
self._logger.debug("Running analysis of entry {entry} aborted".format(**locals()))
def _analyze(self, entry):
path = entry.absolute_path
if path is None or not os.path.exists(path):
return
self._current = entry
self._current_progress = 0
try:
self._logger.debug("Starting analysis of {entry}".format(**locals()))
eventManager().fire(Events.METADATA_ANALYSIS_STARTED, {"file": entry.path, "type": entry.type})
result = self._do_analysis()
self._logger.debug("Analysis of entry {entry} finished, notifying callback".format(**locals()))
self._finished_callback(self._current, result)
finally:
self._current = None
self._current_progress = None
def _do_analysis(self):
return None
def _do_abort(self):
pass
class GcodeAnalysisQueue(AbstractAnalysisQueue):
def _do_analysis(self):
try:
self._gcode = gcodeInterpreter.gcode()
self._gcode.load(self._current.absolute_path)
result = dict()
if self._gcode.totalMoveTimeMinute:
result["estimatedPrintTime"] = self._gcode.totalMoveTimeMinute * 60
if self._gcode.extrusionAmount:
result["filament"] = dict()
for i in range(len(self._gcode.extrusionAmount)):
result["filament"]["tool%d" % i] = {
"length": self._gcode.extrusionAmount[i],
"volume": self._gcode.extrusionVolume[i]
}
return result
finally:
self._gcode = None
def _do_abort(self):
if self._gcode:
self._gcode.abort()
+787
View File
@@ -0,0 +1,787 @@
# coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import logging
import os
import octoprint.filemanager
class StorageInterface(object):
@property
def analysis_backlog(self):
# empty generator pattern, yield is intentionally unreachable
return
yield
def file_exists(self, path):
raise NotImplementedError()
def list_files(self, path=None, filter=None, recursive=True):
raise NotImplementedError()
def add_folder(self, path, ignore_existing=True):
raise NotImplementedError()
def remove_folder(self, path, recursive=True):
raise NotImplementedError()
def add_file(self, path, file_object, links=None, allow_overwrite=False):
raise NotImplementedError()
def remove_file(self, path):
raise NotImplementedError()
def get_metadata(self, path):
raise NotImplementedError()
def add_link(self, path, rel, data):
raise NotImplementedError()
def remove_link(self, path, rel, data):
raise NotImplementedError()
def set_additional_metadata(self, path, key, data, overwrite=False, merge=False):
raise NotImplementedError()
def remove_additional_metadata(self, path, key):
raise NotImplementedError()
def sanitize(self, path):
raise NotImplementedError()
def sanitize_path(self, path):
raise NotImplementedError()
def sanitize_name(self, name):
raise NotImplementedError()
def split_path(self, path):
raise NotImplementedError()
def join_path(self, *path):
raise NotImplementedError()
def rel_path(self, path):
raise NotImplementedError()
def get_absolute_path(self, path):
raise NotImplementedError()
class LocalFileStorage(StorageInterface):
def __init__(self, basefolder, create=False):
self._logger = logging.getLogger(__name__)
self.basefolder = os.path.realpath(os.path.abspath(basefolder))
if not os.path.exists(self.basefolder) and create:
os.makedirs(self.basefolder)
if not os.path.exists(self.basefolder) or not os.path.isdir(self.basefolder):
raise RuntimeError("{basefolder} is not a valid directory".format(**locals()))
import threading
self._metadata_lock = threading.Lock()
@property
def analysis_backlog(self):
for entry in self._analysis_backlog_generator():
yield entry
def _analysis_backlog_generator(self, path=None):
if path is None:
path = self.basefolder
metadata = self._get_metadata(path)
if not metadata:
metadata = dict()
for entry in os.listdir(path):
if entry.startswith(".") or not octoprint.filemanager.valid_file_type(entry):
continue
absolute_path = os.path.join(path, entry)
if os.path.isfile(absolute_path):
if not entry in metadata or not isinstance(metadata[entry], dict) or not "analysis" in metadata[entry]:
yield entry, absolute_path
elif os.path.isdir(absolute_path):
for sub_entry in self._analysis_backlog_generator(absolute_path):
yield self.join_path(entry, sub_entry), os.path.join(absolute_path, sub_entry)
def file_exists(self, path):
path, name = self.sanitize(path)
file_path = os.path.join(path, name)
return os.path.exists(file_path) and os.path.isfile(file_path)
def list_files(self, path=None, filter=None, recursive=True):
"""
List all files in storage starting at ``path``. If ``recursive`` is set to True (the default), also dives into
subfolders.
An optional filter function can be supplied which will be called with a file name and file data and which has
to return True if the file is to be included in the result or False if not.
The data structure of the returned result will be a dictionary mapping from file names to entry data. File nodes
will contain their metadata here, folder nodes will contain their contained files and folders. Example::
{
"some_folder": {
"type": "folder",
"children": {
"some_sub_folder": {
"type": "folder",
"children": { ... }
},
"some_file.gcode": {
"type": "machinecode",
"hash": "<sha1 hash>",
"links": [ ... ],
...
},
...
}
"test.gcode": {
"type": "machinecode",
"hash": "<sha1 hash>",
"links": [...],
...
},
"test.stl": {
"type": "model",
"hash": "<sha1 hash>",
"links": [...],
...
},
...
}
:param path: base path from which to recursively list all files, optional, if not supplied listing will start
from root of base folder
:param filter: a filter that matches the files that are to be returned, may be left out in which case no
filtering will take place
:param recursive: will also step into sub folders for building the complete list if set to True
:return: a dictionary mapping entry names to entry data that represents the whole file list
"""
if path:
path = self.sanitize_path(path)
else:
path = self.basefolder
return self._list_folder(path, filter=filter, recursive=recursive)
def add_folder(self, path, ignore_existing=True):
"""
Adds a folder as ``path``. The ``path`` will be sanitized.
:param path: the path of the new folder
:param ignore_existing: if set to True, no error will be raised if the folder to be added already exists
:return: the sanitized name of the new folder to be used for future references to the folder
"""
path, name = self.sanitize(path)
folder_path = os.path.join(path, name)
if os.path.exists(folder_path):
if not ignore_existing:
raise RuntimeError("{sanitized_foldername} does already exist in {virtual_path}".format(**locals()))
else:
os.mkdir(folder_path)
return self.rel_path((path, name))
def remove_folder(self, path, recursive=True):
"""
Removes the folder at ``path``.
:param path: the path of the folder to remove
:param recursive: if set to True, contained folders and files will also be removed, otherwise and error will
be raised if the folder is not empty (apart from ``.metadata.yaml``) when it's to be removed
"""
path, name = self.sanitize(path)
folder_path = os.path.join(path, name)
if not os.path.exists(folder_path):
return
contents = os.listdir(folder_path)
if ".metadata.yaml" in contents:
contents.remove(".metadata.yaml")
if contents and not recursive:
raise RuntimeError("{sanitized_foldername} in {virtual_path} is not empty".format(**locals()))
import shutil
shutil.rmtree(folder_path)
def add_file(self, path, file_object, links=None, allow_overwrite=False):
"""
Adds the file ``file_object`` as ``path``
:param path: the file's new path, will be sanitized
:param file_object: a file object that provides a ``save`` method which will be called with the destination path
where the object should then store its contents
:param links: any links to add with the file
:param allow_overwrite: if set to True no error will be raised if the file already exists and the existing file
and its metadata will just be silently overwritten
:return: the sanitized name of the file to be used for future references to it
"""
path, name = self.sanitize(path)
if not octoprint.filemanager.valid_file_type(name):
raise RuntimeError("{name} is an unrecognized file type".format(**locals()))
metadata = self._get_metadata(path)
if not metadata:
metadata = dict()
file_path = os.path.join(path, name)
if os.path.exists(file_path) and not os.path.isfile(file_path):
raise RuntimeError("{name} does already exist in {path} and is not a file".format(**locals()))
if os.path.exists(file_path) and not allow_overwrite:
raise RuntimeError("{name} does already exist in {path} and overwriting is prohibited".format(**locals()))
# make sure folders exist
if not os.path.exists(path):
os.makedirs(path)
# save the file
file_object.save(file_path)
# save the file's hash to the metadata of the folder
file_hash = self._create_hash(file_path)
if not name in metadata or not "hash" in metadata[name] or metadata[name]["hash"] != file_hash:
# make sure to create a new metadata entry if we've never seen that file with that content before
file_metadata = dict(
hash=file_hash
)
metadata[name] = file_metadata
self._save_metadata(path, metadata)
# process any links that were also provided for adding to the file
if links:
self._add_links(name, path, links)
return self.rel_path((path, name))
def remove_file(self, path):
"""
Removes the file at ``path``. Will also take care of deleting the corresponding entries
in the metadata and deleting all links pointing to the file.
:param path: path of the file to remove
"""
path, name = self.sanitize(path)
metadata = self._get_metadata(path)
file_path = os.path.join(path, name)
if not os.path.exists(file_path):
return
if not os.path.isfile(file_path):
raise RuntimeError("{name} in {path} is not a file".format(**locals()))
try:
os.remove(file_path)
except Exception as e:
raise RuntimeError("Could not delete {name} in {path}".format(**locals()), e)
if name in metadata:
if "hash" in metadata[name]:
hash = metadata[name]["hash"]
for m in metadata.values():
if not "links" in m:
continue
for link in m["links"]:
if "rel" in link and "hash" in link and (link["rel"] == "model" or link["rel"] == "machinecode") and link["hash"] == hash:
m["links"].remove(link)
del metadata[name]
self._save_metadata(path, metadata)
def get_metadata(self, path):
"""
Retrieves the metadata for the file ``path``.
:param path: virtual path to the file for which to retrieve the metadata
:return: the metadata associated with the file
"""
path, name = self.sanitize(path)
metadata = self._get_metadata(path)
if name in metadata:
return metadata[name]
else:
return None
def add_link(self, path, rel, data):
"""
Adds a link of relation ``rel`` to file ``path`` with the given ``data``.
The following relation types are currently supported:
* ``model``: adds a link to a model from which the file was created/sliced, expected additional data is the ``name``
and optionally the ``hash`` of the file to link to. If the link can be resolved against another file on the
current ``path``, not only will it be added to the links of ``name`` but a reverse link of type ``machinecode``
refering to ``name`` and its hash will also be added to the linked ``model`` file
* ``machinecode``: adds a link to a file containing machine code created from the current file (model), expected
additional data is the ``name`` and optionally the ``hash`` of the file to link to. If the link can be resolved
against another file on the current ``path``, not only will it be added to the links of ``name`` but a reverse
link of type ``model`` refering to ``name`` and its hash will also be added to the linked ``model`` file.
* ``web``: adds a location on the web associated with this file (e.g. a website where to download a model),
expected additional data is a ``href`` attribute holding the website's URL and optionally a ``retrieved``
attribute describing when the content was retrieved
Note that adding ``model`` links to files identifying as models or ``machinecode`` links to files identifying
as machine code will be refused.
:param path: path of the file for which to add a link
:param rel: type of relation of the link to add (currently ``model``, ``machinecode`` and ``web`` are supported)
:param data: additional data of the link to add
"""
path, name = self.sanitize(path)
self._add_links(name, path, [(rel, data)])
def remove_link(self, path, rel, data):
"""
Removes the link consisting of ``rel`` and ``data`` from file ``name`` on ``path``.
:param path: path of the file from which to remove the link
:param rel: type of relation of the link to remove (currently ``model``, ``machinecode`` and ``web`` are supported)
:param data: additional data of the link to remove, must match existing link
"""
path, name = self.sanitize(path)
self._remove_links(name, path, [(rel, data)])
def add_history(self, path, data):
path, name = self.sanitize(path)
self._add_history(name, path, data)
def update_history(self, path, index, data):
path, name = self.sanitize(path)
self._update_history(name, path, index, data)
def remove_history(self, path, index):
path, name = self.sanitize(path)
self._update_history(name, path, index)
def set_additional_metadata(self, path, key, data, overwrite=False, merge=False):
"""
Adds additional metadata to the metadata of ``path``. Metadata in ``data`` will be saved under ``key``.
If ``overwrite`` is set and ``key`` already exists in ``name``'s metadata, the current value will be overwritten.
If ``merge`` is set and ``key`` already exists and both ``data`` and the existing data under ``key`` are dictionaries,
the two dictionaries will be merged recursively.
:param path: the virtual path to the file for which to add additional metadata
:param key: key of metadata to add
:param data: metadata to add
:param overwrite: if True and ``key`` already exists, it will be overwritten
:param merge: if True and ``key`` already exists and both ``data`` and the existing data are dictionaries, they
will be merged
"""
path, name = self.sanitize(path)
metadata = self._get_metadata(path)
metadata_dirty = False
if not name in metadata:
return
if not key in metadata[name] or overwrite:
metadata[name][key] = data
metadata_dirty = True
elif key in metadata[name] and isinstance(metadata[name][key], dict) and isinstance(data, dict) and merge:
current_data = metadata[name][key]
import octoprint.util
new_data = octoprint.util.dict_merge(current_data, data)
metadata[name][key] = new_data
metadata_dirty = True
elif key in metadata[name] and overwrite:
metadata[name][key] = data
metadata_dirty = True
if metadata_dirty:
self._save_metadata(path, metadata)
def remove_additional_metadata(self, path, key):
"""
Removes additional metadata under ``key`` for ``name`` on ``path``
:param path: the virtual path to the file for which to remove the metadata under ``key``
:param key: the key to remove
"""
path, name = self.sanitize(path)
metadata = self._get_metadata(path)
if not name in metadata:
return
if not key in metadata[name]:
return
del metadata[name][key]
self._save_metadata(path, metadata)
def split_path(self, path):
"""
Split ``path`` into base directory and file name.
:param path: the path to split
:return: a tuple (base directory, file name)
"""
split = path.split("/")
if len(split) == 1:
return "", split[0]
else:
return self.join_path(*split[:-1]), split[-1]
def join_path(self, *path):
"""
Join path elements together
:param path: path elements to join
:return: joined representation of the path to be usable as fully qualified path for further operations
"""
return "/".join(path)
def get_absolute_path(self, path):
"""
Retrieves the absolute path on disk for ``path``
:param path: the virtual path for which to retrieve the absolute path on disk
:return: the absolute path on disk to ``path``
"""
path, name = self.sanitize(path)
return os.path.join(path, name)
##~~ internals
def _add_history(self, name, path, data):
metadata = self._get_metadata(path)
if not name in metadata:
metadata[name] = dict()
if not "hash" in metadata[name]:
metadata[name]["hash"] = self._create_hash(os.path.join(path, name))
if not "history" in metadata[name]:
metadata[name]["history"] = []
metadata[name]["history"].append(data)
self._save_metadata(path, metadata)
def _update_history(self, name, path, index, data):
metadata = self._get_metadata(path)
if not name in metadata or not "history" in metadata[name]:
return
try:
metadata[name]["history"][index] = data
self._save_metadata(path, metadata)
except IndexError:
pass
def _delete_history(self, name, path, index):
metadata = self._get_metadata(path)
if not name in metadata or not "history" in metadata[name]:
return
try:
del metadata[name]["history"][index]
self._save_metadata(path, metadata)
except IndexError:
pass
def _add_links(self, name, path, links):
file_type = octoprint.filemanager.get_file_type(name)
if file_type:
file_type = file_type[0]
metadata = self._get_metadata(path)
metadata_dirty = False
if not name in metadata:
metadata[name] = dict()
if not "hash" in metadata[name]:
metadata[name]["hash"] = self._create_hash(os.path.join(path, name))
if not "links" in metadata[name]:
metadata[name]["links"] = []
for rel, data in links:
if (rel == "model" or rel == "machinecode") and "name" in data:
if file_type == "model" and rel == "model":
# adding a model link to a model doesn't make sense
return
elif file_type == "machinecode" and rel == "machinecode":
# adding a machinecode link to a machinecode doesn't make sense
return
ref_path = os.path.join(path, data["name"])
if not os.path.exists(ref_path):
# file doesn't exist, we won't create the link
continue
# fetch hash of target file
if data["name"] in metadata and "hash" in metadata[data["name"]]:
hash = metadata[data["name"]]["hash"]
else:
hash = self._create_hash(ref_path)
if not data["name"] in metadata:
metadata[data["name"]] = dict(
hash=hash,
links=[]
)
else:
metadata[data["name"]]["hash"] = hash
if "hash" in data and not data["hash"] == hash:
# file doesn't have the correct hash, we won't create the link
continue
if not "links" in metadata[data["name"]]:
metadata[data["name"]]["links"] = []
# add reverse link to link target file
metadata[data["name"]]["links"].append(
dict(rel="machinecode" if rel == "model" else "model", name=name, hash=metadata[name]["hash"])
)
metadata_dirty = True
link_dict = dict(
rel=rel,
name=data["name"],
hash=hash
)
elif rel == "web" and "href" in data:
link_dict = dict(
rel=rel,
href=data["href"]
)
if "retrieved" in data:
link_dict["retrieved"] = data["retrieved"]
else:
continue
if link_dict:
metadata[name]["links"].append(link_dict)
metadata_dirty = True
if metadata_dirty:
self._save_metadata(path, metadata)
def _remove_links(self, name, path, links):
metadata = self._get_metadata(path)
metadata_dirty = False
if not name in metadata or not "hash" in metadata[name]:
hash = self._create_hash(os.path.join(path, name))
else:
hash = metadata[name]["hash"]
for rel, data in links:
if (rel == "model" or rel == "machinecode") and "name" in data:
if data["name"] in metadata and "links" in metadata[data["name"]]:
ref_rel = "model" if rel == "machinecode" else "machinecode"
for link in metadata[data["name"]]["links"]:
if link["rel"] == ref_rel and "name" in link and link["name"] == name and "hash" in link and link["hash"] == hash:
metadata[data["name"]]["links"].remove(link)
metadata_dirty = True
if "links" in metadata[name]:
for link in metadata[name]["links"]:
if not link["rel"] == rel:
continue
matches = True
for k, v in data.items():
if not k in link or not link[k] == v:
matches = False
break
if not matches:
continue
metadata[name]["links"].remove(link)
metadata_dirty = True
if metadata_dirty:
self._save_metadata(path, metadata)
def _list_folder(self, path, filter=None, recursive=True):
metadata = self._get_metadata(path)
if not metadata:
metadata = dict()
metadata_dirty = False
result = dict()
for entry in os.listdir(path):
if entry.startswith("."):
# no hidden files and folders
continue
entry_path = os.path.join(path, entry)
# file handling
if os.path.isfile(entry_path):
file_type = octoprint.filemanager.get_file_type(entry)
if not file_type:
# only supported extensions
continue
else:
file_type = file_type[0]
if entry in metadata and isinstance(metadata[entry], dict):
entry_data = metadata[entry]
else:
entry_data = dict(
hash=self._create_hash(entry_path),
links=[],
notes=[]
)
metadata[entry] = entry_data
metadata_dirty = True
# TODO extract model hash from source if possible to recreate link
if not filter or filter(entry, entry_data):
# only add files passing the optional filter
extended_entry_data = dict()
extended_entry_data.update(entry_data)
extended_entry_data["name"] = entry
extended_entry_data["type"] = file_type
stat = os.stat(entry_path)
if stat:
extended_entry_data["size"] = stat.st_size
extended_entry_data["date"] = int(stat.st_mtime)
result[entry] = extended_entry_data
# folder recursion
elif os.path.isdir(entry_path) and recursive:
sub_result = self._list_folder(entry_path, filter=filter)
result[entry] = dict(
name=entry,
type="folder",
children=sub_result
)
# TODO recreate links if we have metadata less entries
# save metadata
if metadata_dirty:
self._save_metadata(path, metadata)
return result
def _create_hash(self, path):
import hashlib
blocksize = 65536
hash = hashlib.sha1()
with open(path, "rb") as f:
buffer = f.read(blocksize)
while len(buffer) > 0:
hash.update(buffer)
buffer = f.read(blocksize)
return hash.hexdigest()
def sanitize(self, path):
name = None
if isinstance(path, (str, unicode, basestring)):
if path.startswith(self.basefolder):
path = path[len(self.basefolder):]
path = path.replace(os.path.sep, "/")
path = path.split("/")
if isinstance(path, (list, tuple)):
if len(path) == 1:
name = path[0]
path = "/"
else:
name = path[-1]
path = "/" + self.join_path(*path[:-1])
if not path:
path = "/"
name = self.sanitize_name(name)
path = self.sanitize_path(path)
return path, name
def sanitize_name(self, name):
if name is None:
return None
if "/" in name or "\\" in name:
raise ValueError("name must not contain / or \\")
import string
valid_chars = "-_.() {ascii}{digits}".format(ascii=string.ascii_letters, digits=string.digits)
sanitized_name = ''.join(c for c in name if c in valid_chars)
sanitized_name = sanitized_name.replace(" ", "_")
return sanitized_name
def sanitize_path(self, path):
if path[0] == "/" or path[0] == ".":
path = path[1:]
path_elements = path.split("/")
joined_path = self.basefolder
for path_element in path_elements:
joined_path = os.path.join(joined_path, self.sanitize_name(path_element))
path = os.path.realpath(joined_path)
if not path.startswith(self.basefolder):
raise ValueError("path not contained in base folder: {path}".format(**locals()))
return path
def rel_path(self, path):
if isinstance(path, (tuple, list)):
path = self.join_path(*path)
if isinstance(path, (str, unicode, basestring)):
if path.startswith(self.basefolder):
path = path[len(self.basefolder):]
path = path.replace(os.path.sep, "/")
if path.startswith("/"):
path = path[1:]
return path
def _get_metadata(self, path):
metadata_path = os.path.join(path, ".metadata.yaml")
if os.path.exists(metadata_path):
with self._metadata_lock:
with open(metadata_path) as f:
try:
import yaml
return yaml.safe_load(f)
except:
self._logger.exception("Error while reading .metadata.yaml from {path}".format(**locals()))
return dict()
def _save_metadata(self, path, metadata):
metadata_path = os.path.join(path, ".metadata.yaml")
with self._metadata_lock:
with open(metadata_path, "w") as f:
try:
import yaml
yaml.safe_dump(metadata, stream=f, default_flow_style=False, indent=" ", allow_unicode=True)
except:
self._logger.exception("Error while writing .metadata.yaml to {path}".format(**locals()))
-615
View File
@@ -1,615 +0,0 @@
# coding=utf-8
import re
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
import os
import Queue
import threading
import yaml
import time
import logging
import octoprint.util as util
import octoprint.util.gcodeInterpreter as gcodeInterpreter
from octoprint.settings import settings
from octoprint.events import eventManager, Events
from octoprint.filemanager.destinations import FileDestinations
from werkzeug.utils import secure_filename
GCODE_EXTENSIONS = ["gcode", "gco", "g"]
STL_EXTENSIONS = ["stl"]
SUPPORTED_EXTENSIONS = GCODE_EXTENSIONS + STL_EXTENSIONS
def isGcodeFileName(filename):
"""Simple helper to determine if a filename has the .gcode extension.
:param filename: :class: `str`
:returns boolean:
"""
return "." in filename and filename.rsplit(".", 1)[1].lower() in GCODE_EXTENSIONS
def isSTLFileName(filename):
"""Simple helper to determine if a filename has the .stl extension.
:param filename: :class: `str`
:returns boolean:
"""
return "." in filename and filename.rsplit(".", 1)[1].lower() in STL_EXTENSIONS
def genGcodeFileName(filename):
if not filename:
return None
name, ext = filename.rsplit(".", 1)
return name + ".gcode"
def genStlFileName(filename):
if not filename:
return None
name, ext = filename.rsplit(".", 1)
return name + ".stl"
class GcodeManager:
def __init__(self):
self._logger = logging.getLogger(__name__)
self._settings = settings()
self._uploadFolder = self._settings.getBaseFolder("uploads")
self._callbacks = []
self._metadata = {}
self._metadataDirty = False
self._metadataFile = os.path.join(self._uploadFolder, "metadata.yaml")
self._metadataTempFile = os.path.join(self._uploadFolder, "metadata.yaml.tmp")
self._metadataFileAccessMutex = threading.Lock()
self._metadataAnalyzer = MetadataAnalyzer(getPathCallback=self.getAbsolutePath, loadedCallback=self._onMetadataAnalysisFinished)
self._loadMetadata(migrate=True)
self._processAnalysisBacklog()
def _processAnalysisBacklog(self):
for osFile in os.listdir(self._uploadFolder):
filename = self._getBasicFilename(osFile)
if not isGcodeFileName(filename):
continue
absolutePath = self.getAbsolutePath(filename)
if absolutePath is None:
continue
fileData = self.getFileData(filename)
if fileData is not None and "gcodeAnalysis" in fileData.keys():
continue
self._metadataAnalyzer.addFileToBacklog(filename)
def _onMetadataAnalysisFinished(self, filename, gcode):
if filename is None or gcode is None:
return
basename = os.path.basename(filename)
absolutePath = self.getAbsolutePath(basename)
if absolutePath is None:
return
analysisResult = {}
dirty = False
if gcode.totalMoveTimeMinute:
analysisResult["estimatedPrintTime"] = gcode.totalMoveTimeMinute * 60
dirty = True
if gcode.extrusionAmount:
analysisResult["filament"] = {}
for i in range(len(gcode.extrusionAmount)):
analysisResult["filament"]["tool%d" % i] = {
"length": gcode.extrusionAmount[i],
"volume": gcode.extrusionVolume[i]
}
dirty = True
if dirty:
metadata = self.getFileMetadata(basename)
metadata["gcodeAnalysis"] = analysisResult
self._metadata[basename] = metadata
self._metadataDirty = True
self._saveMetadata()
eventManager().fire(Events.METADATA_ANALYSIS_FINISHED, {"file": basename, "result": analysisResult})
def _loadMetadata(self, migrate=False):
if os.path.exists(self._metadataFile) and os.path.isfile(self._metadataFile):
with self._metadataFileAccessMutex:
with open(self._metadataFile, "r") as f:
self._metadata = yaml.safe_load(f)
if self._metadata is None:
self._metadata = {}
# TODO: Remove in a couple of versions (2013-12-21)
if migrate:
self._migrateMetadata()
def _migrateMetadata(self):
self._logger.info("Migrating metadata if necessary...")
printTimeRe = re.compile("(\d+):(\d{2}):(\d{2})")
filamentRe = re.compile("(\d*\.\d+)m(\s/\s(\d*\.\d+)cm.)?")
hoursToSeconds = 60 * 60
minutesToSeconds = 60
updateCount = 0
for metadata in self._metadata.values():
if not "gcodeAnalysis" in metadata:
continue
updated = False
if "estimatedPrintTime" in metadata["gcodeAnalysis"]:
estimatedPrintTime = metadata["gcodeAnalysis"]["estimatedPrintTime"]
if isinstance(estimatedPrintTime, (str, unicode)):
match = re.match(printTimeRe, estimatedPrintTime)
if match:
metadata["gcodeAnalysis"]["estimatedPrintTime"] = int(match.group(1)) * hoursToSeconds + int(match.group(2)) * minutesToSeconds + int(match.group(3))
self._metadataDirty = True
updated = True
if "filament" in metadata["gcodeAnalysis"]:
filament = metadata["gcodeAnalysis"]["filament"]
if isinstance(filament, (str, unicode)):
match = re.match(filamentRe, filament)
if match:
metadata["gcodeAnalysis"]["filament"] = {
"tool0": {
"length": int(float(match.group(1)) * 1000)
}
}
if match.group(3) is not None:
metadata["gcodeAnalysis"]["filament"]["tool0"].update({
"volume": float(match.group(3))
})
self._metadataDirty = True
updated = True
elif isinstance(filament, dict) and ("length" in filament.keys() or "volume" in filament.keys()):
metadata["gcodeAnalysis"]["filament"] = {
"tool0": {}
}
if "length" in filament.keys():
metadata["gcodeAnalysis"]["filament"]["tool0"].update({
"length": filament["length"]
})
if "volume" in filament.keys():
metadata["gcodeAnalysis"]["filament"]["tool0"].update({
"volume": filament["volume"]
})
self._metadataDirty = True
updated = True
if updated:
updateCount += 1
self._saveMetadata()
self._logger.info("Updated %d sets of metadata to new format" % updateCount)
def _saveMetadata(self, force=False):
if not self._metadataDirty and not force:
return
with self._metadataFileAccessMutex:
with open(self._metadataTempFile, "wb") as f:
yaml.safe_dump(self._metadata, f, default_flow_style=False, indent=" ", allow_unicode=True)
self._metadataDirty = False
util.safeRename(self._metadataTempFile, self._metadataFile)
self._loadMetadata()
def _getBasicFilename(self, filename):
if filename.startswith(self._uploadFolder):
return filename[len(self._uploadFolder + os.path.sep):]
else:
return filename
#~~ callback handling
def registerCallback(self, callback):
self._callbacks.append(callback)
def unregisterCallback(self, callback):
if callback in self._callbacks:
self._callbacks.remove(callback)
def _sendUpdateTrigger(self, type):
for callback in self._callbacks:
try: callback.sendEvent(type)
except: pass
#~~ file handling
def addFile(self, file, destination, uploadCallback=None):
"""
Adds the given file for the given destination to the systems. Takes care of slicing if enabled and
necessary.
If the file's processing won't be finished directly with the return from this method but happen
asynchronously in the background (e.g. due to slicing), returns a tuple containing the just added file's
filename and False. Otherwise returns a tuple (filename, True).
"""
if not file or not destination:
return None, True
curaEnabled = self._settings.getBoolean(["cura", "enabled"])
filename = file.filename
absolutePath = self.getAbsolutePath(filename, mustExist=False)
gcode = isGcodeFileName(filename)
if absolutePath is None or (not curaEnabled and not gcode):
return None, True
file.save(absolutePath)
if gcode:
return self.processGcode(absolutePath, destination, uploadCallback), True
else:
if curaEnabled and isSTLFileName(filename):
return self.processStl(absolutePath, destination, uploadCallback), False
else:
return filename, False
def getFutureFileName(self, file):
if not file:
return None
absolutePath = self.getAbsolutePath(file.filename, mustExist=False)
if absolutePath is None:
return None
return self._getBasicFilename(absolutePath)
def processStl(self, absolutePath, destination, uploadCallback=None):
from octoprint.slicers.cura import CuraFactory
cura = CuraFactory.create_slicer()
gcodePath = genGcodeFileName(absolutePath)
config = self._settings.get(["cura", "config"])
slicingStart = time.time()
def stlProcessed(stlPath, gcodePath, error=None):
if error:
eventManager().fire(Events.SLICING_FAILED, {"stl": self._getBasicFilename(stlPath), "gcode": self._getBasicFilename(gcodePath), "reason": error})
if os.path.exists(stlPath):
os.remove(stlPath)
else:
slicingStop = time.time()
eventManager().fire(Events.SLICING_DONE, {"stl": self._getBasicFilename(stlPath), "gcode": self._getBasicFilename(gcodePath), "time": slicingStop - slicingStart})
self.processGcode(gcodePath, destination, uploadCallback)
eventManager().fire(Events.SLICING_STARTED, {"stl": self._getBasicFilename(absolutePath), "gcode": self._getBasicFilename(gcodePath)})
cura.process_file(config, gcodePath, absolutePath, stlProcessed, [absolutePath, gcodePath])
return self._getBasicFilename(gcodePath)
def processGcode(self, absolutePath, destination, uploadCallback=None):
if absolutePath is None:
return None
filename = self._getBasicFilename(absolutePath)
if filename in self._metadata.keys():
# delete existing metadata entry, since the file is going to get overwritten
del self._metadata[filename]
self._metadataDirty = True
self._saveMetadata()
self._metadataAnalyzer.addFileToQueue(os.path.basename(absolutePath))
if uploadCallback is not None:
return uploadCallback(filename, absolutePath, destination)
else:
return filename
def getFutureFilename(self, file):
if not file:
return None
absolutePath = self.getAbsolutePath(file.filename, mustExist=False)
if absolutePath is None:
return None
return self._getBasicFilename(absolutePath)
def removeFile(self, filename):
filename = self._getBasicFilename(filename)
absolutePath = self.getAbsolutePath(filename)
stlPath = genStlFileName(absolutePath)
if absolutePath is None:
return
os.remove(absolutePath)
if os.path.exists(stlPath):
os.remove(stlPath)
self.removeFileFromMetadata(filename)
def removeFileFromMetadata(self, filename):
if filename in self._metadata.keys():
del self._metadata[filename]
self._metadataDirty = True
self._saveMetadata()
def getAbsolutePath(self, filename, mustExist=True):
"""
Returns the absolute path of the given filename in the correct upload folder.
Ensures that the file
<ul>
<li>has any of the extensions listed in SUPPORTED_EXTENSIONS</li>
<li>exists and is a file (not a directory) if "mustExist" is set to True</li>
</ul>
@param filename the name of the file for which to determine the absolute path
@param mustExist if set to true, the method also checks if the file exists and is a file
@return the absolute path of the file or None if the file is not valid
"""
filename = self._getBasicFilename(filename)
if not util.isAllowedFile(filename.lower(), set(SUPPORTED_EXTENSIONS)):
return None
# TODO: detect which type of file and add in the extra folder portion
secure = os.path.join(self._uploadFolder, secure_filename(self._getBasicFilename(filename)))
if mustExist and (not os.path.exists(secure) or not os.path.isfile(secure)):
return None
return secure
def getAllFilenames(self):
return map(lambda x: x["name"], self.getAllFileData())
def getAllFileData(self):
files = []
for osFile in os.listdir(self._uploadFolder):
fileData = self.getFileData(osFile)
if fileData is not None:
files.append(fileData)
return files
def getFileData(self, filename):
if not filename:
return
filename = self._getBasicFilename(filename)
# TODO: Make this more robust when STLs will be viewable from the client
if isSTLFileName(filename):
return
absolutePath = self.getAbsolutePath(filename)
if absolutePath is None:
return None
statResult = os.stat(absolutePath)
fileData = {
"name": filename,
"size": statResult.st_size,
"origin": FileDestinations.LOCAL,
"date": int(statResult.st_ctime)
}
# enrich with additional metadata from analysis if available
if filename in self._metadata.keys():
for key in self._metadata[filename].keys():
if key == "prints":
val = self._metadata[filename][key]
last = None
if "last" in val and val["last"] is not None:
last = {
"date": val["last"]["date"],
"success": val["last"]["success"]
}
if "lastPrintTime" in val["last"] and val["last"]["lastPrintTime"] is not None:
last["lastPrintTime"] = val["last"]["lastPrintTime"]
prints = {
"success": val["success"],
"failure": val["failure"],
"last": last
}
fileData["prints"] = prints
else:
fileData[key] = self._metadata[filename][key]
return fileData
def getFileMetadata(self, filename):
filename = self._getBasicFilename(filename)
if filename in self._metadata.keys():
return self._metadata[filename]
else:
return {
"prints": {
"success": 0,
"failure": 0,
"last": None
}
}
def setFileMetadata(self, filename, metadata):
filename = self._getBasicFilename(filename)
self._metadata[filename] = metadata
self._metadataDirty = True
#~~ print job data
def printSucceeded(self, filename, printTime):
filename = self._getBasicFilename(filename)
absolutePath = self.getAbsolutePath(filename)
if absolutePath is None:
return
metadata = self.getFileMetadata(filename)
metadata["prints"]["success"] += 1
metadata["prints"]["last"] = {
"date": time.time(),
"success": True
}
if printTime is not None:
metadata["prints"]["last"]["lastPrintTime"] = printTime
self.setFileMetadata(filename, metadata)
self._saveMetadata()
def printFailed(self, filename, printTime):
filename = self._getBasicFilename(filename)
absolutePath = self.getAbsolutePath(filename)
if absolutePath is None:
return
metadata = self.getFileMetadata(filename)
metadata["prints"]["failure"] += 1
metadata["prints"]["last"] = {
"date": time.time(),
"success": False
}
if printTime is not None:
metadata["prints"]["last"]["lastPrintTime"] = printTime
self.setFileMetadata(filename, metadata)
self._saveMetadata()
def changeLastPrintSuccess(self, filename, succeeded):
filename = self._getBasicFilename(filename)
absolutePath = self.getAbsolutePath(filename)
if absolutePath is None:
return
metadata = self.getFileMetadata(filename)
if metadata is None:
return
if "prints" in metadata.keys():
if "last" in metadata.keys() and metadata["prints"]["last"] is not None:
currentSucceeded = metadata["prints"]["last"]["success"]
if currentSucceeded != succeeded:
metadata["prints"]["last"]["success"] = succeeded
if currentSucceeded:
# last print job was counted as success but actually failed
metadata["prints"]["success"] -= 1
metadata["prints"]["failure"] += 1
else:
# last print job was counted as a failure but actually succeeded
metadata["prints"]["success"] += 1
metadata["prints"]["failure"] -= 1
self.setFileMetadata(filename, metadata)
self._saveMetadata()
#~~ analysis control
def pauseAnalysis(self):
self._metadataAnalyzer.pause()
def resumeAnalysis(self):
self._metadataAnalyzer.resume()
class MetadataAnalyzer:
def __init__(self, getPathCallback, loadedCallback):
self._logger = logging.getLogger(__name__)
self._getPathCallback = getPathCallback
self._loadedCallback = loadedCallback
self._active = threading.Event()
self._active.set()
self._currentFile = None
self._currentProgress = None
self._queue = Queue.PriorityQueue()
self._gcode = None
self._worker = threading.Thread(target=self._work)
self._worker.daemon = True
self._worker.start()
def addFileToQueue(self, filename):
self._logger.debug("Adding file %s to analysis queue (high priority)" % filename)
self._queue.put((0, filename))
def addFileToBacklog(self, filename):
self._logger.debug("Adding file %s to analysis backlog (low priority)" % filename)
self._queue.put((100, filename))
def working(self):
return self.isActive() and not (self._queue.empty() and self._currentFile is None)
def isActive(self):
return self._active.is_set()
def pause(self):
self._logger.debug("Pausing Gcode analyzer")
self._active.clear()
if self._gcode is not None:
self._logger.debug("Aborting running analysis, will restart when Gcode analyzer is resumed")
self._gcode.abort()
def resume(self):
self._logger.debug("Resuming Gcode analyzer")
self._active.set()
def _work(self):
aborted = None
while True:
if aborted is not None:
filename = aborted
aborted = None
self._logger.debug("Got an aborted analysis job for file %s, processing this instead of first item in queue" % filename)
else:
(priority, filename) = self._queue.get()
self._logger.debug("Processing file %s from queue (priority %d)" % (filename, priority))
self._active.wait()
try:
self._analyzeGcode(filename)
self._queue.task_done()
except gcodeInterpreter.AnalysisAborted:
aborted = filename
self._logger.debug("Running analysis of file %s aborted" % filename)
def _analyzeGcode(self, filename):
path = self._getPathCallback(filename)
if path is None or not os.path.exists(path):
return
self._currentFile = filename
self._currentProgress = 0
try:
self._logger.debug("Starting analysis of file %s" % filename)
eventManager().fire(Events.METADATA_ANALYSIS_STARTED, {"file": filename})
self._gcode = gcodeInterpreter.gcode()
self._gcode.progressCallback = self._onParsingProgress
self._gcode.load(path)
self._logger.debug("Analysis of file %s finished, notifying callback" % filename)
self._loadedCallback(self._currentFile, self._gcode)
finally:
self._gcode = None
self._currentProgress = None
self._currentFile = None
def _onParsingProgress(self, progress):
self._currentProgress = progress
+22 -3
View File
@@ -14,7 +14,7 @@ from octoprint.plugin.types import *
# singleton
_instance = None
def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_entry_points=None):
def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_entry_points=None, plugin_disabled_list=None):
global _instance
if _instance is None:
if init:
@@ -28,11 +28,18 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en
SimpleApiPlugin,
AssetPlugin,
BlueprintPlugin,
EventHandlerPlugin]
EventHandlerPlugin,
SlicerPlugin]
if plugin_entry_points is None:
plugin_entry_points = "octoprint.plugin"
if plugin_disabled_list is None:
all_plugin_settings = settings().get(["plugins"])
plugin_disabled_list = []
for key in all_plugin_settings:
if "enabled" in all_plugin_settings[key] and not all_plugin_settings[key]:
plugin_disabled_list.append(key)
_instance = PluginManager(plugin_folders, plugin_types, plugin_entry_points)
_instance = PluginManager(plugin_folders, plugin_types, plugin_entry_points, plugin_disabled_list=plugin_disabled_list)
else:
raise ValueError("Plugin Manager not initialized yet")
return _instance
@@ -111,6 +118,18 @@ class PluginSettings(object):
def globalGetBoolean(self, path):
return self.settings.getBoolean(path)
def globalSet(self, path, value):
self.settings.set(path, value)
def globalSetInt(self, path, value):
self.settings.setInt(path, value)
def globalSetFloat(self, path, value):
self.settings.setFloat(path, value)
def globalSetBoolean(self, path, value):
self.settings.setBoolean(path, value)
def __getattr__(self, item):
if item in self.access_methods and hasattr(self.settings, item) and callable(getattr(self.settings, item)):
orig_item = getattr(self.settings, item)
+26
View File
@@ -190,3 +190,29 @@ class EventHandlerPlugin(Plugin):
pass
class SlicerPlugin(Plugin):
def is_slicer_configured(self):
return False
def get_slicer_type(self):
return None
def get_slicer_name(self):
return None
def get_slicer_profile_options(self):
return None
def get_slicer_profile(self, path):
return None
def get_slicer_default_profile(self):
return None
def save_slicer_profile(self, path, profile, allow_overwrite=True, overrides=None):
pass
def do_slice(self, model_path, machinecode_path=None, profile_path=None):
pass
+266
View File
@@ -0,0 +1,266 @@
# coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import logging
import os
import flask
import octoprint.plugin
import octoprint.util
import octoprint.slicing
default_settings = {
"cura_engine": None,
"default_profile": None
}
s = octoprint.plugin.plugin_settings("cura", defaults=default_settings)
from .profile import Profile
blueprint = flask.Blueprint("plugin.cura", __name__)
@blueprint.route("/import", methods=["POST"])
def importCuraProfile():
import datetime
import tempfile
from octoprint.server import slicingManager
input_name = "file"
input_upload_name = input_name + "." + s.globalGet(["server", "uploads", "nameSuffix"])
input_upload_path = input_name + "." + s.globalGet(["server", "uploads", "pathSuffix"])
if input_upload_name in flask.request.values and input_upload_path in flask.request.values:
filename = flask.request.values[input_upload_name]
try:
profile_dict = Profile.from_cura_ini(flask.request.values[input_upload_path])
except Exception as e:
return flask.make_response("Something went wrong while converting imported profile: {message}".format(e.message), 500)
elif input_name in flask.request.files:
temp_file = tempfile.NamedTemporaryFile("wb", delete=False)
try:
temp_file.close()
upload = flask.request.files[input_name]
upload.save(temp_file.name)
profile_dict = Profile.from_cura_ini(temp_file.name)
except Exception as e:
return flask.make_response("Something went wrong while converting imported profile: {message}".format(e.message), 500)
finally:
os.remove(temp_file)
filename = upload.filename
else:
return flask.make_response("No file included", 400)
if profile_dict is None:
return flask.make_response("Could not convert Cura profile", 400)
name, _ = os.path.splitext(filename)
# default values for name, display name and description
profile_name = _sanitize_name(name)
profile_display_name = name
profile_description = "Imported from {filename} on {date}".format(filename=filename, date=octoprint.util.getFormattedDateTime(datetime.datetime.now()))
profile_allow_overwrite = False
# overrides
if "name" in flask.request.values:
profile_name = flask.request.values["name"]
if "displayName" in flask.request.values:
profile_display_name = flask.request.values["displayName"]
if "description" in flask.request.values:
profile_description = flask.request.values["description"]
if "allowOverwrite" in flask.request.values:
from octoprint.server.api import valid_boolean_trues
profile_allow_overwrite = flask.request.values["allowOverwrite"] in valid_boolean_trues
slicingManager.save_profile("cura",
profile_name,
profile_dict,
allow_overwrite=profile_allow_overwrite,
display_name=profile_display_name,
description=profile_description)
result = dict(
resource=flask.url_for("api.slicingGetSlicerProfile", slicer="cura", name=profile_name, _external=True),
displayName=profile_display_name,
description=profile_description
)
r = flask.make_response(flask.jsonify(result), 201)
r.headers["Location"] = result["resource"]
return r
class CuraPlugin(octoprint.plugin.SlicerPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.BlueprintPlugin):
def __init__(self):
self._logger = logging.getLogger("octoprint.plugins." + __name__)
##~~ BlueprintPlugin API
def get_blueprint(self):
global blueprint
return blueprint
##~~ AssetPlugin API
def get_asset_folder(self):
import os
return os.path.join(os.path.dirname(os.path.realpath(__file__)), "static")
def get_assets(self):
return {
"js": ["js/cura.js"],
"less": ["less/cura.less"],
"css": ["css/cura.css"]
}
##~~ SettingsPlugin API
def on_settings_load(self):
return dict(
cura_engine=s.get(["cura_engine"]),
default_profile=s.get(["default_profile"])
)
def on_settings_save(self, data):
if "cura_engine" in data and data["cura_engine"]:
s.set(["cura_engine"], data["cura_engine"])
if "default_profile" in data and data["default_profile"]:
s.set(["default_profile"], data["default_profile"])
##~~ TemplatePlugin API
def get_template_vars(self):
return dict(
_settings_menu_entry="Cura"
)
def get_template_folder(self):
import os
return os.path.join(os.path.dirname(os.path.realpath(__file__)), "templates")
##~~ SlicerPlugin API
def is_slicer_configured(self):
cura_engine = s.get(["cura_engine"])
return cura_engine is not None and os.path.exists(cura_engine)
def get_slicer_type(self):
return "cura"
def get_slicer_name(self):
return "CuraEngine"
def get_slicer_default_profile(self):
path = s.get(["default_profile"])
if not path:
path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "profiles", "default.profile.yaml")
return self.get_slicer_profile(path)
def get_slicer_profile(self, path):
profile_dict = self._load_profile(path)
display_name = None
description = None
if "_display_name" in profile_dict:
display_name = profile_dict["_display_name"]
del profile_dict["_display_name"]
if "_description" in profile_dict:
description = profile_dict["_description"]
del profile_dict["_description"]
return octoprint.slicing.SlicingProfile(self.get_slicer_type(), "unknown", profile_dict, display_name=display_name, description=description)
def save_slicer_profile(self, path, profile, allow_overwrite=True, overrides=None):
new_profile = Profile.merge_profile(profile.data, overrides=overrides)
if profile.display_name is not None:
new_profile["_display_name"] = profile.display_name
if profile.description is not None:
new_profile["_description"] = profile.description
self._save_profile(path, new_profile, allow_overwrite=allow_overwrite)
def do_slice(self, model_path, machinecode_path=None, profile_path=None):
if not profile_path:
profile_path = s.get(["default_profile"])
if not machinecode_path:
path, _ = os.path.splitext(model_path)
machinecode_path = path + ".gco"
engine_settings = self._convert_to_engine(profile_path)
executable = s.get(["cura_engine"])
if not executable:
return False, "Path to CuraEngine is not configured "
working_dir, _ = os.path.split(executable)
args = ['"%s"' % executable, '-v', '-p']
for k, v in engine_settings.items():
args += ["-s", '"%s=%s"' % (k, str(v))]
args += ['-o', '"%s"' % machinecode_path, '"%s"' % model_path]
import sarge
command = " ".join(args)
self._logger.info("Running %r in %s" % (command, working_dir))
try:
p = sarge.run(command, cwd=working_dir)
if p.returncode == 0:
return True, None
else:
self._logger.warn("Could not slice via Cura, got return code %r" % p.returncode)
return False, "Got returncode %r" % p.returncode
except:
self._logger.exception("Could not slice via Cura, got an unknown error")
return False, "Unknown error, please consult the log file"
def _load_profile(self, path):
import yaml
profile_dict = dict()
with open(path, "r") as f:
try:
profile_dict = yaml.safe_load(f)
except:
raise IOError("Couldn't read profile from {path}".format(path=path))
return profile_dict
def _save_profile(self, path, profile, allow_overwrite=True):
if not allow_overwrite and os.path.exists(path):
raise IOError("Cannot overwrite {path}".format(path=path))
import yaml
with open(path, "wb") as f:
yaml.safe_dump(profile, f, default_flow_style=False, indent=" ", allow_unicode=True)
def _convert_to_engine(self, profile_path):
profile = Profile(self._load_profile(profile_path))
return profile.convert_to_engine()
def _sanitize_name(name):
if name is None:
return None
if "/" in name or "\\" in name:
raise ValueError("name must not contain / or \\")
import string
valid_chars = "-_.() {ascii}{digits}".format(ascii=string.ascii_letters, digits=string.digits)
sanitized_name = ''.join(c for c in name if c in valid_chars)
sanitized_name = sanitized_name.replace(" ", "_")
return sanitized_name.lower()
__plugin_name__ = "cura"
__plugin_version__ = "0.1"
__plugin_implementations__ = [CuraPlugin()]
+937
View File
@@ -0,0 +1,937 @@
# coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
from . import s
import re
class SupportLocationTypes(object):
NONE = "none"
TOUCHING_BUILDPLATE = "buildplate"
EVERYWHERE = "everywhere"
class SupportDualTypes(object):
BOTH = "both"
FIRST = "first"
SECOND = "second"
class SupportTypes(object):
GRID = "grid"
LINES = "lines"
class PlatformAdhesionTypes(object):
NONE = "none"
BRIM = "brim"
RAFT = "raft"
class MachineShapeTypes(object):
SQUARE = "square"
CIRCULAR = "circular"
class GcodeFlavors(object):
REPRAP = "reprap"
REPRAP_VOLUME = "reprap_volume"
ULTIGCODE = "ultigcode"
MAKERBOT = "makerbot"
BFB = "bfb"
MACH3 = "mach3"
defaults = dict(
layer_height=0.1,
wall_thickness=0.8,
solid_layer_thickness=0.6,
nozzle_size=0.4,
print_temperature=[220, 0, 0, 0],
print_bed_temperature=70,
platform_adhesion=PlatformAdhesionTypes.NONE,
filament_diameter=[2.85, 0, 0, 0],
filament_flow=100.0,
bottom_thickness=0.3,
first_layer_width_factor=100.0,
object_sink=0.0,
fill_density=20,
solid_top=True,
solid_bottom=True,
fill_overlap=15,
# speeds
print_speed=50.0,
travel_speed=150.0,
bottom_layer_speed=20.0,
infill_speed=0.0,
outer_shell_speed=0.0,
inner_shell_speed=0.0,
# dual extrusion
overlap_dual=0.15,
wipe_tower=False,
wipe_tower_volume=15,
ooze_shield=False,
# retraction
retraction_enable=True,
retraction_speed=40.0,
retraction_amount=4.5,
retraction_dual_amount=16.5,
retraction_min_travel=1.5,
retraction_combing=True,
retraction_minimal_extrusion=0.02,
retraction_hop=0.0,
# cooling
cool_min_layer_time=5,
fan_enabled=True,
fan_full_height=0.5,
fan_speed=100,
fan_speed_max=100,
cool_min_feedrate=10,
cool_head_lift=False,
# support
support=SupportLocationTypes.NONE,
support_type=SupportTypes.GRID,
support_angle=60.0,
support_fill_rate=15,
support_xy_distance=0.7,
support_z_distance=0.15,
support_dual_extrusion=SupportDualTypes.BOTH,
# platform adhesion
skirt_line_count=1,
skirt_gap=3.0,
skirt_minimal_length=150.0,
brim_line_count=20,
raft_margin=5.0,
raft_line_spacing=3.0,
raft_base_thickness=0.3,
raft_base_linewidth=1.0,
raft_interface_thickness=0.27,
raft_interface_linewidth=0.4,
raft_airgap=0.22,
raft_surface_layers=2,
# repairing
fix_horrible_union_all_type_a=True,
fix_horrible_union_all_type_b=False,
fix_horrible_use_open_bits=False,
fix_horrible_extensive_stitching=False,
# extras
spiralize=False,
follow_surface=False,
machine_width=205,
machine_depth=205,
machine_center_is_zero=False,
has_heated_bed=False,
gcode_flavor=GcodeFlavors.REPRAP,
extruder_amount=1,
steps_per_e=0,
start_gcode=[
# 1 extruder
""";Sliced at: {day} {date} {time}
;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density}
;M190 S{print_bed_temperature} ;Uncomment to add your own bed temperature line
;M109 S{print_temperature} ;Uncomment to add your own temperature line
G21 ;metric values
G90 ;absolute positioning
M82 ;set extruder to absolute mode
M107 ;start with the fan off
G28 X0 Y0 ;move X/Y to min endstops
G28 Z0 ;move Z to min endstops
G1 Z15.0 F{travel_speed} ;move the platform down 15mm
G92 E0 ;zero the extruded length
G1 F200 E3 ;extrude 3mm of feed stock
G92 E0 ;zero the extruded length again
G1 F{travel_speed}
;Put printing message on LCD screen
M117 Printing...
""",
# 2 extruders
""";Sliced at: {day} {date} {time}
;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density}
;M190 S{print_bed_temperature} ;Uncomment to add your own bed temperature line
;M104 S{print_temperature} ;Uncomment to add your own temperature line
;M109 T1 S{print_temperature2} ;Uncomment to add your own temperature line
;M109 T0 S{print_temperature} ;Uncomment to add your own temperature line
G21 ;metric values
G90 ;absolute positioning
M107 ;start with the fan off
G28 X0 Y0 ;move X/Y to min endstops
G28 Z0 ;move Z to min endstops
G1 Z15.0 F{travel_speed} ;move the platform down 15mm
T1 ;Switch to the 2nd extruder
G92 E0 ;zero the extruded length
G1 F200 E10 ;extrude 10mm of feed stock
G92 E0 ;zero the extruded length again
G1 F200 E-{retraction_dual_amount}
T0 ;Switch to the first extruder
G92 E0 ;zero the extruded length
G1 F200 E10 ;extrude 10mm of feed stock
G92 E0 ;zero the extruded length again
G1 F{travel_speed}
;Put printing message on LCD screen
M117 Printing...
""",
# 3 extruders
""";Sliced at: {day} {date} {time}
;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density}
;M190 S{print_bed_temperature} ;Uncomment to add your own bed temperature line
;M104 S{print_temperature} ;Uncomment to add your own temperature line
;M109 T1 S{print_temperature2} ;Uncomment to add your own temperature line
;M109 T0 S{print_temperature} ;Uncomment to add your own temperature line
G21 ;metric values
G90 ;absolute positioning
M107 ;start with the fan off
G28 X0 Y0 ;move X/Y to min endstops
G28 Z0 ;move Z to min endstops
G1 Z15.0 F{travel_speed} ;move the platform down 15mm
T2 ;Switch to the 2nd extruder
G92 E0 ;zero the extruded length
G1 F200 E10 ;extrude 10mm of feed stock
G92 E0 ;zero the extruded length again
G1 F200 E-{retraction_dual_amount}
T1 ;Switch to the 2nd extruder
G92 E0 ;zero the extruded length
G1 F200 E10 ;extrude 10mm of feed stock
G92 E0 ;zero the extruded length again
G1 F200 E-{retraction_dual_amount}
T0 ;Switch to the first extruder
G92 E0 ;zero the extruded length
G1 F200 E10 ;extrude 10mm of feed stock
G92 E0 ;zero the extruded length again
G1 F{travel_speed}
;Put printing message on LCD screen
M117 Printing...
""",
# 4 extruders
""";Sliced at: {day} {date} {time}
;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density}
;M190 S{print_bed_temperature} ;Uncomment to add your own bed temperature line
;M104 S{print_temperature} ;Uncomment to add your own temperature line
;M109 T2 S{print_temperature2} ;Uncomment to add your own temperature line
;M109 T1 S{print_temperature2} ;Uncomment to add your own temperature line
;M109 T0 S{print_temperature} ;Uncomment to add your own temperature line
G21 ;metric values
G90 ;absolute positioning
M107 ;start with the fan off
G28 X0 Y0 ;move X/Y to min endstops
G28 Z0 ;move Z to min endstops
G1 Z15.0 F{travel_speed} ;move the platform down 15mm
T3 ;Switch to the 4th extruder
G92 E0 ;zero the extruded length
G1 F200 E10 ;extrude 10mm of feed stock
G92 E0 ;zero the extruded length again
G1 F200 E-{retraction_dual_amount}
T2 ;Switch to the 3th extruder
G92 E0 ;zero the extruded length
G1 F200 E10 ;extrude 10mm of feed stock
G92 E0 ;zero the extruded length again
G1 F200 E-{retraction_dual_amount}
T1 ;Switch to the 2nd extruder
G92 E0 ;zero the extruded length
G1 F200 E10 ;extrude 10mm of feed stock
G92 E0 ;zero the extruded length again
G1 F200 E-{retraction_dual_amount}
T0 ;Switch to the first extruder
G92 E0 ;zero the extruded length
G1 F200 E10 ;extrude 10mm of feed stock
G92 E0 ;zero the extruded length again
G1 F{travel_speed}
;Put printing message on LCD screen
M117 Printing...
"""
],
end_gcode=[
# 1 extruder
""";End GCode
M104 S0 ;extruder heater off
M140 S0 ;heated bed heater off (if you have it)
G91 ;relative positioning
G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure
G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more
G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way
M84 ;steppers off
G90 ;absolute positioning
;{profile_string}
""",
# 2 extruders
""";End GCode
M104 T0 S0 ;extruder heater off
M104 T1 S0 ;extruder heater off
M140 S0 ;heated bed heater off (if you have it)
G91 ;relative positioning
G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure
G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more
G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way
M84 ;steppers off
G90 ;absolute positioning
;{profile_string}
""",
# 3 extruders
""";End GCode
M104 T0 S0 ;extruder heater off
M104 T1 S0 ;extruder heater off
M104 T2 S0 ;extruder heater off
M140 S0 ;heated bed heater off (if you have it)
G91 ;relative positioning
G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure
G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more
G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way
M84 ;steppers off
G90 ;absolute positioning
;{profile_string}
""",
# 4 extruders
""";End GCode
M104 T0 S0 ;extruder heater off
M104 T1 S0 ;extruder heater off
M104 T2 S0 ;extruder heater off
M104 T3 S0 ;extruder heater off
M140 S0 ;heated bed heater off (if you have it)
G91 ;relative positioning
G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure
G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more
G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way
M84 ;steppers off
G90 ;absolute positioning
;{profile_string}
"""
],
preSwitchExtruder_gcode=""";Switch between the current extruder and the next extruder, when printing with multiple extruders.
;This code is added before the T(n)
""",
postSwitchExtruder_gcode=""";Switch between the current extruder and the next extruder, when printing with multiple extruders.
;This code is added after the T(n)
"""
)
class Profile(object):
regex_extruder_offset = re.compile("extruder_offset_([xy])(\d)")
regex_filament_diameter = re.compile("filament_diameter(\d?)")
regex_print_temperature = re.compile("print_temperature(\d?)")
regex_strip_comments = re.compile(";.*$", flags=re.MULTILINE)
@classmethod
def from_cura_ini(cls, path):
import os
if not os.path.exists(path) or not os.path.isfile(path):
return None
import ConfigParser
config = ConfigParser.ConfigParser()
try:
config.read(path)
except:
return None
arrayified_options = ["print_temperature", "filament_diameter", "start.gcode", "end.gcode"]
translated_options = dict(
inset0_speed="outer_shell_speed",
insetx_speed="inner_shell_speed",
layer0_width_factor="first_layer_width_factor",
simple_mode="follow_surface",
)
translated_options["start.gcode"] = "start_gcode"
translated_options["end.gcode"] = "end_gcode"
value_conversions = dict(
platform_adhesion={
"None": PlatformAdhesionTypes.NONE,
"Brim": PlatformAdhesionTypes.BRIM,
"Raft": PlatformAdhesionTypes.RAFT
},
support={
"None": SupportLocationTypes.NONE,
"Touching buildplate": SupportLocationTypes.TOUCHING_BUILDPLATE,
"Everywhere": SupportLocationTypes.EVERYWHERE
},
support_type={
"Lines": SupportTypes.LINES,
"Grid": SupportTypes.GRID
},
support_dual_extrusion={
"Both": SupportDualTypes.BOTH,
"First extruder": SupportDualTypes.FIRST,
"Second extruder": SupportDualTypes.SECOND
}
)
result = dict()
for section in config.sections():
if not section in ("profile", "alterations"):
continue
for option in config.options(section):
ignored = False
key = option
# try to fetch the value in the correct type
try:
value = config.getboolean(section, option)
except:
# no boolean, try int
try:
value = config.getint(section, option)
except:
# no int, try float
try:
value = config.getfloat(section, option)
except:
# no float, use str
value = config.get(section, option)
index = None
for opt in arrayified_options:
if key.startswith(opt):
if key == opt:
index = 0
else:
try:
# try to convert the target index, e.g. print_temperature2 => print_temperature[1]
index = int(key[len(opt):]) - 1
except ValueError:
# ignore entries for which that fails
ignored = True
key = opt
break
if ignored:
continue
if key in translated_options:
# if the key has to be translated to a new value, do that now
key = translated_options[key]
if key in value_conversions and value in value_conversions[key]:
value = value_conversions[key][value]
if index is not None:
# if we have an array to fill, make sure the target array exists and has the right size
if not key in result:
result[key] = []
if len(result[key]) <= index:
for n in xrange(index - len(result[key]) + 1):
result[key].append(None)
result[key][index] = value
else:
# just set the value if there's no array to fill
result[key] = value
# merge it with our default settings, the imported profile settings taking precedence
return cls.merge_profile(result)
@classmethod
def merge_profile(cls, profile, overrides=None):
import copy
result = copy.deepcopy(defaults)
for k in result.keys():
profile_value = None
override_value = None
if k in profile:
profile_value = profile[k]
if overrides and k in overrides:
override_value = overrides[k]
if profile_value is None and override_value is None:
# neither override nor profile, no need to handle this key further
continue
if k in ("filament_diameter", "print_temperature", "start_gcode", "end_gcode"):
# the array fields need some special treatment. Basically something like this:
#
# override_value: [None, "b"]
# profile_value : ["a" , None, "c"]
# default_value : ["d" , "e" , "f", "g"]
#
# should merge to something like this:
#
# ["a" , "b" , "c", "g"]
#
# So override > profile > default, if neither override nor profile value are available
# the default value should just be left as is
for x in xrange(len(result[k])):
if override_value is not None and x < len(override_value) and override_value[x] is not None:
# we have an override value for this location, so we use it
result[k][x] = override_value[x]
elif profile_value is not None and x < len(profile_value) and profile_value[x] is not None:
# we have a profile value for this location, so we use it
result[k][x] = profile_value[x]
else:
# just change the result value to the override_value if available, otherwise to the profile_value if
# that is given, else just leave as is
if override_value is not None:
result[k] = override_value
elif profile_value is not None:
result[k] = profile_value
return result
def __init__(self, profile):
self.profile = profile
def get(self, key):
if key in ("machine_width", "machine_depth", "machine_center_is_zero"):
bedDimensions = s.globalGet(["printerParameters", "bedDimensions"])
circular = bedDimensions["circular"]
if key == "machine_width":
return bedDimensions["radius"] * 2 if circular else bedDimensions["x"]
elif key == "machine_depth":
return bedDimensions["radius"] * 2 if circular else bedDimensions["y"]
elif key == "machine_center_is_zero":
return circular
else:
return None
elif key == "extruder_amount":
return s.globalGetInt(["printerParameters", "numExtruders"])
elif key.startswith("extruder_offset_"):
extruder_offsets = s.globalGet(["printerParameters", "extruderOffsets"])
match = Profile.regex_extruder_offset.match(key)
if not match:
return 0.0
axis, number = match.groups()
axis = axis.lower()
number = int(number)
if not axis in ("x", "y"):
return 0.0
if number >= len(extruder_offsets):
return 0.0
if not axis in extruder_offsets[number]:
return 0.0
return extruder_offsets[number][axis]
elif key.startswith("filament_diameter"):
match = Profile.regex_filament_diameter.match(key)
if not match:
return 0.0
diameters = defaults["filament_diameter"]
if not match.group(1):
return diameters[0]
index = int(match.group(1))
if index >= len(diameters):
return 0.0
return diameters[index]
elif key.startswith("print_temperature"):
match = Profile.regex_print_temperature.match(key)
if not match:
return 0.0
temperatures = defaults["print_temperature"]
if not match.group(1):
return temperatures[0]
index = int(match.group(1))
if index >= len(temperatures):
return 0.0
return temperatures[index]
else:
if key in self.profile:
return self.profile[key]
elif key in defaults:
return defaults[key]
else:
return None
def get_int(self, key, default=None):
value = self.get(key)
if value is None:
return default
try:
return int(value)
except ValueError:
return default
def get_float(self, key, default=None):
value = self.get(key)
if value is None:
return default
if isinstance(value, (str, unicode, basestring)):
value = value.replace(",", ".").strip()
try:
return float(value)
except ValueError:
return default
def get_boolean(self, key, default=None):
value = self.get(key)
if value is None:
return default
if isinstance(value, bool):
return value
elif isinstance(value, (str, unicode, basestring)):
return value.lower() == "true" or value.lower() == "yes" or value.lower() == "on" or value == "1"
elif isinstance(value, (int, float)):
return value > 0
else:
return value == True
def get_microns(self, key, default=None):
value = self.get_float(key, default=None)
if value is None:
return default
return int(value * 1000)
def get_gcode_template(self, key):
extruder_count = s.globalGetInt(["printerParameters", "numExtruders"])
if key in self.profile:
gcode = self.profile[key]
else:
gcode = defaults[key]
if key in ("start_gcode", "end_gcode"):
return gcode[extruder_count-1]
else:
return gcode
def get_machine_extruder_offset(self, extruder, axis):
extruder_offsets = s.globalGet(["printerParameters", "extruderOffsets"])
if extruder >= len(extruder_offsets):
return 0.0
if axis.lower() not in ("x", "y"):
return 0.0
return extruder_offsets[extruder][axis.lower()]
def get_profile_string(self):
import base64
import zlib
import copy
profile = copy.deepcopy(defaults)
profile.update(self.profile)
for key in ("print_temperature", "print_temperature2", "print_temperature3", "print_temperature4",
"filament_diameter", "filament_diameter2", "filament_diameter3", "filament_diameter4"):
profile[key] = self.get(key)
result = []
for k, v in profile.items():
if isinstance(v, (str, unicode)):
result.append("{k}={v}".format(k=k, v=v.encode("utf-8")))
else:
result.append("{k}={v}".format(k=k, v=v))
return base64.b64encode(zlib.compress("\b".join(result), 9))
def replaceTagMatch(self, m):
import time
pre = m.group(1)
tag = m.group(2)
if tag == 'time':
return pre + time.strftime('%H:%M:%S')
if tag == 'date':
return pre + time.strftime('%d-%m-%Y')
if tag == 'day':
return pre + ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][int(time.strftime('%w'))]
if tag == 'profile_string':
return pre + 'CURA_OCTO_PROFILE_STRING:%s' % (self.get_profile_string())
if pre == 'F' and tag == 'max_z_speed':
f = self.get_float("travel_speed") * 60
elif pre == 'F' and tag in ['print_speed', 'retraction_speed', 'travel_speed', 'bottom_layer_speed', 'cool_min_feedrate']:
f = self.get_float(tag) * 60
elif self.get(tag):
f = self.get(tag)
else:
return '%s?%s?' % (pre, tag)
if (f % 1) == 0:
return pre + str(int(f))
return pre + str(f)
def get_gcode(self, key):
extruder_count = s.globalGetInt(["printerParameters", "numExtruders"])
prefix = ""
postfix = ""
if self.get("gcode_flavor") == GcodeFlavors.ULTIGCODE:
if key == "end_gcode":
return "M25 ;Stop reading from this point on.\n;CURA_PROFILE_STRING:%s\n" % (self.get_profile_string())
return ""
if key == "start_gcode":
contents = self.get_gcode_template("start_gcode")
e_steps = self.get_float("steps_per_e")
if e_steps > 0:
prefix += "M92 E{e_steps}\n" % (e_steps)
temp = self.get_float("print_temperature")
bedTemp = 0
if self.get_boolean("has_heated_bed"):
bedTemp = self.get_float("print_bed_temperature")
include_bed_temps = bedTemp > 0 and not "{print_bed_temperature}" in Profile.regex_strip_comments.sub("", contents)
if include_bed_temps:
prefix += "M140 S{print_bed_temperature}\n"
if temp > 0 and not "{print_temperature}" in Profile.regex_strip_comments.sub("", contents):
if extruder_count > 0:
def temp_line(temp, extruder, template):
t = temp
if extruder > 0:
print_temp = self.get_float("print_temperature%d" % (extruder + 1))
if print_temp > 0:
t = print_temp
return template.format(extruder=extruder, temp=t)
for n in xrange(1, extruder_count):
prefix += temp_line(temp, n, "M104 T{extruder} S{temp}\n")
for n in xrange(0, extruder_count):
prefix += temp_line(temp, n, "M109 T{extruder} S{temp}\n")
prefix += "T0\n"
else:
prefix += "M109 S{temp}\n".format(temp=temp)
if include_bed_temps:
prefix += "M190 S{print_bed_temperature}\n".format(bedTemp=bedTemp)
else:
contents = self.get_gcode_template(key)
return unicode(prefix + re.sub("(.)\{([^\}]*)\}", self.replaceTagMatch, contents).rstrip() + '\n' + postfix).strip().encode('utf-8') + '\n'
def calculate_edge_width_and_line_count(self):
wall_thickness = self.get_float("wall_thickness")
nozzle_size = self.get_float("nozzle_size")
if self.get_boolean("spiralize") or self.get_boolean("follow_surface"):
return wall_thickness, 1
if wall_thickness < 0.01:
return nozzle_size, 0
if wall_thickness < nozzle_size:
return wall_thickness, 1
edge_width = None
line_count = int(wall_thickness / (nozzle_size - 0.0001))
if line_count < 1:
edge_width = nozzle_size
line_count = 1
line_width = wall_thickness / line_count
line_width_alt = wall_thickness / (line_count + 1)
if line_width > nozzle_size * 1.5:
return line_width_alt, line_count + 1
if not edge_width:
edge_width = line_width
return edge_width, line_count
def calculate_solid_layer_count(self):
layer_height = self.get_float("layer_height")
solid_thickness = self.get_float("solid_layer_thickness")
if layer_height == 0.0:
return 1
import math
return int(math.ceil(solid_thickness / (layer_height - 0.0001)))
def calculate_minimal_extruder_count(self):
extruder_count = s.globalGetInt(["printerParameters", "numExtruders"])
if extruder_count < 2:
return 1
if self.get("support") == SupportLocationTypes.NONE:
return 1
if self.get("support_dual_extrusion") == SupportDualTypes.SECOND:
return 2
return 1
def convert_to_engine(self):
edge_width, line_count = self.calculate_edge_width_and_line_count()
solid_layer_count = self.calculate_solid_layer_count()
extruder_count = s.globalGetInt(["printerParameters", "numExtruders"])
minimal_extruder_count = self.calculate_minimal_extruder_count()
settings = {
"layerThickness": self.get_microns("layer_height"),
"initialLayerThickness": self.get_microns("bottom_thickness") if self.get_float("bottom_thickness") > 0.0 else self.get_microns("layer_height"),
"filamentDiameter": self.get_microns("filament_diameter"),
"filamentFlow": self.get_int("filament_flow"),
"extrusionWidth": edge_width * 1000,
"layer0extrusionWidth": int(edge_width * self.get_float("first_layer_width_factor") / 100 * 1000),
"insetCount": line_count,
"downSkinCount": solid_layer_count if self.get_boolean("solid_bottom") else 0,
"upSkinCount": solid_layer_count if self.get_boolean("solid_top") else 0,
"infillOverlap": self.get_int("fill_overlap"),
"initialSpeedupLayers": int(4),
"initialLayerSpeed": self.get_int("bottom_layer_speed"),
"printSpeed": self.get_int("print_speed"),
"infillSpeed": self.get_int("infill_speed") if self.get_int("infill_speed") > 0 else self.get_int("print_speed"),
"inset0Speed": self.get_int("outer_shell_speed") if self.get_int("outer_shell_speed") > 0 else self.get_int("print_speed"),
"insetXSpeed": self.get_int("inner_shell_speed") if self.get_int("inner_shell_speed") > 0 else self.get_int("print_speed"),
"moveSpeed": self.get_int("travel_speed"),
"fanSpeedMin": self.get_int("fan_speed") if self.get_boolean("fan_enabled") else 0,
"fanSpeedMax": self.get_int("fan_speed_max") if self.get_boolean("fan_enabled") else 0,
"supportAngle": int(-1) if self.get("support") == SupportLocationTypes.NONE else self.get_int("support_angle"),
"supportEverywhere": int(1) if self.get("support") == SupportLocationTypes.EVERYWHERE else int(0),
"supportLineDistance": int(100 * edge_width * 1000 / self.get_float("support_fill_rate")) if self.get_float("support_fill_rate") > 0 else -1,
"supportXYDistance": int(1000 * self.get_float("support_xy_distance")),
"supportZDistance": int(1000 * self.get_float("support_z_distance")),
"supportExtruder": 0 if self.get("support_dual_extrusion") == SupportDualTypes.FIRST else (1 if self.get("support_dual_extrusion") == SupportDualTypes.SECOND and minimal_extruder_count > 1 else -1),
"retractionAmount": self.get_microns("retraction_amount") if self.get_boolean("retraction_enable") else 0,
"retractionSpeed": self.get_int("retraction_speed"),
"retractionMinimalDistance": self.get_microns("retraction_min_travel"),
"retractionAmountExtruderSwitch": self.get_microns("retraction_dual_amount"),
"retractionZHop": self.get_microns("retraction_hop"),
"minimalExtrusionBeforeRetraction": self.get_microns("retraction_minimal_extrusion"),
"enableCombing": 1 if self.get_boolean("retraction_combing") else 0,
"multiVolumeOverlap": self.get_microns("overlap_dual"),
"objectSink": max(0, self.get_microns("object_sink")),
"minimalLayerTime": self.get_int("cool_min_layer_time"),
"minimalFeedrate": self.get_int("cool_min_feedrate"),
"coolHeadLift": 1 if self.get_boolean("cool_head_lift") else 0,
# model positioning
"posx": int(self.get_float("machine_width") / 2.0 * 1000) if not self.get_boolean("machine_center_is_zero") else 0.0,
"posy": int(self.get_float("machine_depth") / 2.0 * 1000) if not self.get_boolean("machine_center_is_zero") else 0.0,
# gcodes
"startCode": self.get_gcode("start_gcode"),
"endCode": self.get_gcode("end_gcode"),
"preSwitchExtruderCode": self.get_gcode("preSwitchExtruder_gcode"),
"postSwitchExtruderCode": self.get_gcode("postSwitchExtruder_gcode"),
# fixing
"fixHorrible": 0,
}
for extruder in range(1, extruder_count):
for axis in ("x", "y"):
settings["extruderOffset[{extruder}].{axis}".format(extruder=extruder, axis=axis.upper())] = self.get_machine_extruder_offset(extruder, axis)
fanFullHeight = self.get_microns("fan_full_height")
settings["fanFullOnLayerNr"] = (fanFullHeight - settings["initialLayerThickness"] - 1) / settings["layerThickness"] + 1
if settings["fanFullOnLayerNr"] < 0:
settings["fanFullOnLayerNr"] = 0
if self.get("support_type") == SupportTypes.LINES:
settings["supportType"] = 1
# infill
if self.get_float("fill_density") == 0:
settings["sparseInfillLineDistance"] = -1
elif self.get_float("fill_density") == 100:
settings["sparseInfillLineDistance"] = settings["extrusionWidth"]
settings["downSkinCount"] = 10000
settings["upSkinCount"] = 10000
else:
settings["sparseInfillLineDistance"] = int(100 * edge_width * 1000 / self.get_float("fill_density"))
# brim/raft/skirt
if self.get("platform_adhesion") == PlatformAdhesionTypes.BRIM:
settings["skirtDistance"] = 0
settings["skirtLineCount"] = self.get_int("brim_line_count")
elif self.get("platform_adhesion") == PlatformAdhesionTypes.RAFT:
settings["skirtDistance"] = 0
settings["skirtLineCount"] = 0
settings["raftMargin"] = self.get_microns("raft_margin")
settings["raftLineSpacing"] = self.get_microns("raft_line_spacing")
settings["raftBaseThickness"] = self.get_microns("raft_base_thickness")
settings["raftBaseLinewidth"] = self.get_microns("raft_base_linewidth")
settings["raftInterfaceThickness"] = self.get_microns("raft_interface_thickness")
settings["raftInterfaceLinewidth"] = self.get_microns("raft_interface_linewidth")
settings["raftInterfaceLineSpacing"] = self.get_microns("raft_interface_linewidth") * 2
settings["raftAirGapLayer0"] = self.get_microns("raft_airgap")
settings["raftBaseSpeed"] = self.get_int("bottom_layer_speed")
settings["raftFanSpeed"] = 100
settings["raftSurfaceThickness"] = settings["raftInterfaceThickness"]
settings["raftSurfaceLinewidth"] = int(edge_width * 1000)
settings["raftSurfaceLineSpacing"] = int(edge_width * 1000 * 0.9)
settings["raftSurfaceLayers"] = self.get_int("raft_surface_layers")
settings["raftSurfaceSpeed"] = self.get_int("bottom_layer_speed")
else:
settings["skirtDistance"] = self.get_microns("skirt_gap")
settings["skirtLineCount"] = self.get_int("skirt_line_count")
settings["skirtMinLength"] = self.get_microns("skirt_minimal_length")
# fixing
if self.get_boolean("fix_horrible_union_all_type_a"):
settings["fixHorrible"] |= 0x01
if self.get_boolean("fix_horrible_union_all_type_b"):
settings["fixHorrible"] |= 0x02
if self.get_boolean("fix_horrible_use_open_bits"):
settings["fixHorrible"] |= 0x10
if self.get_boolean("fix_horrible_extensive_stitching"):
settings["fixHorrible"] |= 0x04
if settings["layerThickness"] <= 0:
settings["layerThickness"] = 1000
# gcode flavor
if self.get("gcode_flavor") == GcodeFlavors.ULTIGCODE:
settings["gcodeFlavor"] = 1
elif self.get("gcode_flavor") == GcodeFlavors.MAKERBOT:
settings["gcodeFlavor"] = 2
elif self.get("gcode_flavor") == GcodeFlavors.BFB:
settings["gcodeFlavor"] = 3
elif self.get("gcode_flavor") == GcodeFlavors.MACH3:
settings["gcodeFlavor"] = 4
elif self.get("gcode_flavor") == GcodeFlavors.REPRAP_VOLUME:
settings["gcodeFlavor"] = 5
# extras
if self.get_boolean("spiralize"):
settings["spiralizeMode"] = 1
if self.get_boolean("follow_surface"):
settings["simpleMode"] = 1
# dual extrusion
if self.get_boolean("wipe_tower") and extruder_count > 1:
import math
settings["wipeTowerSize"] = int(math.sqrt(self.get_float("wipe_tower_volume") * 1000 * 1000 * 1000 / settings["layerThickness"]))
if self.get_boolean("ooze_shield"):
settings["enableOozeShield"] = 1
return settings
@@ -0,0 +1,4 @@
layer_height: 0.2
print_temperature:
- 220.0
- 220.0
@@ -0,0 +1 @@
table th.settings_plugin_cura_profiles_key,table td.settings_plugin_cura_profiles_key{text-overflow:ellipsis;text-align:left;width:200px}table th.settings_plugin_cura_profiles_name,table td.settings_plugin_cura_profiles_name{text-overflow:ellipsis;text-align:left}table th.settings_plugin_cura_profiles_actions,table td.settings_plugin_cura_profiles_actions{text-align:center;width:100px}table th.settings_plugin_cura_profiles_actions a,table td.settings_plugin_cura_profiles_actions a{text-decoration:none;color:#000}table th.settings_plugin_cura_profiles_actions a.disabled,table td.settings_plugin_cura_profiles_actions a.disabled{color:#ccc;cursor:default}
@@ -0,0 +1,188 @@
$(function() {
function CuraViewModel(parameters) {
var self = this;
self.loginState = parameters[0];
self.settingsViewModel = parameters[1];
self.fileName = ko.observable();
self.placeholderName = ko.observable();
self.placeholderDisplayName = ko.observable();
self.placeholderDescription = ko.observable();
self.profileName = ko.observable();
self.profileDisplayName = ko.observable();
self.profileDescription = ko.observable();
self.profileAllowOverwrite = ko.observable(true);
self.uploadElement = $("#settings-cura-import");
self.uploadButton = $("#settings-cura-import-start");
self.profiles = new ItemListHelper(
"plugin_cura_profiles",
{
"id": function(a, b) {
if (a["key"].toLocaleLowerCase() < b["key"].toLocaleLowerCase()) return -1;
if (a["key"].toLocaleLowerCase() > b["key"].toLocaleLowerCase()) return 1;
return 0;
},
"name": function(a, b) {
// sorts ascending
var aName = a.name();
if (aName === undefined) {
aName = "";
}
var bName = b.name();
if (bName === undefined) {
bName = "";
}
if (aName.toLocaleLowerCase() < bName.toLocaleLowerCase()) return -1;
if (aName.toLocaleLowerCase() > bName.toLocaleLowerCase()) return 1;
return 0;
}
},
{},
"id",
[],
[],
5
);
self._sanitize = function(name) {
return name.replace(/[^a-zA-Z0-9\-_\.\(\) ]/g, "").replace(/ /g, "_");
};
self.uploadElement.fileupload({
dataType: "json",
maxNumberOfFiles: 1,
autoUpload: false,
add: function(e, data) {
if (data.files.length == 0) {
return false;
}
self.fileName(data.files[0].name);
var name = self.fileName().substr(0, self.fileName().lastIndexOf("."));
self.placeholderName(self._sanitize(name).toLowerCase());
self.placeholderDisplayName(name);
self.placeholderDescription("Imported from " + self.fileName() + " on " + formatDate(new Date().getTime() / 1000));
self.uploadButton.on("click", function() {
var form = {
allowOverwrite: self.profileAllowOverwrite()
};
if (self.profileName() !== undefined) {
form["name"] = self.profileName();
}
if (self.profileDisplayName() !== undefined) {
form["displayName"] = self.profileDisplayName();
}
if (self.profileDescription() !== undefined) {
form["description"] = self.profileDescription();
}
data.formData = form;
data.submit();
});
},
done: function(e, data) {
self.fileName(undefined);
self.placeholderName(undefined);
self.placeholderDisplayName(undefined);
self.placeholderDescription(undefined);
self.profileName(undefined);
self.profileDisplayName(undefined);
self.profileDescription(undefined);
self.profileAllowOverwrite(true);
$("#settings-plugin-cura-import").modal("hide");
self.requestData();
}
});
self.removeProfile = function(data) {
if (!data.resource) {
return;
}
self.profiles.removeItem(function(item) {
return (item.key == data.key);
});
$.ajax({
url: data.resource(),
type: "DELETE",
success: function() {
self.requestData();
}
});
};
self.makeProfileDefault = function(data) {
if (!data.resource) {
return;
}
_.each(self.profiles.items(), function(item) {
item.isdefault(false);
});
var item = self.profiles.getItem(function(item) {
return item.key == data.key;
});
if (item !== undefined) {
item.isdefault(true);
}
$.ajax({
url: data.resource(),
type: "PATCH",
dataType: "json",
data: JSON.stringify({default: true}),
contentType: "application/json; charset=UTF-8",
success: function() {
self.requestData();
}
});
};
self.showImportProfileDialog = function() {
$("#settings_plugin_cura_import").modal("show");
};
self.requestData = function() {
$.ajax({
url: API_BASEURL + "slicing/cura/profiles",
type: "GET",
dataType: "json",
success: self.fromResponse
});
};
self.fromResponse = function(data) {
var profiles = [];
_.each(_.keys(data), function(key) {
profiles.push({
key: key,
name: ko.observable(data[key].displayName),
description: ko.observable(data[key].description),
isdefault: ko.observable(data[key].default),
resource: ko.observable(data[key].resource)
});
});
self.profiles.updateItems(profiles);
};
self.onBeforeBinding = function () {
self.settings = self.settingsViewModel.settings;
self.requestData();
};
}
// view model class, parameters for constructor, container to bind to
ADDITIONAL_VIEWMODELS.push([CuraViewModel, ["loginStateViewModel", "settingsViewModel"], document.getElementById("settings_plugin_cura_dialog")]);
});
@@ -0,0 +1,29 @@
table {
th, td {
&.settings_plugin_cura_profiles_key {
text-overflow: ellipsis;
text-align: left;
width: 200px;
}
&.settings_plugin_cura_profiles_name {
text-overflow: ellipsis;
text-align: left;
}
&.settings_plugin_cura_profiles_actions {
text-align: center;
width: 100px;
a {
text-decoration: none;
color: #000;
&.disabled {
color: #ccc;
cursor: default;
}
}
}
}
}
@@ -0,0 +1,240 @@
<div id="settings_plugin_cura_dialog" data-bind="allowBindings: true">
<h4>{{ _('General') }}</h4>
<form class="form-horizontal">
<div class="control-group">
<label class="control-label" for="settings-cura-path">{{ _('Path to CuraEngine') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: settings.plugins.cura.cura_engine">
</div>
</div>
</form>
<h4>{{ _('Profiles') }}</h4>
<div class="pull-right">
<small>{{ _('Sort by') }}: <a href="#" data-bind="click: function() { profiles.changeSorting('id'); }">{{ _('Identifier') }} ({{ _('ascending') }})</a> | <a href="#" data-bind="click: function() { profiles.changeSorting('name'); }">{{ _('Name') }} ({{ _('ascending') }})</a></small>
</div>
<table class="table table-striped table-hover table-condensed table-hover">
<thead>
<tr>
<th class="settings_plugin_cura_profiles_key">{{ _('Identifier') }}</th>
<th class="settings_plugin_cura_profiles_name">{{ _('Name') }}</th>
<th class="settings_plugin_cura_profiles_actions">{{ _('Actions') }}</th>
</tr>
</thead>
<tbody data-bind="foreach: profiles.paginatedItems">
<tr data-bind="attr: {title: description}">
<td class="settings_plugin_cura_profiles_key"><span class="icon-star" data-bind="invisible: !isdefault()"></span> <span data-bind="text: key"></span></td>
<td class="settings_plugin_cura_profiles_name" data-bind="text: name"></td>
<td class="settings_plugin_cura_profiles_actions">
<a href="#" class="icon-star" title="{{ _('Make default') }}" data-bind="enable: !isdefault(), css: {disabled: isdefault()}, click: function() { if (!$data.isdefault()) { $root.makeProfileDefault($data); } }"></a>&nbsp;|&nbsp;<a href="#" class="icon-trash" title="{{ _('Delete Profile') }}" data-bind="enable: !isdefault(), css: {disabled: isdefault()}, click: function() { if (!$data.isdefault()) { $root.removeProfile($data); } }"></a>
</td>
</tr>
</tbody>
</table>
<div class="pagination pagination-mini pagination-centered">
<ul>
<li data-bind="css: {disabled: profiles.currentPage() === 0}"><a href="#" data-bind="click: profiles.prevPage">«</a></li>
</ul>
<ul data-bind="foreach: profiles.pages">
<li data-bind="css: { active: $data.number === $root.profiles.currentPage(), disabled: $data.number === -1 }"><a href="#" data-bind="text: $data.text, click: function() { $root.profiles.changePage($data.number); }"></a></li>
</ul>
<ul>
<li data-bind="css: {disabled: profiles.currentPage() === profiles.lastPage()}"><a href="#" data-bind="click: profiles.nextPage">»</a></li>
</ul>
</div>
<button class="btn pull-right" data-bind="click: function() { $root.showImportProfileDialog() }">{{ _('Import Profile...') }}</button>
<div id="settings_plugin_cura_import" class="modal hide fade">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3>{{ _('Import Existing Cura Profile') }}</h3>
</div>
<div class="modal-body">
<form class="form-horizontal">
<div class="control-group">
<label class="control-label">{{ _('Profile ini file') }}</label>
<div class="controls">
<div class="input-prepend">
<span class="btn fileinput-button">
<span>{{ _('Browse...') }}</span>
<input id="settings-cura-import" type="file" name="file" data-url="{{ url_for("plugin.cura.importCuraProfile") }}">
</span>
<span class="add-on" data-bind="text: fileName"></span>
</div>
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Identifier') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: profileName, attr: {placeholder: placeholderName}">
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Name') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: profileDisplayName, attr: {placeholder: placeholderDisplayName}">
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Description') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: profileDescription, attr: {placeholder: placeholderDescription}">
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: profileAllowOverwrite"> {{ _('Overwrite existing file') }}
</label>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Abort') }}</button>
<button class="btn btn-primary" id="settings-cura-import-start">{{ _('Confirm') }}</button>
</div>
</div>
<div id="settings_plugin_cura_edit" class="modal hide fade">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3>{{ _('Edit Cura Profile') }}</h3>
</div>
<div class="modal-body">
<div class="tabbable">
<ul class="nav nav-tabs">
<li class="active"><a href="#settings_plugin_cura_edit_general" data-toggle="tab">{{ _('General') }}</a></li>
<li><a href="#settings_plugin_cura_edit_basic" data-toggle="tab">{{ _('Basic') }}</a></li>
<li><a href="#settings_plugin_cura_edit_advanced" data-toggle="tab">{{ _('Advanced') }}</a></li>
<li><a href="#settings_plugin_cura_edit_expert" data-toggle="tab">{{ _('Expert') }}</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="settings_plugin_cura_edit_general">
<form class="form-horizontal">
<div class="control-group">
<label class="control-label">{{ _('Identifier') }}</label>
<div class="controls">
<input type="text" class="input-block-level">
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Name') }}</label>
<div class="controls">
<input type="text" class="input-block-level">
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Descripton') }}</label>
<div class="controls">
<input type="text" class="input-block-level">
</div>
</div>
</form>
</div>
<div class="tab-pane" id="settings_plugin_cura_edit_basic">
<form class="form-horizontal">
<fieldset>
<legend>{{ _('Quality') }}</legend>
<div class="control-group">
<label class="control-label">{{ _('Layer height (mm)') }}</label>
<div class="controls">
<input type="text" class="input-block-level">
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Shell thickness (mm)') }}</label>
<div class="controls">
<input type="text" class="input-block-level">
</div>
</div>
<div class="controls">
<label class="checkbox">
<input type="checkbox"> {{ _('Enable retraction') }}
</label>
</div>
</fieldset>
<fieldset>
<legend>{{ _('Fill') }}</legend>
<div class="control-group">
<label class="control-label">{{ _('Bottom/top thickness (mm)') }}</label>
<div class="controls">
<input type="text" class="input-block-level">
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Fill density (%%)') }}</label>
<div class="controls">
<input type="text" class="input-block-level">
</div>
</div>
</fieldset>
<fieldset>
<legend>{{ _('Speed and Temperature') }}</legend>
<div class="control-group">
<label class="control-label">{{ _('Print speed (mm/s)') }}</label>
<div class="controls">
<input type="text" class="input-block-level">
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Print temperature (°C)') }}</label>
<div class="controls">
<input type="text" class="input-block-level">
</div>
</div>
</fieldset>
<fieldset>
<legend>{{ _('Support') }}</legend>
<div class="control-group">
<label class="control-label">{{ _('Support type') }}</label>
<select>
<option value="none">{{ _('None') }}</option>
<option value="buildplate">{{ _('Touching buildplate') }}</option>
<option value="everywhere">{{ _('Everywhere') }}</option>
</select>
</div>
<div class="control-group">
<label class="control-label">{{ _('Platform adhesion type') }}</label>
<select>
<option value="none">{{ _('None') }}</option>
<option value="brim">{{ _('Brim') }}</option>
<option value="raft">{{ _('Raft') }}</option>
</select>
</div>
</fieldset>
<fieldset>
<legend>{{ _('Filament') }}</legend>
<div class="control-group">
<label class="control-label">{{ _('Diameter (mm)') }}</label>
<div class="controls">
<input type="text" class="input-block-level">
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Flow (%%)') }}</label>
<div class="controls">
<input type="text" class="input-block-level">
</div>
</div>
</fieldset>
</form>
</div>
<div class="tab-pane" id="settings_plugin_cura_edit_advanced"></div>
<div class="tab-pane" id="settings_plugin_cura_edit_expert"></div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Abort') }}</button>
<button class="btn btn-primary" data-bind="click: function() { $root.confirmEditProfile() }">{{ _('Confirm') }}</button>
</div>
</div>
</div>
+17 -22
View File
@@ -30,11 +30,11 @@ def getConnectionOptions():
}
class Printer():
def __init__(self, gcodeManager):
def __init__(self, fileManager, analysisQueue):
from collections import deque
self._gcodeManager = gcodeManager
self._gcodeManager.registerCallback(self)
self._analysisQueue = analysisQueue
self._fileManager = fileManager
# state
# TODO do we really need to hold the temperature here?
@@ -147,14 +147,6 @@ class Printer():
try: callback.sendFeedbackCommandOutput(name, output)
except: pass
#~~ callback from gcodemanager
def sendUpdateTrigger(self, type):
if type == "gcodeFiles" and self._selectedFile:
self._setJobData(self._selectedFile["filename"],
self._selectedFile["filesize"],
self._selectedFile["sd"])
#~~ callback from metadata analysis event
def onMetadataAnalysisFinished(self, event, data):
@@ -316,7 +308,7 @@ class Printer():
# mark print as failure
if self._selectedFile is not None:
self._gcodeManager.printFailed(self._selectedFile["filename"], self._comm.getPrintTime())
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._comm.getPrintTime(), False)
payload = {
"file": self._selectedFile["filename"],
"origin": FileDestinations.LOCAL
@@ -410,13 +402,16 @@ class Printer():
if not sd:
date = int(os.stat(filename).st_ctime)
fileData = self._gcodeManager.getFileData(filename)
try:
fileData = self._fileManager.get_metadata(FileDestinations.SDCARD if sd else FileDestinations.LOCAL, filename)
except:
fileData = None
if fileData is not None:
if "gcodeAnalysis" in fileData:
if estimatedPrintTime is None and "estimatedPrintTime" in fileData["gcodeAnalysis"]:
estimatedPrintTime = fileData["gcodeAnalysis"]["estimatedPrintTime"]
if "filament" in fileData["gcodeAnalysis"].keys():
filament = fileData["gcodeAnalysis"]["filament"]
if "analysis" in fileData:
if estimatedPrintTime is None and "estimatedPrintTime" in fileData["analysis"]:
estimatedPrintTime = fileData["analysis"]["estimatedPrintTime"]
if "filament" in fileData["analysis"].keys():
filament = fileData["analysis"]["filament"]
if "prints" in fileData and fileData["prints"] and "last" in fileData["prints"] and fileData["prints"]["last"] and "lastPrintTime" in fileData["prints"]["last"]:
lastPrintTime = fileData["prints"]["last"]["lastPrintTime"]
@@ -478,12 +473,12 @@ class Printer():
if self._comm is not None and oldState == self._comm.STATE_PRINTING:
if self._selectedFile is not None:
if state == self._comm.STATE_OPERATIONAL:
self._gcodeManager.printSucceeded(self._selectedFile["filename"], self._comm.getPrintTime())
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._comm.getPrintTime(), True)
elif state == self._comm.STATE_CLOSED or state == self._comm.STATE_ERROR or state == self._comm.STATE_CLOSED_WITH_ERROR:
self._gcodeManager.printFailed(self._selectedFile["filename"], self._comm.getPrintTime())
self._gcodeManager.resumeAnalysis() # printing done, put those cpu cycles to good use
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._comm.getPrintTime(), False)
self._analysisQueue.resume() # printing done, put those cpu cycles to good use
elif self._comm is not None and state == self._comm.STATE_PRINTING:
self._gcodeManager.pauseAnalysis() # do not analyse gcode while printing
self._analysisQueue.pause() # do not analyse files while printing
self._setState(state)
+19 -10
View File
@@ -27,7 +27,9 @@ babel = Babel(app)
debug = False
printer = None
gcodeManager = None
fileManager = None
slicingManager = None
analysisQueue = None
userManager = None
eventManager = None
loginManager = None
@@ -40,13 +42,15 @@ user_permission = Permission(RoleNeed("user"))
# only import the octoprint stuff down here, as it might depend on things defined above to be initialized already
from octoprint.printer import Printer, getConnectionOptions
from octoprint.settings import settings
import octoprint.gcodefiles as gcodefiles
import octoprint.users as users
import octoprint.events as events
import octoprint.plugin
import octoprint.timelapse
import octoprint._version
import octoprint.util
import octoprint.filemanager.storage
import octoprint.filemanager.analysis
import octoprint.slicing
from . import util
@@ -180,7 +184,9 @@ class Server():
self._checkForRoot()
global printer
global gcodeManager
global fileManager
global slicingManager
global analysisQueue
global userManager
global eventManager
global loginManager
@@ -194,6 +200,7 @@ class Server():
# first initialize the settings singleton and make sure it uses given configfile and basedir if available
self._initSettings(self._configfile, self._basedir)
pluginManager = octoprint.plugin.plugin_manager(init=True)
# then initialize logging
self._initLogging(self._debug, self._logConf)
@@ -202,9 +209,12 @@ class Server():
logger.info("Starting OctoPrint %s" % DISPLAY_VERSION)
eventManager = events.eventManager()
gcodeManager = gcodefiles.GcodeManager()
printer = Printer(gcodeManager)
pluginManager = octoprint.plugin.plugin_manager(init=True)
analysisQueue = octoprint.filemanager.analysis.AnalysisQueue()
slicingManager = octoprint.slicing.SlicingManager(settings().getBaseFolder("slicingProfiles"))
storage_managers = dict()
storage_managers[octoprint.filemanager.FileDestinations.LOCAL] = octoprint.filemanager.storage.LocalFileStorage(settings().getBaseFolder("uploads"))
fileManager = octoprint.filemanager.FileManager(analysisQueue, slicingManager, initial_storage_managers=storage_managers)
printer = Printer(fileManager, analysisQueue)
# configure additional template folders for jinja2
template_plugins = pluginManager.get_implementations(octoprint.plugin.TemplatePlugin)
@@ -297,8 +307,7 @@ class Server():
# start up watchdogs
observer = Observer()
observer.schedule(util.watchdog.GcodeWatchdogHandler(gcodeManager, printer), settings().getBaseFolder("watched"))
observer.schedule(util.watchdog.UploadCleanupWatchdogHandler(gcodeManager), settings().getBaseFolder("uploads"))
observer.schedule(util.watchdog.GcodeWatchdogHandler(fileManager, printer), settings().getBaseFolder("watched"))
observer.start()
ioloop = IOLoop.instance()
@@ -342,8 +351,8 @@ class Server():
logger.exception("Stacktrace follows:")
def _createSocketConnection(self, session):
global printer, gcodeManager, userManager, eventManager
return util.sockjs.PrinterStateConnection(printer, gcodeManager, userManager, eventManager, session)
global printer, fileManager, analysisQueue, userManager, eventManager
return util.sockjs.PrinterStateConnection(printer, fileManager, analysisQueue, userManager, eventManager, session)
def _checkForRoot(self):
if "geteuid" in dir(os) and os.geteuid() == 0:
+1
View File
@@ -35,6 +35,7 @@ from . import settings as api_settings
from . import timelapse as api_timelapse
from . import users as api_users
from . import log as api_logs
from . import slicing as api_slicing
VERSION = "0.1"
+116 -18
View File
@@ -7,14 +7,14 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
from flask import request, jsonify, make_response, url_for
import octoprint.gcodefiles as gcodefiles
import octoprint.util as util
from octoprint.filemanager.destinations import FileDestinations
from octoprint.settings import settings, valid_boolean_trues
from octoprint.server import printer, gcodeManager, eventManager, NO_CONTENT
from octoprint.server import printer, fileManager, slicingManager, eventManager, NO_CONTENT
from octoprint.server.util.flask import restricted_access
from octoprint.server.api import api
from octoprint.events import Events
import octoprint.filemanager
#~~ GCODE file handling
@@ -22,7 +22,10 @@ from octoprint.events import Events
@api.route("/files", methods=["GET"])
def readGcodeFiles():
files = _getFileList(FileDestinations.LOCAL)
filter = None
if "filter" in request.values:
filter = request.values["filter"]
files = _getFileList(FileDestinations.LOCAL, filter=filter)
files.extend(_getFileList(FileDestinations.SDCARD))
return jsonify(files=files, free=util.getFreeBytes(settings().getBaseFolder("uploads")))
@@ -48,7 +51,7 @@ def _getFileDetails(origin, filename):
return None
def _getFileList(origin):
def _getFileList(origin, filter=None):
if origin == FileDestinations.SDCARD:
sdFileList = printer.getSdFiles()
@@ -56,6 +59,7 @@ def _getFileList(origin):
if sdFileList is not None:
for sdFile, sdSize in sdFileList:
file = {
"type": "machinecode",
"name": sdFile,
"origin": FileDestinations.SDCARD,
"refs": {
@@ -66,8 +70,41 @@ def _getFileList(origin):
file.update({"size": sdSize})
files.append(file)
else:
files = gcodeManager.getAllFileData()
filter_func = None
if filter:
filter_func = lambda entry, entry_data: octoprint.filemanager.valid_file_type(entry, type=filter)
files = fileManager.list_files(origin, filter=filter_func, recursive=False)[origin].values()
for file in files:
file["origin"] = FileDestinations.LOCAL
if "analysis" in file and octoprint.filemanager.valid_file_type(file["name"], type="gcode"):
file["gcodeAnalysis"] = file["analysis"]
del file["analysis"]
if "history" in file and octoprint.filemanager.valid_file_type(file["name"], type="gcode"):
# convert print log
history = file["history"]
del file["history"]
success = 0
failure = 0
last = None
for entry in history:
success += 1 if entry["success"] else 0
failure += 1 if not entry["success"] else 0
if not last or entry["timestamp"] > last["timestamp"]:
last = entry
if last:
prints = dict(
success=success,
failure=failure,
last=dict(
success=last["success"],
date=last["timestamp"],
printTime=last["printTime"]
)
)
file["prints"] = prints
file.update({
"refs": {
"resource": url_for(".readGcodeFile", target=FileDestinations.LOCAL, filename=file["name"], _external=True),
@@ -79,11 +116,9 @@ def _getFileList(origin):
def _verifyFileExists(origin, filename):
if origin == FileDestinations.SDCARD:
availableFiles = map(lambda x: x[0], printer.getSdFiles())
return filename in map(lambda x: x[0], printer.getSdFiles())
else:
availableFiles = gcodeManager.getAllFilenames()
return filename in availableFiles
return fileManager.file_exists(origin, filename)
@api.route("/files/<string:target>", methods=["POST"])
@@ -130,8 +165,11 @@ def uploadGcodeFile(target):
currentOrigin = currentJobFile["origin"]
# determine future filename of file to be uploaded, abort if it can't be uploaded
futureFilename = gcodeManager.getFutureFilename(upload)
if futureFilename is None or (not settings().getBoolean(["cura", "enabled"]) and not gcodefiles.isGcodeFileName(futureFilename)):
try:
futureFilename = fileManager.sanitize_name(FileDestinations.LOCAL, upload.filename)
except:
futureFilename = None
if futureFilename is None or not (slicingManager.slicing_enabled or octoprint.filemanager.valid_file_type(futureFilename, type="gcode")):
return make_response("Can not upload file %s, wrong format?" % upload.filename, 415)
# prohibit overwriting currently selected file while it's being printed
@@ -145,7 +183,8 @@ def uploadGcodeFile(target):
Depending on the file's destination triggers either streaming to SD card or directly calls selectAndOrPrint.
"""
if destination == FileDestinations.SDCARD:
if destination == FileDestinations.SDCARD and octoprint.filemanager.valid_file_type(filename, "gcode"):
return filename, printer.addSdFile(filename, absFilename, selectAndOrPrint)
else:
selectAndOrPrint(filename, absFilename, destination)
@@ -160,12 +199,18 @@ def uploadGcodeFile(target):
Selects the just uploaded file if either selectAfterUpload or printAfterSelect are True, or if the
exact file is already selected, such reloading it.
"""
if selectAfterUpload or printAfterSelect or (currentFilename == filename and currentOrigin == destination):
if octoprint.filemanager.valid_file_type(added_file, "gcode") and (selectAfterUpload or printAfterSelect or (currentFilename == filename and currentOrigin == destination)):
printer.selectFile(absFilename, destination == FileDestinations.SDCARD, printAfterSelect)
filename, done = gcodeManager.addFile(upload, target, fileProcessingFinished)
if filename is None:
added_file = fileManager.add_file(FileDestinations.LOCAL, upload.filename, upload, allow_overwrite=True)
if added_file is None:
return make_response("Could not upload the file %s" % upload.filename, 500)
if octoprint.filemanager.valid_file_type(added_file, "stl"):
filename = added_file
done = True
else:
filename = fileProcessingFinished(added_file, fileManager.get_absolute_path(FileDestinations.LOCAL, added_file), target)
done = True
sdFilename = None
if isinstance(filename, tuple):
@@ -226,7 +271,8 @@ def gcodeFileCommand(filename, target):
# valid file commands, dict mapping command name to mandatory parameters
valid_commands = {
"select": []
"select": [],
"slice": []
}
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
@@ -246,9 +292,61 @@ def gcodeFileCommand(filename, target):
filenameToSelect = filename
sd = True
else:
filenameToSelect = gcodeManager.getAbsolutePath(filename)
filenameToSelect = fileManager.get_absolute_path(target, filename)
printer.selectFile(filenameToSelect, sd, printAfterLoading)
elif command == "slice":
if "slicer" in data.keys():
slicer = data["slicer"]
del data["slicer"]
if not slicer in slicingManager.registered_slicers:
return make_response("Slicer {slicer} is not available".format(**locals()), 400)
elif "cura" in slicingManager.registered_slicers:
slicer = "cura"
else:
return make_response("Cannot slice {filename}, no slicer available".format(**locals()), 415)
if not octoprint.filemanager.valid_file_type(filename, type="stl"):
return make_response("Cannot slice {filename}, not an STL file".format(**locals()), 415)
if "gcode" in data.keys() and data["gcode"]:
gcode_name = data["gcode"]
del data["gcode"]
else:
import os
name, _ = os.path.splitext(filename)
gcode_name = name + ".gco"
if "profile" in data.keys() and data["profile"]:
profile = data["profile"]
del data["profile"]
else:
profile = None
override_keys = [k for k in data if k.startswith("profile.") and data[k] is not None]
overrides = dict()
for key in override_keys:
overrides[key[len("profile."):]] = data[key]
ok, result = fileManager.slice(slicer, target, filename, target, gcode_name, profile=profile, overrides=overrides)
if ok:
files = {}
location = url_for(".readGcodeFile", target=target, filename=gcode_name, _external=True)
result = {
"name": gcode_name,
"origin": FileDestinations.LOCAL,
"refs": {
"resource": location,
"download": url_for("index", _external=True) + "downloads/files/" + target + "/" + gcode_name
}
}
r = make_response(jsonify(result), 202)
r.headers["Location"] = location
return r
else:
return make_response("Could not slice: {result}".format(result=result), 500)
return NO_CONTENT
@@ -282,7 +380,7 @@ def deleteGcodeFile(filename, target):
if sd:
printer.deleteSdFile(filename)
else:
gcodeManager.removeFile(filename)
fileManager.remove_file(target, filename)
return NO_CONTENT
+147
View File
@@ -0,0 +1,147 @@
# coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
from flask import request, jsonify, make_response, url_for
from octoprint.server import slicingManager
from octoprint.server.util.flask import restricted_access
from octoprint.server.api import api, NO_CONTENT
from octoprint.settings import settings as s
@api.route("/slicing", methods=["GET"])
def slicingListAll():
default_slicer = s().get(["slicing", "defaultSlicer"])
result = dict()
for slicer in slicingManager.registered_slicers:
result[slicer] = dict(
key=slicer,
displayName=slicingManager.get_slicer(slicer).get_slicer_name(),
default=default_slicer == slicer,
profiles=_getSlicingProfilesData(slicer)
)
return jsonify(result)
@api.route("/slicing/<string:slicer>/profiles", methods=["GET"])
def slicingListSlicerProfiles(slicer):
if not slicer in slicingManager.registered_slicers:
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
return jsonify(_getSlicingProfilesData(slicer))
@api.route("/slicing/<string:slicer>/profiles/<string:name>", methods=["GET"])
def slicingGetSlicerProfile(slicer, name):
if not slicer in slicingManager.registered_slicers:
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
profile = slicingManager.load_profile(slicer, name)
if not profile:
return make_response("Profile not found", 404)
result = _getSlicingProfileData(slicer, name, profile)
result["data"] = profile.data
return jsonify(result)
@api.route("/slicing/<string:slicer>/profiles/<string:name>", methods=["PUT"])
@restricted_access
def slicingAddSlicerProfile(slicer, name):
if not slicer in slicingManager.registered_slicers:
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
if not "application/json" in request.headers["Content-Type"]:
return None, None, make_response("Expected content-type JSON", 400)
json_data = request.json
data = dict()
display_name = None
description = None
if "data" in json_data:
data = json_data["data"]
if "displayName" in json_data:
display_name = json_data["displayName"]
if "description" in json_data:
description = json_data["description"]
profile = slicingManager.save_profile(slicer, name, data, display_name=display_name, description=description)
result = _getSlicingProfileData(slicer, name, profile)
r = make_response(jsonify(result), 201)
r.headers["Location"] = result["resource"]
return r
@api.route("/slicing/<string:slicer>/profiles/<string:name>", methods=["PATCH"])
@restricted_access
def slicingPatchSlicerProfile(slicer, name):
if not slicer in slicingManager.registered_slicers:
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
if not "application/json" in request.headers["Content-Type"]:
return None, None, make_response("Expected content-type JSON", 400)
profile = slicingManager.load_profile(slicer, name)
if not profile:
return make_response("Profile not found", 404)
json_data = request.json
data = dict()
display_name = None
description = None
if "data" in json_data:
data = json_data["data"]
if "displayName" in json_data:
display_name = json_data["displayName"]
if "description" in json_data:
description = json_data["description"]
from octoprint.server.api import valid_boolean_trues
if "default" in json_data and json_data["default"] in valid_boolean_trues:
default_profiles = s().get(["slicing", "defaultProfiles"])
if not default_profiles:
default_profiles = dict()
default_profiles[slicer] = name
s().set(["slicing", "defaultProfiles"], default_profiles)
s().save(force=True)
slicingManager.save_profile(slicer, name, profile, overrides=data, display_name=display_name, description=description)
return NO_CONTENT
@api.route("/slicing/<string:slicer>/profiles/<string:name>", methods=["DELETE"])
@restricted_access
def slicingDelSlicerProfile(slicer, name):
if not slicer in slicingManager.registered_slicers:
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
slicingManager.delete_profile(slicer, name)
return NO_CONTENT
def _getSlicingProfilesData(slicer):
profiles = slicingManager.all_profiles(slicer)
if not profiles:
return dict()
result = dict()
for name, profile in profiles.items():
result[name] = _getSlicingProfileData(slicer, name, profile)
return result
def _getSlicingProfileData(slicer, name, profile):
defaultProfiles = s().get(["slicing", "defaultProfiles"])
result = dict(
key=name,
default=defaultProfiles and slicer in defaultProfiles and defaultProfiles[slicer] == name,
resource=url_for(".slicingGetSlicerProfile", slicer=slicer, name=name, _external=True)
)
if profile.display_name is not None:
result["displayName"] = profile.display_name
if profile.description is not None:
result["description"] = profile.description
return result
+6 -7
View File
@@ -15,7 +15,7 @@ from octoprint.events import Events
class PrinterStateConnection(sockjs.tornado.SockJSConnection):
def __init__(self, printer, gcodeManager, userManager, eventManager, session):
def __init__(self, printer, fileManager, analysisQueue, userManager, eventManager, session):
sockjs.tornado.SockJSConnection.__init__(self, session)
self._logger = logging.getLogger(__name__)
@@ -28,7 +28,8 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection):
self._messageBacklogMutex = threading.Lock()
self._printer = printer
self._gcodeManager = gcodeManager
self._fileManager = fileManager
self._analysisQueue = analysisQueue
self._userManager = userManager
self._eventManager = eventManager
@@ -46,7 +47,6 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection):
self._emit("connected", {"apikey": octoprint.server.UI_API_KEY, "version": octoprint.server.VERSION, "display_version": octoprint.server.DISPLAY_VERSION})
self._printer.registerCallback(self)
self._gcodeManager.registerCallback(self)
octoprint.timelapse.registerCallback(self)
self._eventManager.fire(Events.CLIENT_OPENED, {"remoteAddress": remoteAddress})
@@ -58,7 +58,6 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection):
def on_close(self):
self._logger.info("Client connection closed")
self._printer.unregisterCallback(self)
self._gcodeManager.unregisterCallback(self)
octoprint.timelapse.unregisterCallback(self)
self._eventManager.fire(Events.CLIENT_CLOSED)
@@ -83,9 +82,9 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection):
self._messageBacklog = []
data.update({
"temps": temperatures,
"logs": logs,
"messages": messages
"temps": temperatures,
"logs": logs,
"messages": messages
})
self._emit("current", data)
+30 -32
View File
@@ -6,31 +6,10 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import logging
import os
import watchdog.events
import octoprint.gcodefiles
import octoprint.filemanager
import octoprint.util
from octoprint.settings import settings
class UploadCleanupWatchdogHandler(watchdog.events.PatternMatchingEventHandler):
"""
Takes care of automatically deleting metadata entries for files that get deleted from the uploads folder
"""
patterns = map(lambda x: "*.%s" % x, octoprint.gcodefiles.GCODE_EXTENSIONS)
def __init__(self, gcode_manager):
watchdog.events.PatternMatchingEventHandler.__init__(self)
self._gcode_manager = gcode_manager
def on_deleted(self, event):
filename = self._gcode_manager._getBasicFilename(event.src_path)
if not filename:
return
self._gcode_manager.removeFileFromMetadata(filename)
class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler):
@@ -38,27 +17,28 @@ class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler):
Takes care of automatically "uploading" files that get added to the watched folder.
"""
patterns = map(lambda x: "*.%s" % x, octoprint.gcodefiles.SUPPORTED_EXTENSIONS)
patterns = map(lambda x: "*.%s" % x, octoprint.filemanager.get_all_extensions())
def __init__(self, gcodeManager, printer):
def __init__(self, file_manager, printer):
watchdog.events.PatternMatchingEventHandler.__init__(self)
self._logger = logging.getLogger(__name__)
self._gcodeManager = gcodeManager
self._file_manager = file_manager
self._printer = printer
def _upload(self, path):
class WatchdogFileWrapper(object):
def __init__(self, path):
import os
self._path = path
self.filename = os.path.basename(self._path)
def save(self, target):
octoprint.util.safeRename(self._path, target)
fileWrapper = WatchdogFileWrapper(path)
file_wrapper = WatchdogFileWrapper(path)
# determine current job
currentFilename = None
@@ -71,17 +51,35 @@ class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler):
currentOrigin = currentJobFile["origin"]
# determine future filename of file to be uploaded, abort if it can't be uploaded
futureFilename = self._gcodeManager.getFutureFilename(fileWrapper)
if futureFilename is None or (not settings().getBoolean(["cura", "enabled"]) and not octoprint.gcodefiles.isGcodeFileName(futureFilename)):
self._logger.warn("Could not add %s: Invalid file" % fileWrapper.filename)
try:
futureFilename = self._file_manager.sanitize_name(octoprint.filemanager.FileDestinations.LOCAL, file_wrapper.filename)
except:
futureFilename = None
if futureFilename is None or (len(self._file_manager.registered_slicers) == 0 and not octoprint.filemanager.valid_file_type(futureFilename, type="gcode")):
return
# prohibit overwriting currently selected file while it's being printed
if futureFilename == currentFilename and not currentOrigin == octoprint.gcodefiles.FileDestinations.SDCARD and self._printer.isPrinting() or self._printer.isPaused():
self._logger.warn("Could not add %s: Trying to overwrite file that is currently being printed" % fileWrapper.filename)
if futureFilename == currentFilename and currentOrigin == octoprint.filemanager.FileDestinations.LOCAL and self._printer.isPrinting() or self._printer.isPaused():
return
self._gcodeManager.addFile(fileWrapper, octoprint.gcodefiles.FileDestinations.LOCAL)
added_file = self._file_manager.add_file(octoprint.filemanager.FileDestinations.LOCAL,
file_wrapper.filename,
file_wrapper,
allow_overwrite=True)
if added_file is None:
return
slicer_name = self._file_manager.default_slicer
if octoprint.filemanager.valid_file_type(added_file, "stl") and slicer_name:
# if it's an STL we now have to slice it before we can continue
import os
name, ext = os.path.splitext(added_file)
gcode_path = name + ".gco"
self._file_manager.slice(slicer_name,
octoprint.filemanager.FileDestinations.LOCAL,
added_file,
octoprint.filemanager.FileDestinations.LOCAL,
gcode_path)
def on_created(self, event):
self._upload(event.src_path)
+14 -9
View File
@@ -49,8 +49,8 @@ default_settings = {
},
"uploads": {
"maxSize": 1 * 1024 * 1024 * 1024, # 1GB
"nameSuffix": ".name",
"pathSuffix": ".path"
"nameSuffix": "name",
"pathSuffix": "path"
},
"maxSize": 100 * 1024, # 100 KB
},
@@ -92,14 +92,14 @@ default_settings = {
"logs": None,
"virtualSd": None,
"watched": None,
"plugins": None
"plugins": None,
"slicingProfiles": None
},
"temperature": {
"profiles":
[
{"name": "ABS", "extruder" : 210, "bed" : 100 },
{"name": "PLA", "extruder" : 180, "bed" : 60 }
]
"profiles": [
{"name": "ABS", "extruder" : 210, "bed" : 100 },
{"name": "PLA", "extruder" : 180, "bed" : 60 }
]
},
"printerParameters": {
"movementSpeed": {
@@ -115,7 +115,7 @@ default_settings = {
{"x": 0.0, "y": 0.0}
],
"bedDimensions": {
"x": 200.0, "y": 200.0, "r": 100
"x": 200.0, "y": 200.0, "r": 100, "circular": False
},
"defaultExtrusionLength": 5
},
@@ -140,6 +140,11 @@ default_settings = {
"path": "/default/path/to/cura",
"config": "/default/path/to/your/cura/config.ini"
},
"slicing": {
"enabled": True,
"defaultSlicer": "cura",
"defaultProfiles": None
},
"events": {
"enabled": True,
"subscriptions": []
View File
Whitespace-only changes.
-76
View File
@@ -1,76 +0,0 @@
import sarge
__author__ = "Ross Hendrickson savorywatt"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
import logging
import os
from octoprint.settings import settings
class CuraFactory(object):
@staticmethod
def create_slicer(path=None):
"""Utilizes the factory pattern to setup a CuraEngine object
:param path: :class: `str`
"""
if path:
return Cura(path)
current_settings = settings(init=True)
path = current_settings.get(["cura", "path"])
return Cura(path)
class Cura(object):
def __init__(self, cura_path):
if not cura_path:
raise Exception("Unable to create CuraEngine - no path specified")
self.cura_path = cura_path
self._logger = logging.getLogger(__name__)
def process_file(
self, config, gcode, file_path, call_back=None,
call_back_args=None):
"""Wraps around the main.cpp processFile method.
:param config: :class: `string` :path to a cura config file:
:param gcode: :class: `string :path to write out the gcode generated:
:param file_path: :class: `string :path to the STL to be sliced:
:note: This will spawn a thread to handle the subprocess call and allow
us to be able to have a call back
"""
import threading
def start_thread(call_back, call_back_args, call_args, cwd):
self._logger.info("Running %r in %s" % (call_args, cwd))
command = " ".join(call_args)
try:
p = sarge.run(command, cwd=cwd)
if p.returncode == 0:
call_back(*call_back_args)
else:
self._logger.warn("Could not slice via Cura, got return code %r" % p.returncode)
call_back_args.append("Got returncode %r" % p.returncode)
call_back(*call_back_args)
except:
self._logger.exception("Could not slice via Cura, got an unknown error")
call_back_args.append("Unknown error, please consult the log file")
call_back(*call_back_args)
executable = self.cura_path
(workingDir, ignored) = os.path.split(executable)
args = [executable, '-i', config, '-s', file_path, '-o', gcode]
thread = threading.Thread(target=start_thread, args=(call_back,
call_back_args, args, workingDir))
thread.start()
@@ -1,31 +0,0 @@
import unittest
from mock import patch
from octoprint.slicers.cura import CuraFactory
from octoprint.slicers.cura import Cura
class CuraFactoryTestCase(unittest.TestCase):
def test_cura_factory(self):
fake_path = 'my/temp/path'
result = CuraFactory.create_slicer(fake_path)
self.assertEqual(fake_path, result.cura_path)
@patch('threading.Thread')
def test_cura_engine_process_file(self, thread):
path = 'rosshendrickson/workspaces/opensource/CuraEngine/'
cura = CuraFactory.create_slicer(path)
file_path = './cura/tests/test.stl'
config_path = './cura/tests/config'
gcode_filename = './cura/tests/output.gcode'
cura.process_file(config_path, gcode_filename, file_path)
self.assertTrue(thread.called)
+237
View File
@@ -0,0 +1,237 @@
# coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import os
import octoprint.plugin
import octoprint.events
from octoprint.settings import settings
class SlicingProfile(object):
def __init__(self, slicer, name, data, display_name=None, description=None):
self.slicer = slicer
self.name = name
self.data = data
self.display_name = display_name
self.description = description
class TemporaryProfile(object):
def __init__(self, save_profile, profile, overrides=None):
self.save_profile = save_profile
self.profile = profile
self.overrides = overrides
def __enter__(self):
import tempfile
temp_profile = tempfile.NamedTemporaryFile(prefix="slicing-profile-temp-", suffix=".profile", delete=False)
temp_profile.close()
self.temp_path = temp_profile.name
self.save_profile(self.temp_path, self.profile, overrides=self.overrides)
return self.temp_path
def __exit__(self, type, value, traceback):
import os
try:
os.remove(self.temp_path)
except:
pass
class SlicingManager(object):
def __init__(self, profile_path):
self._profile_path = profile_path
self._slicers = dict()
self._slicer_names = dict()
self._load_slicers()
def _load_slicers(self):
plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SlicerPlugin)
for name, plugin in plugins.items():
if plugin.is_slicer_configured():
self._slicers[plugin.get_slicer_type()] = plugin
@property
def slicing_enabled(self):
return len(self.registered_slicers) > 0
@property
def registered_slicers(self):
return self._slicers.keys()
@property
def default_slicer(self):
slicer_name = settings().get(["slicing", "defaultSlicer"])
if slicer_name in self.registered_slicers:
return slicer_name
else:
return None
def get_slicer(self, slicer):
return self._slicers[slicer] if slicer in self._slicers else None
def slice(self, slicer_name, source_path, dest_path, profile_name, callback, callback_args=None, callback_kwargs=None, overrides=None):
if callback_args is None:
callback_args = ()
if callback_kwargs is None:
callback_kwargs = dict()
if not slicer_name in self.registered_slicers:
error = "No such slicer: {slicer_name}".format(**locals())
callback_kwargs.update(dict(_error=error))
callback(*callback_args, **callback_kwargs)
return False, error
slicer = self.get_slicer(slicer_name)
def slicer_worker(slicer, model_path, machinecode_path, profile_name, overrides, callback, callback_args, callback_kwargs):
with self.temporary_profile(slicer.get_slicer_type(), name=profile_name, overrides=overrides) as profile_path:
ok, result = slicer.do_slice(model_path, machinecode_path=machinecode_path, profile_path=profile_path)
if not ok:
callback_kwargs.update(dict(_error=result))
callback(*callback_args, **callback_kwargs)
import threading
slicer_worker_thread = threading.Thread(target=slicer_worker,
args=(slicer, source_path, dest_path, profile_name, overrides, callback, callback_args, callback_kwargs))
slicer_worker_thread.daemon = True
slicer_worker_thread.start()
return True, None
def load_profile(self, slicer, name):
if not slicer in self.registered_slicers:
return None
try:
path = self.get_profile_path(slicer, name, must_exist=True)
except IOError:
return None
return self._load_profile_from_path(slicer, path)
def save_profile(self, slicer, name, profile, overrides=None, allow_overwrite=True, display_name=None, description=None):
if not slicer in self.registered_slicers:
return
if not isinstance(profile, SlicingProfile):
if isinstance(profile, dict):
profile = SlicingProfile(slicer, name, profile, display_name=display_name, description=description)
else:
raise ValueError("profile must be a SlicingProfile")
else:
profile.slicer = slicer
profile.name = name
if display_name is not None:
profile.display_name = display_name
if description is not None:
profile.description = description
path = self.get_profile_path(slicer, name)
self._save_profile_to_path(slicer, path, profile, overrides=overrides, allow_overwrite=allow_overwrite)
return profile
def temporary_profile(self, slicer, name=None, overrides=None):
if not slicer in self.registered_slicers:
return None
profile = self._get_default_profile(slicer)
if name:
try:
profile = self.load_profile(slicer, name)
except IOError:
profile = self._get_default_profile(slicer)
else:
if profile is None:
profile = self._get_default_profile(slicer)
return TemporaryProfile(self.get_slicer(slicer).save_slicer_profile, profile, overrides=overrides)
def delete_profile(self, slicer, name):
if not slicer in self.registered_slicers:
return None
path = self.get_profile_path(slicer, name)
if not os.path.exists(path) or not os.path.isfile(path):
return
os.remove(path)
def all_profiles(self, slicer):
if not slicer in self.registered_slicers:
return None
profiles = dict()
slicer_profile_path = self.get_slicer_profile_path(slicer)
for entry in os.listdir(slicer_profile_path):
if not entry.endswith(".profile") or entry.startswith("."):
# we are only interested in profiles and no hidden files
continue
path = os.path.join(slicer_profile_path, entry)
profile_name = entry[:-len(".profile")]
profiles[profile_name] = self._load_profile_from_path(slicer, path)
return profiles
def get_slicer_profile_path(self, slicer):
if not slicer in self.registered_slicers:
return None
path = os.path.join(self._profile_path, slicer)
if not os.path.exists(path):
os.makedirs(path)
return path
def get_profile_path(self, slicer, name, must_exist=False):
if not slicer in self.registered_slicers:
return None
if not name:
return None
name = self._sanitize(name)
path = os.path.join(self.get_slicer_profile_path(slicer), "{name}.profile".format(name=name))
if not os.path.realpath(path).startswith(self._profile_path):
raise IOError("Path to profile {name} tried to break out of allows sub path".format(**locals()))
if must_exist and not (os.path.exists(path) and os.path.isfile(path)):
raise IOError("Profile {name} doesn't exist".format(**locals()))
return path
def _sanitize(self, name):
if name is None:
return None
if "/" in name or "\\" in name:
raise ValueError("name must not contain / or \\")
import string
valid_chars = "-_.() {ascii}{digits}".format(ascii=string.ascii_letters, digits=string.digits)
sanitized_name = ''.join(c for c in name if c in valid_chars)
sanitized_name = sanitized_name.replace(" ", "_")
return sanitized_name
def _load_profile_from_path(self, slicer, path):
return self.get_slicer(slicer).get_slicer_profile(path)
def _save_profile_to_path(self, slicer, path, profile, allow_overwrite=True, overrides=None):
self.get_slicer(slicer).save_slicer_profile(path, profile, allow_overwrite=allow_overwrite, overrides=overrides)
def _get_default_profile(self, slicer):
default_profiles = settings().get(["slicing", "defaultProfiles"])
if default_profiles and slicer in default_profiles:
try:
return self.load_profile(slicer, default_profiles[slicer])
except:
pass
return self.get_slicer(slicer).get_slicer_default_profile()
@@ -145,6 +145,8 @@ function DataUpdater(allViewModels) {
var gcodeUploadProgress = $("#gcode_upload_progress");
var gcodeUploadProgressBar = $(".bar", gcodeUploadProgress);
console.log("Got event " + type + " with payload: " + JSON.stringify(payload))
if (type == "UpdatedFiles") {
_.each(self.allViewModels, function(viewModel) {
if (viewModel.hasOwnProperty("onUpdatedFiles")) {
+20 -2
View File
@@ -52,6 +52,19 @@ function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSor
return matcher(self.selectedItem());
};
self.removeItem = function(matcher) {
var item = self.getItem(matcher, true);
if (item === undefined) {
return;
}
var index = self.allItems.indexOf(item);
if (index > -1) {
self.allItems.splice(index, 1);
self._updateItems();
}
};
//~~ pagination
self.paginatedItems = ko.dependentObservable(function() {
@@ -131,8 +144,13 @@ function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSor
}
};
self.getItem = function(matcher) {
var itemList = self.items();
self.getItem = function(matcher, all) {
var itemList;
if (all !== undefined && all === true) {
itemList = self.allItems;
} else {
itemList = self.items();
}
for (var i = 0; i < itemList.length; i++) {
if (matcher(itemList[i])) {
return itemList[i];
+11 -3
View File
@@ -76,7 +76,8 @@ $(function() {
var temperatureViewModel = new TemperatureViewModel(loginStateViewModel, settingsViewModel);
var controlViewModel = new ControlViewModel(loginStateViewModel, settingsViewModel);
var terminalViewModel = new TerminalViewModel(loginStateViewModel, settingsViewModel);
var gcodeFilesViewModel = new GcodeFilesViewModel(printerStateViewModel, loginStateViewModel);
var slicingViewModel = new SlicingViewModel(loginStateViewModel);
var gcodeFilesViewModel = new GcodeFilesViewModel(printerStateViewModel, loginStateViewModel, slicingViewModel);
var gcodeViewModel = new GcodeViewModel(loginStateViewModel, settingsViewModel);
var navigationViewModel = new NavigationViewModel(loginStateViewModel, appearanceViewModel, settingsViewModel, usersViewModel);
var logViewModel = new LogViewModel(loginStateViewModel);
@@ -95,7 +96,8 @@ $(function() {
gcodeFilesViewModel: gcodeFilesViewModel,
gcodeViewModel: gcodeViewModel,
navigationViewModel: navigationViewModel,
logViewModel: logViewModel
logViewModel: logViewModel,
slicingViewModel: slicingViewModel
};
var allViewModels = _.values(viewModelMap);
@@ -154,6 +156,10 @@ $(function() {
}
gcodeFilesViewModel.requestData(filename, location);
if (_.endsWith(filename.toLowerCase(), ".stl")) {
slicingViewModel.show(location, filename);
}
if (data.result.done) {
$("#gcode_upload_progress .bar").css("width", "0%");
$("#gcode_upload_progress").removeClass("progress-striped").removeClass("active");
@@ -292,7 +298,7 @@ $(function() {
var foundLocal = false;
var foundSd = false;
var found = false
var found = false;
var node = e.target;
do {
if (dropZoneLocal && node === dropZoneLocal[0]) {
@@ -406,6 +412,8 @@ $(function() {
ko.applyBindings(timelapseViewModel, timelapseElement);
}
ko.applyBindings(slicingViewModel, document.getElementById("slicing_configuration_dialog"));
// apply bindings and signal startup
_.each(additionalViewModels, function(additionalViewModel) {
if (additionalViewModel[0].hasOwnProperty("onBeforeBinding")) {
+22 -14
View File
@@ -1,8 +1,9 @@
function GcodeFilesViewModel(printerStateViewModel, loginStateViewModel) {
function GcodeFilesViewModel(printerStateViewModel, loginStateViewModel, slicingViewModel) {
var self = this;
self.printerState = printerStateViewModel;
self.loginState = loginStateViewModel;
self.slicing = slicingViewModel;
self.isErrorOrClosed = ko.observable(undefined);
self.isOperational = ko.observable(undefined);
@@ -57,11 +58,17 @@ function GcodeFilesViewModel(printerStateViewModel, loginStateViewModel) {
},
"local": function(file) {
return !(file["origin"] && file["origin"] == "sdcard");
},
"machinecode": function(file) {
return file["type"] && file["type"] == "machinecode";
},
"model": function(file) {
return file["type"] && file["type"] == "model";
}
},
"name",
[],
[["sd", "local"]],
["machinecode"],
[["sd", "local"], ["machinecode", "model"]],
0
);
@@ -152,8 +159,7 @@ function GcodeFilesViewModel(printerStateViewModel, loginStateViewModel) {
self.highlightFilename(self.printerState.filename());
};
self.loadFile = function(filename, printAfterLoad) {
var file = self.listHelper.getItem(function(item) {return item.name == filename});
self.loadFile = function(file, printAfterLoad) {
if (!file || !file.refs || !file.refs.hasOwnProperty("resource")) return;
$.ajax({
@@ -165,17 +171,9 @@ function GcodeFilesViewModel(printerStateViewModel, loginStateViewModel) {
});
};
self.removeFile = function(filename) {
var file = self.listHelper.getItem(function(item) {return item.name == filename});
self.removeFile = function(file) {
if (!file || !file.refs || !file.refs.hasOwnProperty("resource")) return;
var origin;
if (file.origin === undefined) {
origin = "local";
} else {
origin = file.origin;
}
$.ajax({
url: file.refs.resource,
type: "DELETE",
@@ -185,6 +183,12 @@ function GcodeFilesViewModel(printerStateViewModel, loginStateViewModel) {
});
};
self.sliceFile = function(file) {
if (!file) return;
self.slicing.show(file.origin, file.name);
};
self.initSdCard = function() {
self._sendSdCommand("init");
};
@@ -230,6 +234,10 @@ function GcodeFilesViewModel(printerStateViewModel, loginStateViewModel) {
return data["prints"]["last"]["success"] ? "text-success" : "text-error";
};
self.templateFor = function(data) {
return "files_template_" + data.type;
};
self.getEntryId = function(data) {
return "gcode_file_" + md5(data["name"] + ":" + data["origin"]);
};
@@ -0,0 +1,141 @@
function SlicingViewModel(loginStateViewModel) {
var self = this;
self.loginState = loginStateViewModel;
self.target = undefined;
self.file = undefined;
self.data = undefined;
self.gcodeFilename = ko.observable();
self.title = ko.observable();
self.slicer = ko.observable();
self.slicers = ko.observableArray();
self.profile = ko.observable();
self.profiles = ko.observableArray();
self.show = function(target, file) {
self.target = target;
self.file = file;
self.title(_.sprintf(gettext("Slicing %(filename)s"), {filename: self.file}));
self.gcodeFilename(self.file.substr(0, self.file.lastIndexOf(".")));
$("#slicing_configuration_dialog").modal("show");
};
self.slicer.subscribe(function(newValue) {
self.profilesForSlicer(newValue);
});
self.enableSliceButton = ko.computed(function() {
return self.gcodeFilename() != undefined
&& self.gcodeFilename().trim() != ""
&& self.slicer() != undefined
&& self.profile() != undefined;
});
self.requestData = function() {
$.ajax({
url: API_BASEURL + "slicing",
type: "GET",
dataType: "json",
success: self.fromResponse
})
};
self.fromResponse = function(data) {
self.data = data;
var selectedSlicer = undefined;
self.slicers.removeAll();
_.each(_.values(data), function(slicer) {
var name = slicer.displayName;
if (name == undefined) {
name = slicer.key;
}
if (slicer.default) {
selectedSlicer = slicer.key;
}
self.slicers.push({
key: slicer.key,
name: name
});
});
if (selectedSlicer != undefined) {
self.slicer(selectedSlicer);
}
};
self.profilesForSlicer = function(key) {
if (key == undefined) {
key = self.slicer();
}
if (key == undefined || !self.data.hasOwnProperty(key)) {
return;
}
var slicer = self.data[key];
var selectedProfile = undefined;
self.profiles.removeAll();
_.each(_.values(slicer.profiles), function(profile) {
var name = profile.displayName;
if (name == undefined) {
name = profile.key;
}
if (profile.default) {
selectedProfile = profile.key;
}
self.profiles.push({
key: profile.key,
name: name
})
});
if (selectedProfile != undefined) {
self.profile(selectedProfile);
}
};
self.slice = function() {
var gcodeFilename = self._sanitize(self.gcodeFilename());
if (!_.endsWith(gcodeFilename.toLowerCase(), ".gco")
&& !_.endsWith(gcodeFilename.toLowerCase(), ".gcode")
&& !_.endsWith(gcodeFilename.toLowerCase(), ".g")) {
gcodeFilename = gcodeFilename + ".gco";
}
var data = {
command: "slice",
slicer: self.slicer(),
profile: self.profile(),
gcode: gcodeFilename
};
$.ajax({
url: API_BASEURL + "files/" + self.target + "/" + self.file,
type: "POST",
dataType: "json",
contentType: "application/json; charset=UTF-8",
data: JSON.stringify(data)
});
$("#slicing_configuration_dialog").modal("hide");
self.gcodeFilename(undefined);
self.slicer(undefined);
self.profile(undefined);
};
self._sanitize = function(name) {
return name.replace(/[^a-zA-Z0-9\-_\.\(\) ]/g, "").replace(/ /g, "_");
};
self.onStartup = function() {
self.requestData();
};
}
+37
View File
@@ -1,3 +1,40 @@
<div id="slicing_configuration_dialog" class="modal hide fade">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3 data-bind="text: title"></h3>
</div>
<div class="modal-body">
<p>{{ _('Please configure which slicer and which slicing profile to use and name the GCode file to slice to below, or click "Cancel" if you do not wish to slice the file now.') }}</p>
<form class="form-horizontal">
<div class="control-group">
<label class="control-label">{{ _('Slicer') }}</label>
<div class="controls">
<select data-bind="options: slicers, optionsText: 'name', optionsValue: 'key', optionsCaption: '{{ _('Select a slicer...') }}', value: slicer, valueAllowUnset: true"></select>
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Slicing Profile') }}</label>
<div class="controls">
<select data-bind="options: profiles, optionsText: 'name', optionsValue: 'key', optionsCaption: '{{ _('Select a profile...') }}', value: profile, valueAllowUnset: true"></select>
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('GCode Filename') }}</label>
<div class="controls">
<div class="input-append">
<input type="text" data-bind="value: gcodeFilename">
<span class="add-on">.gco</span>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<a href="#" class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Cancel') }}</a>
<a href="#" class="btn btn-primary" data-bind="click: function() { if ($root.enableSliceButton()) { $root.slice() } }, enabled: enableSliceButton, css: {disabled: !$root.enableSliceButton()}">{{ _('Slice') }}</a>
</div>
</div>
<div id="offline_overlay" xmlns="http://www.w3.org/1999/html">
<div id="offline_overlay_background"></div>
<div id="offline_overlay_wrapper">
+25 -5
View File
@@ -183,6 +183,9 @@
<li><a href="#" data-bind="click: function() { $root.listHelper.changeSorting('name'); }"><i class="icon-ok" data-bind="style: {visibility: listHelper.currentSorting() == 'name' ? 'visible' : 'hidden'}"></i> {{ _('Sort by name') }} ({{ _('ascending') }})</a></li>
<li><a href="#" data-bind="click: function() { $root.listHelper.changeSorting('upload'); }"><i class="icon-ok" data-bind="style: {visibility: listHelper.currentSorting() == 'upload' ? 'visible' : 'hidden'}"></i> {{ _('Sort by upload date') }} ({{ _('descending') }})</a></li>
<li><a href="#" data-bind="click: function() { $root.listHelper.changeSorting('size'); }"><i class="icon-ok" data-bind="style: {visibility: listHelper.currentSorting() == 'size' ? 'visible' : 'hidden'}"></i> {{ _('Sort by file size') }} ({{ _('descending') }})</a></li>
<li class="divider"></li>
<li><a href="#" data-bind="click: function() { $root.listHelper.toggleFilter('machinecode'); }"><i class="icon-ok" data-bind="style: {visibility: _.contains(listHelper.currentFilters(), 'machinecode') ? 'visible' : 'hidden'}"></i> {{ _('Only show GCode files') }}</a></li>
<li><a href="#" data-bind="click: function() { $root.listHelper.toggleFilter('model'); }"><i class="icon-ok" data-bind="style: {visibility: _.contains(listHelper.currentFilters(), 'model') ? 'visible' : 'hidden'}"></i> {{ _('Only show STL files') }}</a></li>
{% if enableSdSupport %}
<li class="divider"></li>
<li><a href="#" data-bind="click: function() { $root.listHelper.toggleFilter('local'); }"><i class="icon-ok" data-bind="style: {visibility: _.contains(listHelper.currentFilters(), 'local') ? 'visible' : 'hidden'}"></i> {{ _('Only show files stored locally') }}</a></li>
@@ -212,7 +215,9 @@
<input type="text" class="input-block search-query" data-bind="value: searchQuery, valueUpdate: 'input'" placeholder="{{ _('Search...') }}">
</form>
<div class="gcode_files" data-bind="slimScrolledForeach: listHelper.paginatedItems">
<div class="entry" data-bind="attr: { id: $root.getEntryId($data) }">
<div class="entry" data-bind="attr: { id: $root.getEntryId($data) }, template: { name: $root.templateFor($data), data: $data }"></div>
<script type="text/html" id="files_template_machinecode">
<div class="title" data-bind="css: $root.getSuccessClass($data), style: { 'font-weight': $root.listHelper.isSelected($data) ? 'bold' : 'normal' }, text: name"></div>
<div class="uploaded">{{ _('Uploaded') }}: <span data-bind="text: formatTimeAgo(date)"></span></div>
<div class="size">{{ _('Size') }}: <span data-bind="text: formatSize(size)"></span></div>
@@ -220,11 +225,25 @@
<div class="btn-group action-buttons">
<div class="btn btn-mini toggleAdditionalData" data-bind="click: function() { if ($root.enableAdditionalData($data)) { $root.toggleAdditionalData($data); } else { return; } }, css: { disabled: !$root.enableAdditionalData($data) }"><i class="icon-chevron-down"></i></div>
<a class="btn btn-mini" data-bind="attr: {href: $root.downloadLink($data), css: {disabled: !$root.downloadLink($data)}}"><i class="icon-download-alt" title="{{ _('Download') }}"></i></a>
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableRemove($data)) { $root.removeFile($data.name); } else { return; } }, css: {disabled: !$root.enableRemove($data)}"><i class="icon-trash" title="{{ _('Remove') }}"></i></div>
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableSelect($data)) { $root.loadFile($data.name, false); } else { return; } }, css: {disabled: !$root.enableSelect($data)}"><i class="icon-folder-open" title="{{ _('Load') }}"></i></div>
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableSelect($data)) { $root.loadFile($data.name, true); } else { return; } }, css: {disabled: !$root.enableSelect($data)}"><i class="icon-print" title="{{ _('Load and Print') }}"></i></div>
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableRemove($data)) { $root.removeFile($data); } else { return; } }, css: {disabled: !$root.enableRemove($data)}"><i class="icon-trash" title="{{ _('Remove') }}"></i></div>
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableSelect($data)) { $root.loadFile($data, false); } else { return; } }, css: {disabled: !$root.enableSelect($data)}"><i class="icon-folder-open" title="{{ _('Load') }}"></i></div>
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableSelect($data)) { $root.loadFile($data, true); } else { return; } }, css: {disabled: !$root.enableSelect($data)}"><i class="icon-print" title="{{ _('Load and Print') }}"></i></div>
</div>
</div>
</script>
<script type="text/html" id="files_template_model">
<div class="title muted" data-bind="text: name"></div>
<div class="uploaded">{{ _('Uploaded') }}: <span data-bind="text: formatTimeAgo(date)"></span></div>
<div class="size">{{ _('Size') }}: <span data-bind="text: formatSize(size)"></span></div>
<div class="btn-group action-buttons">
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableRemove($data)) { $root.removeFile($data); } else { return; } }, css: {disabled: !$root.enableRemove($data)}"><i class="icon-trash" title="{{ _('Remove') }}"></i></div>
<div class="btn btn-mini" data-bind="click: function() { $root.sliceFile($data); }"><i class="icon-magic" title="{{ _('Slice') }}"></i></div>
</div>
</script>
<script type="text/html" id="files_template_folder">
<div class="title" data-bind="text: name"></div>
</script>
</div>
<div class="muted text-right">
<small>{{ _('Free') }}: <span data-bind="text: freeSpaceString"></span></small>
@@ -665,6 +684,7 @@
<script type="text/javascript" src="{{ url_for('static', filename='js/app/viewmodels/navigation.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/app/viewmodels/printerstate.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/app/viewmodels/settings.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/app/viewmodels/slicing.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/app/viewmodels/temperature.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/app/viewmodels/terminal.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/app/viewmodels/timelapse.js') }}"></script>
-23
View File
@@ -14,7 +14,6 @@
<li class="nav-header">{{ _('Features') }}</li>
<li><a href="#settings_features" data-toggle="tab">{{ _('Features') }}</a></li>
<li><a href="#settings_webcam" data-toggle="tab">{{ _('Webcam') }}</a></li>
<li><a href="#settings_cura" data-toggle="tab">{{ _('Cura') }}</a></li>
{% if enableAccessControl %}<li><a href="#settings_users" data-toggle="tab">{{ _('Access Control') }}</a></li>{% endif %}
<li><a href="#settings_api" data-toggle="tab">{{ _('API') }}</a></li>
<li class="nav-header">OctoPrint</li>
@@ -422,28 +421,6 @@
</div>
</form>
</div>
<div class="tab-pane" id="settings_cura">
<form class="form-horizontal">
<div class="control-group">
<label class="control-label" for="settings-curaEnabled">{{ _('Enable slicing via Cura') }}</label>
<div class="controls">
<input type="checkbox" data-bind="checked: cura_enabled">
</div>
</div>
<div class="control-group">
<label class="control-label" for="settings-curaPath">{{ _('Path to Cura') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: cura_path">
</div>
</div>
<div class="control-group">
<label class="control-label" for="settings-curaConfig">{{ _('Path to Cura config') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: cura_config">
</div>
</div>
</form>
</div>
<div class="tab-pane" id="settings_api">
<form class="form-horizontal">
<div class="control-group">
+1 -1
View File
@@ -132,7 +132,7 @@ def getDosFilename(input, existingFilenames, extension=None):
def findCollisionfreeName(input, extension, existingFilenames):
filename = re.sub(r"\s+", "_", input.lower().translate(None, ".\"/\\[]:;=,"))
filename = re.sub(r"\s+", "_", input.lower().translate({ord(i):None for i in ".\"/\\[]:;=,"}))
counter = 1
power = 1
+3 -2
View File
@@ -22,8 +22,8 @@ from octoprint.util.avr_isp import ispBase
from octoprint.settings import settings
from octoprint.events import eventManager, Events
from octoprint.filemanager import valid_file_type
from octoprint.filemanager.destinations import FileDestinations
from octoprint.gcodefiles import isGcodeFileName
from octoprint.util import getExceptionString, getNewTimeout, sanitizeAscii, filterNonAscii
from octoprint.util.virtual import VirtualPrinter
@@ -407,6 +407,7 @@ class MachineCom(object):
else:
self._sendNext()
except:
self._logger.exception("Error while trying to start printing")
self._errorValue = getExceptionString()
self._changeState(self.STATE_ERROR)
eventManager().fire(Events.ERROR, {"error": self.getErrorString()})
@@ -668,7 +669,7 @@ class MachineCom(object):
filename = preprocessed_line
size = None
if isGcodeFileName(filename):
if valid_file_type(filename, "gcode"):
if filterNonAscii(filename):
self._logger.warn("Got a file from printer's SD that has a non-ascii filename (%s), that shouldn't happen according to the protocol" % filename)
else:
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+226
View File
@@ -0,0 +1,226 @@
# coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import unittest
import mock
import octoprint.filemanager
class FileManagerTest(unittest.TestCase):
def setUp(self):
import octoprint.slicing
import octoprint.filemanager.storage
self.addCleanup(self.cleanUp)
# mock event manager
self.event_manager_patcher = mock.patch("octoprint.filemanager.eventManager")
event_manager = self.event_manager_patcher.start()
event_manager.return_value.fire = mock.MagicMock()
self.fire_event = event_manager.return_value.fire
self.analysis_queue = mock.MagicMock(spec=octoprint.filemanager.AnalysisQueue)
self.slicing_manager = mock.MagicMock(spec=octoprint.slicing.SlicingManager)
self.local_storage = mock.MagicMock(spec=octoprint.filemanager.storage.LocalFileStorage)
self.local_storage.analysis_backlog = iter([])
self.storage_managers = dict()
self.storage_managers[octoprint.filemanager.FileDestinations.LOCAL] = self.local_storage
self.file_manager = octoprint.filemanager.FileManager(self.analysis_queue, self.slicing_manager, initial_storage_managers=self.storage_managers)
def cleanUp(self):
self.event_manager_patcher.stop()
def test_add_file(self):
wrapper = object()
self.local_storage.add_file.return_value = ("", "test.file")
self.local_storage.get_absolute_path.return_value = "prefix/test.file"
file_path = self.file_manager.add_file(octoprint.filemanager.FileDestinations.LOCAL, "test.file", wrapper)
self.assertEquals(("", "test.file"), file_path)
self.local_storage.add_file.assert_called_once_with("test.file", wrapper, allow_overwrite=False, links=None)
self.fire_event.assert_called_once_with(octoprint.filemanager.Events.UPDATED_FILES, dict(type="printables"))
def test_remove_file(self):
self.file_manager.remove_file(octoprint.filemanager.FileDestinations.LOCAL, "test.file")
self.local_storage.remove_file.assert_called_once_with("test.file")
self.fire_event.assert_called_once_with(octoprint.filemanager.Events.UPDATED_FILES, dict(type="printables"))
def test_add_folder(self):
self.local_storage.add_folder.return_value = ("", "test_folder")
folder_path = self.file_manager.add_folder(octoprint.filemanager.FileDestinations.LOCAL, "test_folder")
self.assertEquals(("", "test_folder"), folder_path)
self.local_storage.add_folder.assert_called_once_with("test_folder", ignore_existing=True)
self.fire_event.assert_called_once_with(octoprint.filemanager.Events.UPDATED_FILES, dict(type="printables"))
def test_add_folder_not_ignoring_existing(self):
self.local_storage.add_folder.side_effect = RuntimeError("already there")
try:
self.file_manager.add_folder(octoprint.filemanager.FileDestinations.LOCAL, "test_folder", ignore_existing=False)
self.fail("Expected an exception to occur!")
except RuntimeError as e:
self.assertEquals("already there", e.message)
self.local_storage.add_folder.assert_called_once_with("test_folder", ignore_existing=False)
def test_remove_folder(self):
self.file_manager.remove_folder(octoprint.filemanager.FileDestinations.LOCAL, "test_folder")
self.local_storage.remove_folder.assert_called_once_with("test_folder", recursive=True)
self.fire_event.assert_called_once_with(octoprint.filemanager.Events.UPDATED_FILES, dict(type="printables"))
def test_remove_folder_nonrecursive(self):
self.file_manager.remove_folder(octoprint.filemanager.FileDestinations.LOCAL, "test_folder", recursive=False)
self.local_storage.remove_folder.assert_called_once_with("test_folder", recursive=False)
def test_get_metadata(self):
expected = dict(key="value")
self.local_storage.get_metadata.return_value = expected
metadata = self.file_manager.get_metadata(octoprint.filemanager.FileDestinations.LOCAL, "test.file")
self.assertEquals(metadata, expected)
self.local_storage.get_metadata.assert_called_once_with("test.file")
@mock.patch("__builtin__.open", new_callable=mock.mock_open)
@mock.patch("shutil.copyfileobj")
@mock.patch("os.remove")
@mock.patch("tempfile.NamedTemporaryFile")
@mock.patch("time.time", side_effect=[1411979916.422, 1411979932.116])
def test_slice(self, mocked_time, mocked_tempfile, mocked_os, mocked_shutil, mocked_open):
callback = mock.MagicMock()
callback_args = ("one", "two", "three")
# mock temporary file
temp_file = mock.MagicMock()
temp_file.name = "tmp.file"
mocked_tempfile.return_value = temp_file
# mock metadata on local storage
metadata = dict(hash="aabbccddeeff")
self.local_storage.get_metadata.return_value = metadata
# mock get_absolute_path method on local storage
def get_absolute_path(path):
if isinstance(path, tuple):
import os
joined_path = ""
for part in path:
joined_path = os.path.join(joined_path, part)
path = joined_path
return "prefix/" + path
self.local_storage.get_absolute_path.side_effect = get_absolute_path
# mock split_path method on local storage
def split_path(path):
return "", path
self.local_storage.split_path.side_effect = split_path
# mock add_file method on local storage
def add_file(path, file_obj, links=None, allow_overwrite=False):
file_obj.save("prefix/" + path)
return "", path
self.local_storage.add_file.side_effect = add_file
# mock slice method on slicing manager
def slice(slicer_name, source_path, dest_path, profile, done_cb, callback_args=None, overrides=None):
self.assertEquals("some_slicer", slicer_name)
self.assertEquals("prefix/source.file", source_path)
self.assertEquals("tmp.file", dest_path)
self.assertIsNone(profile)
self.assertIsNone(overrides)
if not callback_args:
callback_args = ()
done_cb(*callback_args)
self.slicing_manager.slice.side_effect = slice
##~~ execute tested method
self.file_manager.slice("some_slicer", octoprint.filemanager.FileDestinations.LOCAL, "source.file", octoprint.filemanager.FileDestinations.LOCAL, "dest.file", callback=callback, callback_args=callback_args)
# assert that events where fired
expected_events = [mock.call(octoprint.filemanager.Events.SLICING_STARTED, {"stl": "source.file", "gcode": "dest.file"}),
mock.call(octoprint.filemanager.Events.SLICING_DONE, {"stl": "source.file", "gcode": "dest.file", "time": 15.694000005722046})]
self.fire_event.call_args_list = expected_events
# assert that model links were added
expected_links = [("model", dict(name="source.file"))]
self.local_storage.add_file.assert_called_once_with("dest.file", mock.ANY, allow_overwrite=True, links=expected_links)
# assert that the generated gcode was manipulated as required
expected_open_calls = [mock.call("prefix/dest.file", "w"), mock.call("tmp.file", "r")]
self.assertEquals(mocked_open.call_args_list, expected_open_calls)
mocked_open.return_value.write.assert_called_once_with(";Generated from source.file aabbccddeeff\r")
# assert that the contents of tmp.file where copied to dest.file
mocked_shutil.assert_called_once_with(mock.ANY, mock.ANY)
# assert that the temporary file was deleted
mocked_os.assert_called_once_with("tmp.file")
# assert that our callback was called with the supplied arguments
callback.assert_called_once_with(*callback_args)
@mock.patch("os.remove")
@mock.patch("tempfile.NamedTemporaryFile")
@mock.patch("time.time", side_effect=[1411979916.422, 1411979932.116])
def test_slice_error(self, mocked_time, mocked_tempfile, mocked_os):
callback = mock.MagicMock()
callback_args = ("one", "two", "three")
# mock temporary file
temp_file = mock.MagicMock()
temp_file.name = "tmp.file"
mocked_tempfile.return_value = temp_file
# mock get_absolute_path method on local storage
def get_absolute_path(path):
if isinstance(path, tuple):
import os
joined_path = ""
for part in path:
joined_path = os.path.join(joined_path, part)
path = joined_path
return "prefix/" + path
self.local_storage.get_absolute_path.side_effect = get_absolute_path
# mock slice method on slicing manager
def slice(slicer_name, source_path, dest_path, profile, done_cb, callback_args=None, overrides=None):
self.assertEquals("some_slicer", slicer_name)
self.assertEquals("prefix/source.file", source_path)
self.assertEquals("tmp.file", dest_path)
self.assertIsNone(profile)
self.assertIsNone(overrides)
if not callback_args:
callback_args = ()
done_cb(*callback_args, _error="Something went wrong")
self.slicing_manager.slice.side_effect = slice
##~~ execute tested method
self.file_manager.slice("some_slicer", octoprint.filemanager.FileDestinations.LOCAL, "source.file", octoprint.filemanager.FileDestinations.LOCAL, "dest.file", callback=callback, callback_args=callback_args)
# assert that events where fired
expected_events = [mock.call(octoprint.filemanager.Events.SLICING_STARTED, {"stl": "source.file", "gcode": "dest.file"}),
mock.call(octoprint.filemanager.Events.SLICING_FAILED, {"stl": "source.file", "gcode": "dest.file", "reason": "Something went wrong"})]
self.fire_event.call_args_list = expected_events
# assert that the temporary file was deleted
mocked_os.assert_called_once_with("tmp.file")
# assert that time.time was only called once
mocked_time.assert_called_once()
+323
View File
@@ -0,0 +1,323 @@
# coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import unittest
import os
import octoprint.filemanager.storage
class FileWrapper(object):
def __init__(self, filename):
self.path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "_files", filename)
import hashlib
blocksize = 65536
hash = hashlib.sha1()
with open(self.path, "rb") as f:
buffer = f.read(blocksize)
while len(buffer) > 0:
hash.update(buffer)
buffer = f.read(blocksize)
self.hash = hash.hexdigest()
def save(self, destination):
import shutil
shutil.copy(self.path, destination)
FILE_BP_CASE_STL = FileWrapper("bp_case.stl")
FILE_BP_CASE_GCODE = FileWrapper("bp_case.gcode")
FILE_CRAZYRADIO_STL = FileWrapper("crazyradio.stl")
class LocalStorageTest(unittest.TestCase):
def setUp(self):
import tempfile
self.basefolder = tempfile.mkdtemp()
self.storage = octoprint.filemanager.storage.LocalFileStorage(self.basefolder)
def tearDown(self):
import shutil
shutil.rmtree(self.basefolder)
def test_add_file(self):
self._add_file("bp_case.stl", "bp_case.stl", FILE_BP_CASE_STL)
def test_add_file_overwrite(self):
self._add_file("bp_case.stl", "bp_case.stl", FILE_BP_CASE_STL)
try:
self._add_file("bp_case.stl", "bp_case.stl", FILE_BP_CASE_STL, overwrite=False)
except:
pass
self._add_file("bp_case.stl", "bp_case.stl", FILE_BP_CASE_STL, overwrite=True)
def test_add_file_with_web(self):
import time
href = "http://www.example.com"
retrieved = time.time()
stl_name = self._add_file("bp_case.stl", "bp_case.stl", FILE_BP_CASE_STL, links=[("web", dict(href=href, retrieved=retrieved))])
stl_metadata = self.storage.get_metadata(stl_name)
self.assertIsNotNone(stl_metadata)
self.assertEquals(1, len(stl_metadata["links"]))
link = stl_metadata["links"][0]
self.assertTrue("web", link["rel"])
self.assertTrue("href" in link)
self.assertEquals(href, link["href"])
self.assertTrue("retrieved" in link)
self.assertEquals(retrieved, link["retrieved"])
def test_add_file_with_association(self):
stl_name = self._add_file("bp_case.stl", "bp_case.stl", FILE_BP_CASE_STL)
gcode_name = self._add_file("bp_case.gcode", "bp_case.gcode", FILE_BP_CASE_GCODE, links=[("model", dict(name=stl_name))])
stl_metadata = self.storage.get_metadata(stl_name)
gcode_metadata = self.storage.get_metadata(gcode_name)
# forward link
self.assertEquals(1, len(gcode_metadata["links"]))
link = gcode_metadata["links"][0]
self.assertEquals("model", link["rel"])
self.assertTrue("name" in link)
self.assertEquals(stl_name, link["name"])
self.assertTrue("hash" in link)
self.assertEquals(FILE_BP_CASE_STL.hash, link["hash"])
# reverse link
self.assertEquals(1, len(stl_metadata["links"]))
link = stl_metadata["links"][0]
self.assertEquals("machinecode", link["rel"])
self.assertTrue("name" in link)
self.assertEquals(gcode_name, link["name"])
self.assertTrue("hash" in link)
self.assertEquals(FILE_BP_CASE_GCODE.hash, link["hash"])
def test_remove_file(self):
stl_name = self._add_file("bp_case.stl", "bp_case.stl", FILE_BP_CASE_STL)
gcode_name = self._add_file("bp_case.gcode", "bp_case.gcode", FILE_BP_CASE_GCODE, links=[("model", dict(name=stl_name))])
stl_metadata = self.storage.get_metadata(stl_name)
gcode_metadata = self.storage.get_metadata(gcode_name)
self.assertIsNotNone(stl_metadata)
self.assertIsNotNone(gcode_metadata)
self.storage.remove_file(stl_name)
self.assertFalse(os.path.exists(os.path.join(self.basefolder, stl_name)))
stl_metadata = self.storage.get_metadata(stl_name)
gcode_metadata = self.storage.get_metadata(gcode_name)
self.assertIsNone(stl_metadata)
self.assertIsNotNone(gcode_metadata)
self.assertEquals(0, len(gcode_metadata["links"]))
def test_add_folder(self):
self._add_folder("test", "test")
def test_add_subfolder(self):
folder_name = self._add_folder("folder with some spaces", "folder_with_some_spaces")
subfolder_name = self._add_folder((folder_name, "subfolder"), folder_name + "/subfolder")
stl_name = self._add_file((subfolder_name, "bp_case.stl"), subfolder_name + "/bp_case.stl", FILE_BP_CASE_STL)
self.assertTrue(os.path.exists(os.path.join(self.basefolder, folder_name)))
self.assertTrue(os.path.exists(os.path.join(self.basefolder, subfolder_name)))
self.assertTrue(os.path.exists(os.path.join(self.basefolder, stl_name)))
def test_remove_folder(self):
content_folder = self._add_folder("content", "content")
other_stl_name = self._add_file((content_folder, "crazyradio.stl"), content_folder + "/crazyradio.stl", FILE_CRAZYRADIO_STL)
empty_folder = self._add_folder("empty", "empty")
try:
self.storage.remove_folder(content_folder, recursive=False)
except:
self.assertTrue(os.path.exists(os.path.join(self.basefolder, content_folder)))
self.assertTrue(os.path.isdir(os.path.join(self.basefolder, content_folder)))
self.assertTrue(os.path.exists(os.path.join(self.basefolder, other_stl_name)))
self.assertIsNotNone(self.storage.get_metadata(other_stl_name))
self.storage.remove_folder(content_folder, recursive=True)
self.assertFalse(os.path.exists(os.path.join(self.basefolder, content_folder)))
self.assertFalse(os.path.isdir(os.path.join(self.basefolder, content_folder)))
self.storage.remove_folder(empty_folder, recursive=False)
self.assertFalse(os.path.exists(os.path.join(self.basefolder, empty_folder)))
self.assertFalse(os.path.isdir(os.path.join(self.basefolder, empty_folder)))
def test_remove_folder_with_metadata(self):
content_folder = self._add_folder("content", "content")
other_stl_name = self._add_file((content_folder, "crazyradio.stl"), content_folder + "/crazyradio.stl", FILE_CRAZYRADIO_STL)
self.storage.remove_file(other_stl_name)
self.storage.remove_folder(content_folder, recursive=False)
def test_list(self):
bp_case_stl = self._add_file("bp_case.stl", "bp_case.stl", FILE_BP_CASE_STL)
self._add_file("bp_case.gcode", "bp_case.gcode", FILE_BP_CASE_GCODE, links=[("model", dict(name=bp_case_stl))])
content_folder = self._add_folder("content", "content")
self._add_file((content_folder, "crazyradio.stl"), content_folder + "/crazyradio.stl", FILE_CRAZYRADIO_STL)
self._add_folder("empty", "empty")
file_list = self.storage.list_files()
self.assertEquals(4, len(file_list))
self.assertTrue("bp_case.stl" in file_list)
self.assertTrue("bp_case.gcode" in file_list)
self.assertTrue("content" in file_list)
self.assertTrue("empty" in file_list)
self.assertEquals("model", file_list["bp_case.stl"]["type"])
self.assertEquals(FILE_BP_CASE_STL.hash, file_list["bp_case.stl"]["hash"])
self.assertEquals("machinecode", file_list["bp_case.gcode"]["type"])
self.assertEquals(FILE_BP_CASE_GCODE.hash, file_list["bp_case.gcode"]["hash"])
self.assertEquals("folder", file_list[content_folder]["type"])
self.assertEquals(1, len(file_list[content_folder]["children"]))
self.assertTrue("crazyradio.stl" in file_list["content"]["children"])
self.assertEquals("model", file_list["content"]["children"]["crazyradio.stl"]["type"])
self.assertEquals(FILE_CRAZYRADIO_STL.hash, file_list["content"]["children"]["crazyradio.stl"]["hash"])
self.assertEquals("folder", file_list["empty"]["type"])
self.assertEquals(0, len(file_list["empty"]["children"]))
def test_add_link_model(self):
stl_name = self._add_file("bp_case.stl", "bp_case.stl", FILE_BP_CASE_STL)
gcode_name = self._add_file("bp_case.gcode", "bp_case.gcode", FILE_BP_CASE_GCODE)
self.storage.add_link(gcode_name, "model", dict(name=stl_name))
stl_metadata = self.storage.get_metadata(stl_name)
gcode_metadata = self.storage.get_metadata(gcode_name)
# forward link
self.assertEquals(1, len(gcode_metadata["links"]))
link = gcode_metadata["links"][0]
self.assertEquals("model", link["rel"])
self.assertTrue("name" in link)
self.assertEquals(stl_name, link["name"])
self.assertTrue("hash" in link)
self.assertEquals(FILE_BP_CASE_STL.hash, link["hash"])
# reverse link
self.assertEquals(1, len(stl_metadata["links"]))
link = stl_metadata["links"][0]
self.assertEquals("machinecode", link["rel"])
self.assertTrue("name" in link)
self.assertEquals(gcode_name, link["name"])
self.assertTrue("hash" in link)
self.assertEquals(FILE_BP_CASE_GCODE.hash, link["hash"])
def test_add_link_machinecode(self):
stl_name = self._add_file("bp_case.stl", "bp_case.stl", FILE_BP_CASE_STL)
gcode_name = self._add_file("bp_case.gcode", "bp_case.gcode", FILE_BP_CASE_GCODE)
self.storage.add_link(stl_name, "machinecode", dict(name=gcode_name))
stl_metadata = self.storage.get_metadata(stl_name)
gcode_metadata = self.storage.get_metadata(gcode_name)
# forward link
self.assertEquals(1, len(gcode_metadata["links"]))
link = gcode_metadata["links"][0]
self.assertEquals("model", link["rel"])
self.assertTrue("name" in link)
self.assertEquals(stl_name, link["name"])
self.assertTrue("hash" in link)
self.assertEquals(FILE_BP_CASE_STL.hash, link["hash"])
# reverse link
self.assertEquals(1, len(stl_metadata["links"]))
link = stl_metadata["links"][0]
self.assertEquals("machinecode", link["rel"])
self.assertTrue("name" in link)
self.assertEquals(gcode_name, link["name"])
self.assertTrue("hash" in link)
self.assertEquals(FILE_BP_CASE_GCODE.hash, link["hash"])
def test_remove_link(self):
stl_name = self._add_file("bp_case.stl", "bp_case.stl", FILE_BP_CASE_STL)
self.storage.add_link(stl_name, "web", dict(href="http://www.example.com"))
self.storage.add_link(stl_name, "web", dict(href="http://www.example2.com"))
stl_metadata = self.storage.get_metadata(stl_name)
self.assertEquals(2, len(stl_metadata["links"]))
self.storage.remove_link(stl_name, "web", dict(href="http://www.example.com"))
stl_metadata = self.storage.get_metadata(stl_name)
self.assertEquals(1, len(stl_metadata["links"]))
self.storage.remove_link(stl_name, "web", dict(href="wrong_href"))
stl_metadata = self.storage.get_metadata(stl_name)
self.assertEquals(1, len(stl_metadata["links"]))
def test_remove_link_bidirectional(self):
stl_name = self._add_file("bp_case.stl", "bp_case.stl", FILE_BP_CASE_STL)
gcode_name = self._add_file("bp_case.gcode", "bp_case.gcode", FILE_BP_CASE_GCODE)
self.storage.add_link(stl_name, "machinecode", dict(name=gcode_name))
self.storage.add_link(stl_name, "web", dict(href="http://www.example.com"))
stl_metadata = self.storage.get_metadata(stl_name)
gcode_metadata = self.storage.get_metadata(gcode_name)
self.assertEquals(1, len(gcode_metadata["links"]))
self.assertEquals(2, len(stl_metadata["links"]))
self.storage.remove_link(gcode_name, "model", dict(name=stl_name, hash=FILE_BP_CASE_STL.hash))
stl_metadata = self.storage.get_metadata(stl_name)
gcode_metadata = self.storage.get_metadata(gcode_name)
self.assertEquals(0, len(gcode_metadata["links"]))
self.assertEquals(1, len(stl_metadata["links"]))
def _add_file(self, path, expected_path, file_object, links=None, overwrite=False):
sanitized_path = self.storage.add_file(path, file_object, links=links, allow_overwrite=overwrite)
split_path = sanitized_path.split("/")
if len(split_path) == 1:
file_path = os.path.join(self.basefolder, split_path[0])
folder_path = self.basefolder
else:
file_path = os.path.join(self.basefolder, os.path.join(*split_path))
folder_path = os.path.join(self.basefolder, os.path.join(*split_path[:-1]))
self.assertEquals(expected_path, sanitized_path)
self.assertTrue(os.path.exists(file_path))
self.assertTrue(os.path.exists(os.path.join(folder_path, ".metadata.yaml")))
metadata = self.storage.get_metadata(sanitized_path)
self.assertIsNotNone(metadata)
# assert hash
self.assertTrue("hash" in metadata)
self.assertEquals(file_object.hash, metadata["hash"])
# assert presence of links if supplied
if links:
self.assertTrue("links" in metadata)
return sanitized_path
def _add_folder(self, path, expected_path):
sanitized_path = self.storage.add_folder(path)
self.assertEquals(expected_path, sanitized_path)
self.assertTrue(os.path.exists(os.path.join(self.basefolder, os.path.join(*sanitized_path.split("/")))))
self.assertTrue(os.path.isdir(os.path.join(self.basefolder, os.path.join(*sanitized_path.split("/")))))
return sanitized_path
File renamed without changes.
File renamed without changes.
@@ -13,10 +13,10 @@ class PluginTestCase(unittest.TestCase):
# TODO mock pkg_resources to return some defined entry_points
import os
plugin_folders = [os.path.join(os.path.dirname(os.path.realpath(__file__)), "test_plugins")]
plugin_folders = [os.path.join(os.path.dirname(os.path.realpath(__file__)), "_plugins")]
plugin_types = [octoprint.plugin.SettingsPlugin, octoprint.plugin.StartupPlugin]
plugin_entry_points = None
self.plugin_manager = octoprint.plugin.core.PluginManager(plugin_folders, plugin_types, plugin_entry_points)
self.plugin_manager = octoprint.plugin.core.PluginManager(plugin_folders, plugin_types, plugin_entry_points, plugin_disabled_list=[])
def test_plugin_loading(self):
self.assertEquals(4, len(self.plugin_manager.plugins))
+144
View File
@@ -0,0 +1,144 @@
# coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import unittest
import mock
import octoprint.slicing
class TestSlicingManager(unittest.TestCase):
def setUp(self):
self.addCleanup(self.cleanUp)
import tempfile
self.profile_path = tempfile.mkdtemp()
self.slicer_plugin = mock.MagicMock()
self.slicer_plugin.get_slicer_type.return_value = "mock"
# mock plugin manager
self.plugin_manager_patcher = mock.patch("octoprint.plugin.plugin_manager")
self.plugin_manager = self.plugin_manager_patcher.start()
self._mock_slicer_plugins(self.slicer_plugin)
# mock settings
self.settings_patcher = mock.patch("octoprint.slicing.settings")
settings = self.settings_patcher.start()
self.settings = settings.return_value
self.slicing_manager = octoprint.slicing.SlicingManager(self.profile_path)
def tearDown(self):
import shutil
shutil.rmtree(self.profile_path)
def cleanUp(self):
self.settings_patcher.stop()
self.plugin_manager_patcher.stop()
def _mock_slicer_plugins(self, *plugins):
def get_implementations(*types):
import octoprint.plugin
if octoprint.plugin.SlicerPlugin in types:
return dict(("slicer_" + plugin.get_slicer_type(), plugin) for plugin in plugins)
return dict()
self.plugin_manager.return_value.get_implementations.side_effect = get_implementations
def test_registered_slicers(self):
self.assertEquals(["mock"], self.slicing_manager.registered_slicers)
def test_slicing_enabled(self):
self.assertTrue(self.slicing_manager.slicing_enabled)
def test_default_slicer(self):
def get(path):
if path == ["slicing", "defaultSlicer"]:
return "mock"
else:
return None
self.settings.get.side_effect = get
self.assertEquals("mock", self.slicing_manager.default_slicer)
def test_default_slicer_unknown(self):
def get(path):
if path == ["slicing", "defaultSlicer"]:
return "unknown"
else:
return None
self.settings.get.side_effect = get
self.assertIsNone(self.slicing_manager.default_slicer)
@mock.patch("threading.Thread")
@mock.patch("tempfile.NamedTemporaryFile")
@mock.patch("os.remove")
def test_slice(self, mocked_os_remove, mocked_tempfile, mocked_thread):
# mock temporary file
temp_file = mock.MagicMock()
temp_file.name = "tmp.file"
mocked_tempfile.return_value = temp_file
# mock retrieval of default profile
def get(path):
return dict()
self.settings.get.side_effect = get
default_profile = octoprint.slicing.SlicingProfile("mock", "default", dict(layer_height=0.2, fill_density=40))
self.slicer_plugin.get_slicer_default_profile.return_value = default_profile
# mock threading
class MockThread(object):
def __init__(self):
self.target = None
self.args = None
self.mock = None
def constructor(self, target=None, args=None):
self.target = target
self.args = args
self.mock = mock.MagicMock()
self.mock.start.side_effect = self.start
return self.mock
def start(self):
self.target(*self.args)
mock_thread = MockThread()
mocked_thread.side_effect = mock_thread.constructor
# mock slicing
self.slicer_plugin.do_slice.return_value = True, None
##~~ call tested method
slicer_name = "mock"
source_path = "prefix/source.file"
dest_path = "prefix/dest.file"
profile_name = "dummy_profile"
callback = mock.MagicMock()
callback_args = ("one", "two", "three")
callback_kwargs = dict(foo="bar")
overrides = dict(layer_height=0.5)
self.slicing_manager.slice(slicer_name, source_path, dest_path, profile_name, callback, callback_args=callback_args, callback_kwargs=callback_kwargs, overrides=overrides)
# assert that temporary profile was created properly
self.slicer_plugin.save_slicer_profile.assert_called_once_with("tmp.file", default_profile, overrides=overrides)
# assert that slicing thread was created properly
mocked_thread.assert_called_once_with(target=mock.ANY, args=(self.slicer_plugin, source_path, dest_path, profile_name, overrides, callback, callback_args, callback_kwargs))
self.assertTrue(mock_thread.mock.daemon)
mock_thread.mock.start.assert_called_once()
# assert that slicer was called correctly
self.slicer_plugin.do_slice.assert_called_once_with("prefix/source.file", machinecode_path="prefix/dest.file", profile_path="tmp.file")
# assert that temporary profile was deleted again
mocked_os_remove.assert_called_once_with("tmp.file")
# assert that callback was called property
callback.assert_called_once_with(*callback_args, **callback_kwargs)
-124
View File
@@ -1,124 +0,0 @@
import unittest
from mock import Mock
from mock import patch
import logging
from octoprint.filemanager.destinations import FileDestinations
class FileManipulationTestCase(unittest.TestCase):
def setUp(self):
from octoprint.settings import settings
from octoprint.gcodefiles import GcodeManager
self.settings = settings(True)
self.manager = GcodeManager()
self.filenames = []
def tearDown(self):
for filename in self.filenames:
self.manager.removeFile(filename)
logging.info("REMOVED %s filenames" % str(len(self.filenames)))
@patch('octoprint.settings.Settings.getBoolean')
@patch('octoprint.slicers.cura.Cura.process_file')
def test_add_stl_file_curaDisabled(self, process, getterMock):
getterMock.return_value = False
fake = Mock()
fake.filename = "test_stl.stl"
self.filenames.append(fake.filename)
fake.__getitem__ = "SOMETHING"
result, done = self.manager.addFile(fake, FileDestinations.LOCAL)
logging.info("RESULT:%s" % str(result))
self.assertFalse(process.called)
self.assertIsNone(result)
self.assertTrue(done)
@patch('octoprint.settings.Settings.getBoolean')
@patch('octoprint.slicers.cura.Cura.process_file')
def test_add_stl_file_curaEnabled(self, process, getterMock):
getterMock.return_value = True
fake = Mock()
fake.filename = "test_stl.stl"
self.filenames.append(fake.filename)
fake.__getitem__ = "SOMETHING"
result, done = self.manager.addFile(fake, FileDestinations.LOCAL)
logging.info("RESULT:%s" % str(result))
getterMock.assert_called_once_with(["cura", "enabled"])
self.assertTrue(process.called)
self.assertTrue("test_stl.gcode" == result)
self.assertFalse(done)
def test_add_gcode_file(self):
fake = Mock()
fake.filename = "test_stl.gcode"
self.filenames.append(fake.filename)
fake.__getitem__ = "SOMETHING"
result, done = self.manager.addFile(fake, FileDestinations.LOCAL)
logging.info("RESULT:%s" % str(result))
self.assertTrue(fake.filename == result)
self.assertTrue(done)
class FileUtilTestCase(unittest.TestCase):
def test_isGcode(self):
from octoprint.gcodefiles import isGcodeFileName
filename = "/asdj/wefasdf/junk.stl"
result = isGcodeFileName(filename)
self.assertFalse(result)
filename = "/asdj/wefasdf/junk.gcode"
result = isGcodeFileName(filename)
self.assertTrue(result)
def test_isSTLFileName(self):
from octoprint.gcodefiles import isSTLFileName
filename = "/asdj/wefasdf/junk.stl"
result = isSTLFileName(filename)
self.assertTrue(result)
filename = "/asdj/wefasdf/junk.gcode"
result = isSTLFileName(filename)
self.assertFalse(result)
def test_genGcodeFileName(self):
from octoprint.gcodefiles import genGcodeFileName
filename = "test.stl"
expected = "test.gcode"
result = genGcodeFileName(filename)
self.assertEqual(result, expected)