Merge branch 'devel' into dev/commRefactoringNG

Conflicts:
	src/octoprint/printer/__init__.py
	src/octoprint/printer/standard.py
This commit is contained in:
Gina Häußge committed 2016-02-10 16:54:15 +01:00
commit 648c10c91f
27 files changed
+1563 -598

No files matched your search

+5 -4
View File
@@ -14,10 +14,11 @@ master
HEAD
\(detached.*
# maintenance is currently the branch for preparation of maintenance release 1.2.9
# so are any fix/... branches
maintenance 1.2.9 dedadbc9ac0305799e94ae279d3bca131629c4c5 pep440-dev
fix/.* 1.2.9 dedadbc9ac0305799e94ae279d3bca131629c4c5 pep440-dev
# maintenance is currently the branch for preparation of maintenance release 1.2.10
# so are any fix/... and improve/... branches
maintenance 1.2.10 abe68adac8f465a31bf4f3f3933190c1fc242cda pep440-dev
fix/.* 1.2.10 abe68adac8f465a31bf4f3f3933190c1fc242cda pep440-dev
improve/.* 1.2.10 abe68adac8f465a31bf4f3f3933190c1fc242cda pep440-dev
# every other branch is a development branch and thus gets resolved to 1.3.0-dev for now
.* 1.3.0 198d3450d94be1a2 pep440-dev
+1
View File
@@ -59,6 +59,7 @@ date of first contribution):
* [Richard Joyce](https://github.com/richjoyce)
* ["bwgan"](https://github.com/bwgan)
* [Siim Raud](https://github.com/2ndalpha)
* ["geoporalis"](https://github.com/geoporalis)
OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by
[Daid Braam](https://github.com/daid). Parts of its communication layer and
+39
View File
@@ -69,6 +69,45 @@
* [#1047](https://github.com/foosel/OctoPrint/issues/1047) - Fixed 90 degree
webcam rotation for iOS Safari.
## 1.2.9 (2016-02-10)
### Improvements
* [#318](https://github.com/foosel/OctoPrint/issues/318) - Snapshots for timelapses are now named in a non-colliding, job-based way, allowing a new timelapse to start while the other is still being rendered (although printing with an active timelapse rendering job is not recommended and will be solved with a proper render job queue in a later version). Timelapses that were not successfully rendered are kept for 7 days (configurable, although not via the UI so far) and can be manually rendered or deleted through a new UI component within the timelapse tab that shows up if unrendered timelapses are detected.
* [#485](https://github.com/foosel/OctoPrint/issues/485) - "Timelapse rendering" notification is now persistent, even across reloads/client switches. That should make it easier to see that a rendering job is currently in progress.
* [#939](https://github.com/foosel/OctoPrint/issues/939) - Updated to Knockout 3.4.0
* [#1204](https://github.com/foosel/OctoPrint/issues/1204) - Display total print time as estimated by GCODE viewer on GCODE viewer tab. That will allow access to an estimate even if the server hadn't yet calculated that when a print started. Note that due to slightly different implementation server and client side the resulting estimate might differ.
* OctoPrint now serves an intermediary page upon start that informs the user about the server still starting up. Once the server is detected as running, the page automatically switches to the standard interface.
* OctoPrint now displays a link to the release notes of an updated component in the update notification, the update confirmation and the version overview in the settings dialog. Please always make sure to at least skim over the release notes for new OctoPrint releases, they might contain important information that you need to know before updating.
* Improved initial page loading speeds by introducing a preemptive cache. OctoPrint will now record how you access it and on server start pre-render the page so it's ideally available in the server-side cache when you try to access it.
* Initialize login user name and password with an empty string and clear both on successful login (see [#1175](https://github.com/foosel/OctoPrint/pull/1175)).
* Added a "Refresh" button to the file list for people who modify the stored files externally (doing this is not encouraged however due to reasons of book keeping, e.g. metadata tracking etc).
* "Save" button on settings dialog is now disabled while background tasks (getting or receiving config data from the backend) are in progress.
* Improved performance of terminal tab on lower powered clients. Adaptive rate limiting now ensures the server backs off with log updates if the client can't process them fast enough. If the client is really slow, log updates get disabled automatically during printing. This behaviour can be disabled with override buttons in the terminal tab's advanced options if necessary.
* Added option to ignore any unhandled errors reported by the firmware and another option to only cancel ongoing prints on unhandled errors from the firmware (instead of instant disconnect that so far was the default).
* Made version compatibility check PEP440 compliant (important for plugin authors).
* Do not hiccup on manually sent `M28` commands.
* Persist print recovery data on print failures (origin and name of printed file, position in file when print was aborted, time and date of print failure). Currently this data isn't used anywhere, but it [can be accessed from plugins in order to add recovery functionality](https://github.com/foosel/OctoPrint-PrintRecoveryPoc) to OctoPrint.
* Small performance improvements in update checks.
* The file upload dialog will now only display files having an extension that's supported for upload (if the browser supports it, also see [#1196](https://github.com/foosel/OctoPrint/issues/1196)).
### Bug Fixes
* [#1007](https://github.com/foosel/OctoPrint/issues/1007) - Don't enable the "Print" button if no print job is selected.
* [#1181](https://github.com/foosel/OctoPrint/issues/1181) - Properly slugify UTF-8 only file names.
* [#1196](https://github.com/foosel/OctoPrint/issues/1196) - Do not show drag-n-drop overlay if server is offline.
* [#1208](https://github.com/foosel/OctoPrint/issues/1208) - Fixed `retraction_combing` profile setting being incorrectly used by bundled Cura plugin (see [#1209](https://github.com/foosel/OctoPrint/pull/1209))
* Fixed OctoPrint compatibility check in the plugin manager, could report `False` for development versions against certain versions of Python's `setuptools` (thanks to @ignaworm who stumbled over this).
* Fixed a missing parameter in `PluginSettings.remove` call (see [#1177](https://github.com/foosel/OctoPrint/pull/1177)).
* Docs: Fixed the example for a custom `M114` control to also match negative coordinates.
* Reset scroll position in settings dialog properly when re-opening it or switching tabs.
* Fixed an issue that prevented system menu entries that were added to a so far empty system menu make the menu show up.
* Fixed an issue that made requests to restricted resources fail even though the first run wizard had been completed successfully.
* Fixed an issue where an unknown command or the suppression of a command could cause the communication to stall until a communication timeout was triggered.
* Strip [unwanted ANSI characters](https://github.com/pypa/pip/issues/3418) from output produced by pip versions 8.0.0, 8.0.1 and 8.0.3 that prevents our plugin installation detection from working correctly.
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.8...1.2.9))
## 1.2.8 (2015-12-07)
### Notes for Upgraders
+69 -2
View File
@@ -13,6 +13,8 @@ or **[creating pull requests](#pull-requests)**.
* [Where can I find those log files you keep talking about?](#where-can-i-find-those-log-files-you-keep-talking-about)
* [Where can I find my browser's error console?](#where-can-i-find-my-browsers-error-console)
* [Pull requests](#pull-requests)
* [What do the branches mean?](#what-do-the-branches-mean)
* [How OctoPrint is versioned](#how-octoprint-is-versioned)
* [History](#history)
* [Footnotes](#footnotes)
@@ -225,12 +227,14 @@ See [How to open the Javascript Console in different browsers](https://webmaster
make sure to backport it to the `maintenance` branch to also include it in
the next release.
4. Make sure you **follow the current coding style**. This means:
* Tabs instead of spaces in the Python files[2]
* Spaces instead of tabs in the Javascript sources
* English language (code, variables, comments, ...)
* Comments where necessary: Tell why the code does something like it does
* Comments where necessary: Tell *why* the code does something like it does
it, structure your code
* Following the general architecture
If your PR needs to make changes to the Stylesheets, change the ``.less`` files
from which the CSS is compiled.
5. **Test your changes thoroughly**. That also means testing with usage
@@ -240,13 +244,75 @@ See [How to open the Javascript Console in different browsers](https://webmaster
your changes. Ideally **add unit tests** - OctoPrint severely lacks in that
department, but we are trying to change that, so any new code already covered
with a test suite helps a lot!
6. In your pull request's description, **state what your pull request is doing**,
6. In your pull request's description, **state what your pull request does**,
as in, what feature does it implement, what bug does it fix. The more
thoroughly you explain your intent behind the PR here, the higher the
chances it will get merged fast.
7. Important: Don't forget to **add yourself to the [AUTHORS](./AUTHORS.md)
file** :)
## What do the branches mean?
There are three main branches in OctoPrint:
* `master`: The master branch always contains the current stable release. It
is *only* updated on new releases. Will have a version number following
the scheme `x.y.z` (e.g. `1.2.9`) or - if it's absolutely necessary to
add a commit after release to this branch - `x.y.z.post<commits since x.y.z>`
(e.g. `1.2.9.post1`).
* `maintenance`: Improvements and fixes of the current release that make up
the next release go here. More or less continously updated. You can consider
this a preview of the next release version. It should be very stable at all
times. Anything you spot in here helps tremendously with getting a rock solid
next stable release, so if you want to help out development, running the
`maintenance` branch and reporting back anything you find is a very good way
to do that. Will usually have a version number following the scheme
`x.y.z+1.dev.<commits since increase of z>` for an OctoPrint version of `x.y.z`
(e.g. `1.2.10.dev12`).
* `devel`: Ongoing development of new features that will go into the next bigger
release (MINOR version number increases) will happen on this branch. Usually
kept stable, sometimes stuff can break though or lose backwards compatibility
temporarily. Can be considered the "bleeding edge". All PRs should target
*this* branch. Important improvements and fixes from PRs here are backported to
`maintenance` as needed. Will usually have a version number following the
scheme `x.y+1.0.dev<commits since increase of y>` for an OctoPrint version
of `x.y.z` (e.g. `1.3.0.dev123`).
Additionally, from time to time you might see other branches pop up in the repository.
Those usually have one of the following prefixes:
* `fix/...`: Fixes under development that are to be merged into the `maintenance`
and `devel` branches.
* `improve/...`: Improvements under development that are to be merged into the
`maintenance` and `devel` branches.
* `dev/...` or `feature/...`: New functionality under development that is to be merged
into the `devel` branch.
There is also the `gh-pages` branch, which holds OctoPrint's web page, and a couple of
older development branches that are slowly being migrated or deleted.
## How OctoPrint is versioned
OctoPrint follows the [semantic versioning scheme](http://semver.org/) of **MAJOR.MINOR.PATCH**.
The **PATCH** version number is the one increasing most often due to OctoPrint's maintenance releases.
Releases that only change the patch number indicate that they contain bug fixes and small improvements
of existing functionality. Example: 1.2.8 to 1.2.9.
The **MINOR** version number increases with releases that add a lot of new functionality and
large features. Example: 1.2.x to 1.3.0.
Finally, the **MAJOR** version number increases if there are breaking API changes that concern any of the
documented interfaces (REST API, plugin interfaces, ...). So far this hasn't happened. Example: 1.x.y to 2.0.0.
OctoPrint's version numbers are automatically generated using [versioneer](https://github.com/warner/python-versioneer)
and depend on the selected git branch, nearest git tag and commits. The generated version number
should always be [PEP440](https://www.python.org/dev/peps/pep-0440/) compatible. Unless a git tag
is used for version number determination, the version number will also contain the git hash within
the local version identifier to allow for an exact determination of the active code base
(e.g. `1.2.9.dev68+g46c7a9c`). Additionally, instances with active uncommitted changes will contain
`.dirty` in the local version identifier.
## History
* 2015-01-23: More guidelines for creating pull requests, support/questions
@@ -255,6 +321,7 @@ See [How to open the Javascript Console in different browsers](https://webmaster
* 2015-07-07: Added step to add yourself to AUTHORS when creating a PR :)
* 2015-12-01: Heavily reworked to include examples, better structure and
all information in one document.
* 2016-02-10: Added information about branch structure and versioning.
## Footnotes
* [1] - If you are wondering why, the problem is that anything that you add
+40
View File
@@ -175,6 +175,9 @@ class FileManager(object):
self._progress_plugins = []
self._preprocessor_hooks = dict()
import octoprint.settings
self._recovery_file = os.path.join(octoprint.settings.settings().getBaseFolder("data"), "print_recovery_data.yaml")
def initialize(self):
self.reload_plugins()
@@ -439,6 +442,43 @@ class FileManager(object):
# if there's no storage configured where to log the print, we'll just not log it
pass
def save_recovery_data(self, origin, path, pos):
import time
import yaml
from octoprint.util import atomic_write
data = dict(origin=origin,
path=self.path_in_storage(origin, path),
pos=pos,
date=time.time())
try:
with atomic_write(self._recovery_file) as f:
yaml.safe_dump(data, stream=f, default_flow_style=False, indent=" ", allow_unicode=True)
except:
self._logger.exception("Could not write recovery data to file {}".format(self._recovery_file))
def delete_recovery_data(self):
if not os.path.isfile(self._recovery_file):
return
try:
os.remove(self._recovery_file)
except:
self._logger.exception("Error deleting recovery data file {}".format(self._recovery_file))
def get_recovery_data(self):
if not os.path.isfile(self._recovery_file):
return None
import yaml
try:
with open(self._recovery_file) as f:
data = yaml.safe_load(f)
return data
except:
self._logger.exception("Could not read recovery data from file {}".format(self._recovery_file))
self.delete_recovery_data()
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)
@@ -65,7 +65,7 @@ def get_latest(target, check):
if returncode != 0:
return None, True
return_code, base = _git(["merge-base", "@{0}", "@{u}"], checkout_folder)
returncode, base = _git(["merge-base", "@{0}", "@{u}"], checkout_folder)
if returncode != 0:
return None, True
@@ -703,6 +703,7 @@ class VirtualPrinter(object):
def _finishSdFile(self):
self._writingToSd = False
self._selectedSdFile = None
self.outgoing.put("Done saving file")
def _sdPrintingWorker(self):
self._selectedSdFilePos = 0
+3 -3
View File
@@ -215,7 +215,7 @@ class PrinterInterface(object):
"""
raise NotImplementedError()
def select_job(self, job, start_printing=False):
def select_job(self, job, start_printing=False, pos=None):
"""
Selects the specified ``job`` for printing. Optionally can also directly start the print after selecting
the job.
@@ -235,7 +235,7 @@ class PrinterInterface(object):
# TODO add a since to the deprecation message as soon as the version this stuff will be included in is defined
@octoprint.util.deprecated("select_file has been deprecated, use select_job instead", includedoc="Replaced by :func:`select_job`")
def select_file(self, path, sd, printAfterSelect=False):
def select_file(self, path, sd, printAfterSelect=False, pos=None):
"""
Selects the specified ``path`` for printing, specifying if the file is to be found on the ``sd`` or not.
Optionally can also directly start the print after selecting the file.
@@ -257,7 +257,7 @@ class PrinterInterface(object):
"""
raise NotImplementedError()
def start_print(self):
def start_print(self, pos=None):
"""
Starts printing the currently selected file. If no file is currently selected, does nothing.
"""
+8 -6
View File
@@ -396,12 +396,12 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener,
factor = self._convert_rate_value(factor, min=75, max=125)
self._protocol.set_extrusion_multiplier(factor)
def select_job(self, job, start_printing=False):
def select_job(self, job, start_printing=False, pos=None):
self._update_job(job)
self._reset_progress_data()
if start_printing and self.is_ready():
self.start_print()
self.start_print(pos=pos)
def unselect_job(self):
self._update_job(job=None)
@@ -409,18 +409,18 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener,
# TODO add a since to the deprecation message as soon as the version this stuff will be included in is defined
@util.deprecated("select_file has been deprecated, use select_job instead", includedoc="Replaced by :func:`select_job`")
def select_file(self, path, sd, printAfterSelect=False):
def select_file(self, path, sd, printAfterSelect=False, pos=None):
if sd:
job = SDFilePrintjob("/" + path)
else:
job = LocalGcodeFilePrintjob(os.path.join(settings().getBaseFolder("uploads"), path), name=path)
self.select_job(job, start_printing=printAfterSelect)
self.select_job(job, start_printing=printAfterSelect, pos=pos)
# TODO add a since to the deprecation message as soon as the version this stuff will be included in is defined
unselect_file = util.deprecated("unselect_file has been deprecated, use unselect_job instead", includedoc="Replaced by :func:`unselect_job`")(unselect_job)
def start_print(self):
def start_print(self, pos=None):
"""
Starts the currently loaded print job.
Only starts if the printer is connected and operational, not currently printing and a printjob is loaded
@@ -432,7 +432,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener,
self._update_progress_data()
self._setCurrentZ(None)
self._protocol.process(self._job.job)
self._protocol.process(self._job.job, position=pos)
def toggle_pause_print(self):
"""
@@ -934,6 +934,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener,
# TODO
self.disconnect()
def on_comm_record_fileposition(self, origin, name, pos):
self._fileManager.save_recovery_data(origin, name, pos)
class StateMonitor(object):
def __init__(self, interval=0.5, on_update=None, on_add_temperature=None, on_add_log=None, on_add_message=None):
+1 -1
View File
@@ -150,7 +150,7 @@ def setTimelapseConfig():
return make_response("Invalid value for interval: %d" % interval)
if admin_permission.can() and "save" in data and data["save"] in valid_boolean_trues:
octoprint.timelapse.configureTimelapse(config, True)
octoprint.timelapse.configure_timelapse(config, True)
else:
octoprint.timelapse.configure_timelapse(config)
+3
View File
@@ -17,6 +17,7 @@ from octoprint.server import app, userManager, pluginManager, gettext, \
debug, LOCALES, VERSION, DISPLAY_VERSION, UI_API_KEY, BRANCH, preemptiveCache, \
NOT_MODIFIED
from octoprint.settings import settings
from octoprint.filemanager import get_all_extensions
import re
@@ -249,6 +250,7 @@ def _get_render_kwargs(templates, plugin_names, plugin_vars, now):
first_run = settings().getBoolean(["server", "firstRun"])
locales = dict((l.language, dict(language=l.language, display=l.display_name, english=l.english_name)) for l in LOCALES)
extensions = map(lambda ext: ".{}".format(ext), get_all_extensions())
#~~ prepare full set of template vars for rendering
@@ -260,6 +262,7 @@ def _get_render_kwargs(templates, plugin_names, plugin_vars, now):
templates=templates,
pluginNames=plugin_names,
locales=locales,
supportedExtensions=extensions
)
render_kwargs.update(plugin_vars)
@@ -605,8 +605,7 @@ $(function() {
self.uploadProgress
.removeClass("progress-striped active");
}
}
};
self._handleUploadDone = function(e, data) {
var filename = undefined;
@@ -621,7 +620,7 @@ $(function() {
self.requestData(filename, location, self.currentPath());
if (data.result.done) {
selef._setProgressBar(0, "", false);
self._setProgressBar(0, "", false);
}
};
@@ -634,14 +633,14 @@ $(function() {
type: "error",
hide: false
});
self.setProgressBar(0, "", false);
self._setProgressBar(0, "", false);
};
self._handleUploadProgress = function(e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
var uploaded = progress >= 100;
self.setProgressBar(progress, uploaded ? gettext("Saving ...") : gettext("Uploading ..."), uploaded);
self._setProgressBar(progress, uploaded ? gettext("Saving ...") : gettext("Uploading ..."), uploaded);
};
self._handleDragNDrop = function (e) {
@@ -424,6 +424,7 @@ $(function() {
} else {
var output = [];
output.push(gettext("Model size") + ": " + model.width.toFixed(2) + "mm &times; " + model.depth.toFixed(2) + "mm &times; " + model.height.toFixed(2) + "mm");
output.push(gettext("Estimated total print time") + ": " + formatDuration(model.printTime));
output.push(gettext("Estimated layer height") + ": " + model.layerHeight.toFixed(2) + gettext("mm"));
output.push(gettext("Layer count") + ": " + model.layersPrinted.toFixed(0) + " " + gettext("printed") + ", " + model.layersTotal.toFixed(0) + " " + gettext("visited"));
+3 -3
View File
@@ -54,18 +54,18 @@
<span class="btn btn-primary fileinput-button span6" data-bind="css: {disabled: !$root.loginState.isUser()}" style="margin-bottom: 10px">
<i class="icon-upload-alt icon-white"></i>
<span>{{ _('Upload') }}</span>
<input id="gcode_upload" type="file" name="file" class="fileinput-button" data-bind="enable: loginState.isUser()">
<input id="gcode_upload" accept="{{ ",".join(supportedExtensions) }}" type="file" name="file" class="fileinput-button" data-bind="enable: loginState.isUser()">
</span>
<span class="btn btn-primary fileinput-button span6" data-bind="css: {disabled: !$root.loginState.isUser() || !$root.isSdReady()}" style="margin-bottom: 10px">
<i class="icon-upload-alt icon-white"></i>
<span>{{ _('Upload to SD') }}</span>
<input id="gcode_upload_sd" type="file" name="file" class="fileinput-button" data-bind="enable: loginState.isUser() && isSdReady()">
<input id="gcode_upload_sd" accept="{{ ",".join(supportedExtensions) }}" type="file" name="file" class="fileinput-button" data-bind="enable: loginState.isUser() && isSdReady()">
</span>
{% else %}
<span class="btn btn-primary fileinput-button span12" data-bind="css: {disabled: !$root.loginState.isUser()}" style="margin-bottom: 10px">
<i class="icon-upload-alt icon-white"></i>
<span>{{ _('Upload') }}</span>
<input id="gcode_upload" type="file" name="file" class="fileinput-button" data-bind="enable: loginState.isUser()">
<input id="gcode_upload" accept="{{ ",".join(supportedExtensions) }}" type="file" name="file" class="fileinput-button" data-bind="enable: loginState.isUser()">
</span>
{% endif %}
</div>
@@ -57,6 +57,10 @@
</p>
</div>
</div>
<div class="muted">
<small>{{ _('Note that the time estimates in this tab are calculated by the GCODE viewer in your browser and might differ from the values calculated by the server that are displayed in the "State" and "Files" panels in the sidebar due to slightly different implementations.') }}</small>
</div>
</div>
<div data-bind="visible: waitForApproval">
<h1>{{ _('Warning') }}</h1>
+24 -2
View File
@@ -22,6 +22,8 @@ from octoprint.events import eventManager, Events
import sarge
import collections
import re
# currently configured timelapse
current = None
@@ -32,6 +34,10 @@ current_render_job = None
_capture_format = "{prefix}-%d.jpg"
_output_format = "{prefix}.mpg"
# old capture format, needed to delete old left-overs from
# versions <1.2.9
_old_capture_format_re = re.compile("^tmp_\d{5}.jpg$")
# valid timelapses
_valid_timelapse_types = ["off", "timed", "zchange"]
@@ -93,7 +99,7 @@ def get_unrendered_timelapses():
del job["timestamp"]
return job
return [util.dict_merge(dict(name=key), finalize_fields(value)) for key, value in jobs.items()]
return sorted([util.dict_merge(dict(name=key), finalize_fields(value)) for key, value in jobs.items()], key=lambda x: x["name"])
def delete_unrendered_timelapse(name):
@@ -129,14 +135,30 @@ def delete_old_unrendered_timelapses():
clean_after_days = settings().getInt(["webcam", "cleanTmpAfterDays"])
cutoff = time.time() - clean_after_days * 24 * 60 * 60
prefixes_to_clean = []
for filename in os.listdir(basedir):
try:
path = os.path.join(basedir, filename)
prefix = _extract_prefix(filename)
if prefix is None:
# might be an old tmp_00000.jpg kinda frame. we can't
# render those easily anymore, so delete that stuff
if _old_capture_format_re.match(filename):
os.remove(path)
continue
if prefix in prefixes_to_clean:
continue
if os.path.getmtime(path) < cutoff:
os.remove(path)
prefixes_to_clean.append(prefix)
except:
logging.getLogger(__name__).exception("Error while processing file {} during cleanup".format(filename))
for prefix in prefixes_to_clean:
delete_unrendered_timelapse(prefix)
def _create_render_start_handler(name, gcode=None):
def f(movie):
File diff suppressed because it is too large. Load diff
+52 -7
View File
@@ -286,6 +286,7 @@ class MachineCom(object):
self._sdFiles = []
self._sdFileToSelect = None
self._ignore_select = False
self._manualStreaming = False
# print job
self._currentFile = None
@@ -326,6 +327,7 @@ class MachineCom(object):
self._callback.on_comm_sd_files([])
if self._currentFile is not None:
self._recordFilePosition()
self._currentFile.close()
oldState = self.getStateString()
@@ -615,7 +617,7 @@ class MachineCom(object):
self.sendCommand(line)
return "\n".join(scriptLines)
def startPrint(self):
def startPrint(self, pos=None):
if not self.isOperational() or self.isPrinting():
return
@@ -643,19 +645,26 @@ class MachineCom(object):
self.sendGcodeScript("beforePrintStarted", replacements=dict(event=payload))
if self.isSdFileSelected():
#self.sendCommand("M26 S0") # setting the sd post apparently sometimes doesn't work, so we re-select
#self.sendCommand("M26 S0") # setting the sd pos apparently sometimes doesn't work, so we re-select
# the file instead
# make sure to ignore the "file selected" later on, otherwise we'll reset our progress data
self._ignore_select = True
self.sendCommand("M23 {filename}".format(filename=self._currentFile.getFilename()))
self._currentFile.setFilepos(0)
if pos is not None and isinstance(pos, int) and pos > 0:
self._currentFile.setFilepos(pos)
self.sendCommand("M26 S{}".format(pos))
else:
self._currentFile.setFilepos(0)
self.sendCommand("M24")
self._sd_status_timer = RepeatedTimer(lambda: get_interval("sdStatus", default_value=1.0), self._poll_sd_status, run_first=True)
self._sd_status_timer.start()
else:
if pos is not None and isinstance(pos, int) and pos > 0:
self._currentFile.seek(pos)
line = self._getNext()
if line is not None:
self.sendCommand(line)
@@ -722,6 +731,8 @@ class MachineCom(object):
except:
pass
self._recordFilePosition()
payload = {
"file": self._currentFile.getFilename(),
"filename": os.path.basename(self._currentFile.getFilename()),
@@ -859,6 +870,18 @@ class MachineCom(object):
self.sendCommand("M110 N%d" % number)
##~~ record aborted file positions
def _recordFilePosition(self):
if self._currentFile is None:
return
origin = self._currentFile.getFileLocation()
filename = self._currentFile.getFilename()
pos = self._currentFile.getFilepos()
self._callback.on_comm_record_fileposition(origin, filename, pos)
##~~ communication monitoring and handling
def _processTemperatures(self, line):
@@ -1079,15 +1102,14 @@ class MachineCom(object):
elif 'File selected' in line:
if self._ignore_select:
self._ignore_select = False
elif self._currentFile is not None:
elif self._currentFile is not None and self.isSdFileSelected():
# final answer to M23, at least on Marlin, Repetier and Sprinter: "File selected"
self._callback.on_comm_file_selected(self._currentFile.getFilename(), self._currentFile.getFilesize(), True)
eventManager().fire(Events.FILE_SELECTED, {
"file": self._currentFile.getFilename(),
"origin": self._currentFile.getFileLocation()
})
elif 'Writing to file' in line:
# anwer to M28, at least on Marlin, Repetier and Sprinter: "Writing to file: %s"
elif 'Writing to file' in line and self.isStreaming():
self._changeState(self.STATE_PRINTING)
self._clear_to_send.set()
line = "ok"
@@ -1269,7 +1291,7 @@ class MachineCom(object):
will be done.
"""
if self.isOperational() and not self.isStreaming() and not self._long_running_command and not self._heating:
if self.isOperational() and not self.isStreaming() and not self._long_running_command and not self._heating and not self._manualStreaming:
self.sendCommand("M105", cmd_type="temperature_poll")
def _poll_sd_status(self):
@@ -1493,6 +1515,9 @@ class MachineCom(object):
return ret
def _getNext(self):
if self._currentFile is None:
return None
line = self._currentFile.getNext()
if line is None:
if self.isStreaming():
@@ -1870,6 +1895,16 @@ class MachineCom(object):
if self.isPrinting() and not self.isSdPrinting():
self.setPause(True)
def _gcode_M28_sent(self, cmd, cmd_type=None):
if not self.isStreaming():
self._log("Detected manual streaming. Disabling temperature polling. Finish writing with M29. Do NOT attempt to print while manually streaming!")
self._manualStreaming = True
def _gcode_M29_sent(self, cmd, cmd_type=None):
if self._manualStreaming:
self._log("Manual streaming done. Re-enabling temperature polling. All is well.")
self._manualStreaming = False
def _gcode_M140_queuing(self, cmd, cmd_type=None):
if not self._printerProfileManager.get_current_or_default()["heatedBed"]:
self._log("Warn: Not sending \"{}\", printer profile has no heated bed".format(cmd))
@@ -2026,6 +2061,9 @@ class MachineComPrintCallback(object):
def on_comm_force_disconnect(self):
pass
def on_comm_record_fileposition(self, origin, name, pos):
pass
### Printing file information classes ##################################################################################
class PrintingFileInformation(object):
@@ -2124,6 +2162,13 @@ class PrintingGcodeFileInformation(PrintingFileInformation):
self._size = os.stat(self._filename).st_size
self._pos = 0
def seek(self, offset):
if self._handle is None:
return
self._handle.seek(offset)
self._pos = self._handle.tell()
def start(self):
"""
Opens the file for reading and determines the file size.
+41 -2
View File
@@ -8,6 +8,39 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms
import sarge
import logging
import re
# These regexes are based on the colorama package
# Author: Jonathan Hartley
# License: BSD-3 (https://github.com/tartley/colorama/blob/master/LICENSE.txt)
# Website: https://github.com/tartley/colorama/
_ANSI_CSI_PATTERN = "\001?\033\[(\??(?:\d|;)*)([a-zA-Z])\002?" # Control Sequence Introducer
_ANSI_OSC_PATTERN = "\001?\033\]((?:.|;)*?)(\x07)\002?" # Operating System Command
_ANSI_REGEX = re.compile("|".join([_ANSI_CSI_PATTERN,
_ANSI_OSC_PATTERN]))
def clean_ansi(line):
"""
Removes ANSI control codes from ``line``.
Parameters:
line (str or unicode): the line to process
Returns:
(str or unicode) The line without any ANSI control codes
Example::
>>> text = "Some text with some \x1b[31mred words\x1b[39m in it"
>>> clean_ansi(text)
'Some text with some red words in it'
>>> text = "We \x1b[?25lhide the cursor here and then \x1b[?25hshow it again here"
>>> clean_ansi(text)
'We hide the cursor here and then show it again here'
"""
return _ANSI_REGEX.sub("", line)
class CommandlineError(Exception):
@@ -53,11 +86,13 @@ class CommandlineCaller(object):
while p.returncode is None:
line = p.stderr.readline(timeout=0.5)
if line:
line = self._preprocess_lines(line)
self._log_stderr(line)
all_stderr.append(line)
line = p.stdout.readline(timeout=0.5)
if line:
line = self._preprocess_lines(line)
self._log_stdout(line)
all_stdout.append(line)
@@ -68,13 +103,14 @@ class CommandlineCaller(object):
stderr = p.stderr.text
if stderr:
split_lines = stderr.split("\n")
split_lines = self._preprocess_lines(
stderr.split("\n"))
self._log_stderr(*split_lines)
all_stderr += split_lines
stdout = p.stdout.text
if stdout:
split_lines = stdout.split("\n")
split_lines = self._preprocess_lines(stdout.split("\n"))
self._log_stdout(*split_lines)
all_stdout += split_lines
@@ -85,3 +121,6 @@ class CommandlineCaller(object):
def _log_stderr(self, *lines):
self.on_log_stderr(*lines)
def _preprocess_lines(self, lines):
return lines
+25 -3
View File
@@ -9,12 +9,12 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms
import sarge
import sys
import logging
import re
import site
import pkg_resources
from .commandline import CommandlineCaller
from .commandline import CommandlineCaller, clean_ansi
from octoprint.util import to_unicode
_cache = dict(version=dict(), setup=dict())
@@ -258,7 +258,7 @@ class PipCaller(CommandlineCaller):
self._logger.warn("Error while trying to run pip --version: {}".format(p.stderr.text))
return None, None
output = p.stdout.text
output = PipCaller._preprocess(p.stdout.text)
# output should look something like this:
#
# pip <version> from <path> (<python version>)
@@ -363,6 +363,28 @@ class PipCaller(CommandlineCaller):
self._logger.debug("Could not detect desired output from testballoon install, got this instead: {!r}".format(data))
return False, False, False, None
def _preprocess_lines(self, lines):
return map(self._preprocess, lines)
@staticmethod
def _preprocess(text):
"""
Strips ANSI and VT100 cursor control characters from line and makes sure it's a unicode.
Parameters:
text (str or unicode): The text to process
Returns:
(unicode) The processed text as a unicode, stripped of ANSI and VT100 cursor show/hide codes
Example::
>>> text = b'some text with some\x1b[?25h ANSI codes for \x1b[31mred words\x1b[39m and\x1b[?25l also some cursor control codes'
>>> PipCaller._preprocess(text)
u'some text with some ANSI codes for red words and also some cursor control codes'
"""
return to_unicode(clean_ansi(text))
class LocalPipCaller(PipCaller):
"""
The LocalPipCaller always uses the pip instance associated with
+135
View File
@@ -13,6 +13,8 @@ import mock
import octoprint.filemanager
import octoprint.filemanager.util
import octoprint.settings
class FilemanagerMethodTest(unittest.TestCase):
def setUp(self):
@@ -124,6 +126,15 @@ class FileManagerTest(unittest.TestCase):
self.plugin_manager_patcher = mock.patch("octoprint.plugin.plugin_manager")
self.plugin_manager = self.plugin_manager_patcher.start()
# mock settings
self.settings_patcher = mock.patch("octoprint.settings.settings")
self.settings_getter = self.settings_patcher.start()
self.settings = mock.create_autospec(octoprint.settings.Settings)
self.settings.getBaseFolder.return_value = "/path/to/a/base_folder"
self.settings_getter.return_value = self.settings
self.analysis_queue = mock.MagicMock(spec=octoprint.filemanager.AnalysisQueue)
self.slicing_manager = mock.MagicMock(spec=octoprint.slicing.SlicingManager)
@@ -141,6 +152,7 @@ class FileManagerTest(unittest.TestCase):
def cleanUp(self):
self.event_manager_patcher.stop()
self.plugin_manager_patcher.stop()
self.settings_patcher.stop()
def test_add_file(self):
wrapper = object()
@@ -192,6 +204,129 @@ class FileManagerTest(unittest.TestCase):
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)
@mock.patch("octoprint.util.atomic_write", create=True)
@mock.patch("yaml.safe_dump", create=True)
@mock.patch("time.time")
def test_save_recovery_data(self, mock_time, mock_yaml_safe_dump, mock_atomic_write):
import os
now = 123456789
path = "some_file.gco"
pos = 1234
recovery_file = os.path.join("/path/to/a/base_folder", "print_recovery_data.yaml")
mock_atomic_write.return_value = mock.MagicMock(spec=file)
mock_atomic_write_handle = mock_atomic_write.return_value.__enter__.return_value
mock_time.return_value = now
self.local_storage.path_in_storage.return_value = path
self.file_manager.save_recovery_data(octoprint.filemanager.FileDestinations.LOCAL, path, pos)
expected = dict(origin=octoprint.filemanager.FileDestinations.LOCAL,
path=path,
pos=pos,
date=now)
mock_atomic_write.assert_called_with(recovery_file)
mock_yaml_safe_dump.assert_called_with(expected, stream=mock_atomic_write_handle, default_flow_style=False, indent=" ", allow_unicode=True)
@mock.patch("octoprint.util.atomic_write", create=True)
@mock.patch("yaml.safe_dump", create=True)
@mock.patch("time.time")
def test_save_recovery_data(self, mock_time, mock_yaml_safe_dump, mock_atomic_write):
import os
now = 123456789
path = "some_file.gco"
pos = 1234
recovery_file = os.path.join("/path/to/a/base_folder", "print_recovery_data.yaml")
mock_atomic_write.return_value = mock.MagicMock(spec=file)
mock_atomic_write_handle = mock_atomic_write.return_value.__enter__.return_value
mock_time.return_value = now
self.local_storage.path_in_storage.return_value = path
mock_yaml_safe_dump.side_effect = RuntimeError
self.file_manager.save_recovery_data(octoprint.filemanager.FileDestinations.LOCAL, path, pos)
@mock.patch("os.path.isfile")
@mock.patch("os.remove")
def test_delete_recovery_data(self, mock_remove, mock_isfile):
import os
recovery_file = os.path.join("/path/to/a/base_folder", "print_recovery_data.yaml")
mock_isfile.return_value = True
self.file_manager.delete_recovery_data()
mock_remove.assert_called_with(recovery_file)
@mock.patch("os.path.isfile")
@mock.patch("os.remove")
def test_delete_recovery_data_no_file(self, mock_remove, mock_isfile):
mock_isfile.return_value = False
self.file_manager.delete_recovery_data()
self.assertFalse(mock_remove.called)
@mock.patch("os.path.isfile")
@mock.patch("os.remove")
def test_delete_recovery_data_error(self, mock_remove, mock_isfile):
mock_isfile.return_value = True
mock_remove.side_effect = RuntimeError
self.file_manager.delete_recovery_data()
@mock.patch("os.path.isfile")
@mock.patch("yaml.safe_load")
def test_get_recovery_data(self, mock_yaml_safe_load, mock_isfile):
import os
recovery_file = os.path.join("/path/to/a/base_folder", "print_recovery_data.yaml")
mock_isfile.return_value = True
data = dict(path="some_path.gco",
origin="local",
pos=1234,
date=123456789)
mock_yaml_safe_load.return_value = data
with mock.patch("__builtin__.open", mock.mock_open(read_data=data), create=True) as m:
result = self.file_manager.get_recovery_data()
self.assertDictEqual(data, result)
m.assert_called_with(recovery_file)
mock_handle = m()
mock_yaml_safe_load.assert_called_with(mock_handle)
@mock.patch("os.path.isfile")
def test_get_recovery_data_no_file(self, mock_isfile):
mock_isfile.return_value = False
result = self.file_manager.get_recovery_data()
self.assertIsNone(result)
@mock.patch("os.path.isfile")
@mock.patch("yaml.safe_load")
@mock.patch("os.remove")
def test_get_recovery_data_broken_file(self, mock_remove, mock_yaml_safe_load, mock_isfile):
import os
recovery_file = os.path.join("/path/to/a/base_folder", "print_recovery_data.yaml")
mock_isfile.return_value = True
mock_yaml_safe_load.side_effect = RuntimeError
result = self.file_manager.get_recovery_data()
self.assertIsNone(result)
mock_remove.assert_called_with(recovery_file)
def test_get_metadata(self):
expected = dict(key="value")
self.local_storage.get_metadata.return_value = expected
+9
View File
@@ -0,0 +1,9 @@
# coding=utf-8
"""
Unit tests for ``octoprint.timelapse``.
"""
from __future__ import absolute_import
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License"
+172
View File
@@ -0,0 +1,172 @@
# coding=utf-8
from __future__ import absolute_import
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License"
import unittest
import mock
import os
import time
from collections import namedtuple
_stat = namedtuple("StatResult", "st_size, st_ctime, st_mtime")
import octoprint.settings
import octoprint.timelapse
class TimelapseTest(unittest.TestCase):
def setUp(self):
# mock settings
self.settings_patcher = mock.patch("octoprint.timelapse.settings")
self.settings_getter = self.settings_patcher.start()
self.settings = mock.create_autospec(octoprint.settings.Settings)
self.settings_getter.return_value = self.settings
self.now = time.time()
def cleanUp(self):
self.settings_patcher.stop()
@mock.patch("os.remove")
@mock.patch("os.listdir")
def test_delete_unrendered_timelapse(self, mock_listdir, mock_remove):
## prepare
mocked_path = "/path/to/timelapse/tmp"
mocked_files = ["a-0.jpg",
"a-1.jpg",
"a-2.jpg",
"b-0.jpg",
"b-1.jpg",
"tmp_00000.jpg",
"tmp_00001.jpg"]
self.settings.getBaseFolder.return_value = mocked_path
mock_listdir.return_value = mocked_files
## test
octoprint.timelapse.delete_unrendered_timelapse("b")
## verify
expected_deletions = map(lambda x: os.path.join(mocked_path, x), ["b-0.jpg",
"b-1.jpg"])
expected_deletion_calls = map(mock.call, expected_deletions)
self.assertListEqual(mock_remove.mock_calls, expected_deletion_calls)
@mock.patch("time.time")
@mock.patch("os.remove")
@mock.patch("os.path.getmtime")
@mock.patch("os.listdir")
def test_delete_old_unrendered_timelapses(self, mock_listdir, mock_mtime, mock_remove, mock_time):
## prepare
mocked_path = "/path/to/timelapse/tmp"
mocked_files = ["old-0.jpg",
"old-1.jpg",
"old-2.jpg",
"prefix-0.jpg",
"prefix-1.jpg",
"tmp_00000.jpg",
"tmp_00001.jpg"]
now = self.now
days = 1
def mtime(p):
if p.startswith(os.path.join(mocked_path, "old-0")):
# old-0 is definitely older than cutoff
return 0
else:
# all other files were just created
return now
self.settings.getBaseFolder.return_value = mocked_path
self.settings.getInt.return_value = days
mock_time.return_value = now
mock_listdir.return_value = mocked_files
mock_mtime.side_effect = mtime
## test
octoprint.timelapse.delete_old_unrendered_timelapses()
## verify
expected_deletions = map(lambda x: os.path.join(mocked_path, x), ["tmp_00000.jpg",
"tmp_00001.jpg",
"old-0.jpg",
"old-1.jpg",
"old-2.jpg"])
expected_deletion_calls = map(mock.call, expected_deletions)
self.assertListEqual(mock_remove.mock_calls, expected_deletion_calls)
@mock.patch("os.stat")
@mock.patch("os.listdir")
def test_get_finished_timelapses(self, mock_listdir, mock_stat):
## prepare
files = dict()
files["one.mpg"] = _stat(st_size=1024, st_ctime=self.now, st_mtime=self.now)
files["nope.jpg"] = _stat(st_size=100, st_ctime=self.now, st_mtime=self.now)
files["two.mpg"] = _stat(st_size=2048, st_ctime=self.now, st_mtime=self.now)
mocked_path = "/path/to/timelapse"
self.settings.getBaseFolder.return_value = mocked_path
mock_listdir.return_value = sorted(files.keys())
def stat(p):
name = p[len(mocked_path) + 1:]
return files[name]
mock_stat.side_effect = stat
## test
result = octoprint.timelapse.get_finished_timelapses()
## verify
self.assertEqual(len(result), 2)
self.assertEqual(result[0]["name"], "one.mpg")
self.assertEqual(result[0]["bytes"], 1024)
self.assertEqual(result[1]["name"], "two.mpg")
self.assertEqual(result[1]["bytes"], 2048)
@mock.patch("os.stat")
@mock.patch("os.listdir")
def test_unrendered_timelapses(self, mock_listdir, mock_stat):
## prepare
files = dict()
files["one-0.jpg"] = _stat(st_size=1, st_ctime=self.now - 1, st_mtime=self.now - 1)
files["one-1.jpg"] = _stat(st_size=2, st_ctime=self.now, st_mtime=self.now)
files["one-2.jpg"] = _stat(st_size=3, st_ctime=self.now, st_mtime=self.now)
files["nope.mpg"] = _stat(st_size=2048, st_ctime=self.now, st_mtime=self.now)
files["two-0.jpg"] = _stat(st_size=4, st_ctime=self.now, st_mtime=self.now)
files["two-1.jpg"] = _stat(st_size=5, st_ctime=self.now, st_mtime=self.now)
mocked_path = "/path/to/timelapse/tmp"
self.settings.getBaseFolder.return_value = mocked_path
mock_listdir.return_value = sorted(files.keys())
def stat(p):
name = p[len(mocked_path) + 1:]
return files[name]
mock_stat.side_effect = stat
## test
result = octoprint.timelapse.get_unrendered_timelapses()
## verify
self.assertEqual(len(result), 2)
self.assertEqual(result[0]["name"], "one")
self.assertEqual(result[0]["count"], 3)
self.assertEqual(result[0]["bytes"], 6)
self.assertEqual(result[1]["name"], "two")
self.assertEqual(result[1]["count"], 2)
self.assertEqual(result[1]["bytes"], 9)
Binary file not shown.
File diff suppressed because it is too large. Load diff
+324 -185
View File
File diff suppressed because it is too large. Load diff