Compare commits
51
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f656a7b0cb | ||
|
|
6305c4d2eb | ||
|
|
b5cf20a1de | ||
|
|
5807b606f0 | ||
|
|
398eaf58a9 | ||
|
|
4a933228c7 | ||
|
|
56caa7750c | ||
|
|
38a47bb2a8 | ||
|
|
e6f9003549 | ||
|
|
5cadf85401 | ||
|
|
baab1ce70a | ||
|
|
cbaf848711 | ||
|
|
85060b972a | ||
|
|
29aefdec08 | ||
|
|
6e01a361c5 | ||
|
|
542ccb5421 | ||
|
|
6d8eb682c1 | ||
|
|
d701c261c3 | ||
|
|
7b16f38ba3 | ||
|
|
337329eda0 | ||
|
|
47b7552f91 | ||
|
|
6736224962 | ||
|
|
c9009496f6 | ||
|
|
d393a6730c | ||
|
|
069bfdd9f8 | ||
|
|
23d2cdec76 | ||
|
|
1a308a1bc7 | ||
|
|
13098dde00 | ||
|
|
27d1a6ca37 | ||
|
|
1616fb4de8 | ||
|
|
07d8d4b88d | ||
|
|
2a3d9c291d | ||
|
|
b36290a1f2 | ||
|
|
48d74ef2fd | ||
|
|
35e20162ec | ||
|
|
c82ec3d3af | ||
|
|
5c06bd5036 | ||
|
|
21034b381c | ||
|
|
beb5850361 | ||
|
|
1ea0cf9213 | ||
|
|
4081a25f48 | ||
|
|
718a102d44 | ||
|
|
49f4a0c5b0 | ||
|
|
d267a752cd | ||
|
|
632724a023 | ||
|
|
eb48a50139 | ||
|
|
0a3dc4b354 | ||
|
|
fe134e7986 | ||
|
|
b5f40cfd69 | ||
|
|
3fb9248d2a | ||
|
|
3dd0ace076 |
No files matched your search
@@ -0,0 +1,60 @@
|
||||
Please read the "guidelines for contributing" that are linked ^-- just
|
||||
up there. Also read the FAQ: https://github.com/foosel/OctoPrint/wiki/FAQ.
|
||||
|
||||
This is a bug and feature tracker, please only use it to report bugs
|
||||
or request features within OctoPrint (not OctoPi, not any OctoPrint
|
||||
plugins and not unofficial OctoPrint versions). Mark requests with
|
||||
a [Request] prefix in the title please. Fully fill out the bug reporting
|
||||
template for bug reports.
|
||||
|
||||
Do not seek support here ("I need help with ..."), that belongs on
|
||||
the mailing list or the G+ community (both linked in the "guidelines
|
||||
for contributing" linked above, read it!), NOT here.
|
||||
|
||||
Thank you!
|
||||
|
||||
----
|
||||
|
||||
#### What were you doing?
|
||||
|
||||
[Please be as specific as possible here. The maintainers will need to reproduce
|
||||
your issue in order to fix it and that is not possible if they don't know
|
||||
what you did to get it to happen in the first place. If you encountered
|
||||
a problem with specific files of any sorts, make sure to also include a link to a file
|
||||
with which to reproduce the problem.]
|
||||
|
||||
#### What did you expect to happen?
|
||||
|
||||
#### What happened instead?
|
||||
|
||||
#### Branch & Commit or Version of OctoPrint
|
||||
|
||||
[Can be found in the lower left corner of the web interface.]
|
||||
|
||||
#### Printer model & used firmware incl. version
|
||||
|
||||
[If applicable, always include if unsure.]
|
||||
|
||||
#### Browser and Version of Browser, Operating System running Browser
|
||||
|
||||
[If applicable, always include if unsure.]
|
||||
|
||||
#### Link to octoprint.log
|
||||
|
||||
[On gist.github.com or pastebin.com. Always include and never truncate.]
|
||||
|
||||
#### Link to contents of terminal tab or serial.log
|
||||
|
||||
[On gist.github.com or pastebin.com. If applicable, always include if unsure or
|
||||
reporting communication issues. Never truncate.]
|
||||
|
||||
#### Link to contents of Javascript console in the browser
|
||||
|
||||
[On gist.github.com or pastebin.com or alternatively a screenshot. If applicable -
|
||||
always include if unsure or reporting UI issues.]
|
||||
|
||||
#### Screenshot(s) showing the problem:
|
||||
|
||||
[If applicable. Always include if unsure or reporting UI issues.]
|
||||
|
||||
I have read the FAQ.
|
||||
@@ -0,0 +1,50 @@
|
||||
Thank you for your interest into contributing to OctoPrint, it's
|
||||
highly appreciated!
|
||||
|
||||
Please make sure you have read the "guidelines for contributing" as
|
||||
linked just above this form, there's a section on Pull Requests in there
|
||||
as well that contains important information.
|
||||
|
||||
As a summary, please make sure you have ticked all points on this
|
||||
checklist:
|
||||
|
||||
* [ ] Your changes are not possible to do through a plugin and relevant
|
||||
to a large audience (ideally all users of OctoPrint)
|
||||
* [ ] If your changes are large or otherwise disruptive: You have
|
||||
made sure your changes don't interfere with current development by
|
||||
talking it through with the maintainers, e.g. through a
|
||||
Brainstorming ticket
|
||||
* [ ] Your PR targets OctoPrint's devel branch (not master,
|
||||
maintenance or anything else)
|
||||
* [ ] Your PR was opened from a custom branch on your repository
|
||||
(no PRs from your version of master, maintenance or devel please),
|
||||
e.g. dev/my_new_feature
|
||||
* [ ] Your PR only contains relevant changes: no unrelated files,
|
||||
no dead code, ideally only one commit - rebase your PR if necessary!
|
||||
* [ ] Your changes follow the coding style
|
||||
* [ ] If your changes include style sheets: You have modified the
|
||||
.less source files, not the .css files (those are generated with
|
||||
lessc)
|
||||
* [ ] You have tested your changes (please state how!) - ideally you
|
||||
have added unit tests
|
||||
* [ ] You have run the existing unit tests against your changes and
|
||||
nothing broke
|
||||
* [ ] You have added yourself to the AUTHORS.md file :)
|
||||
|
||||
Feel free to delete all this help text, then describe
|
||||
your PR further. You may use the template provided below to do that.
|
||||
The more details the better!
|
||||
|
||||
----
|
||||
|
||||
#### What does this PR do and why is it necessary?
|
||||
|
||||
#### How was it tested? How can it be tested by the reviewer?
|
||||
|
||||
#### Any background context you want to provide?
|
||||
|
||||
#### What are the relevant tickets if any?
|
||||
|
||||
#### Screenshots (if appropriate)
|
||||
|
||||
#### Further notes
|
||||
+4
-4
@@ -14,11 +14,11 @@ master
|
||||
HEAD
|
||||
\(detached.*
|
||||
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.2.9
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.2.10
|
||||
# so are any fix/... and improve/... branches
|
||||
maintenance 1.2.9 dedadbc9ac0305799e94ae279d3bca131629c4c5 pep440-dev
|
||||
fix/.* 1.2.9 dedadbc9ac0305799e94ae279d3bca131629c4c5 pep440-dev
|
||||
improve/.* 1.2.9 dedadbc9ac0305799e94ae279d3bca131629c4c5 pep440-dev
|
||||
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
|
||||
@@ -59,6 +59,7 @@ date of first contribution):
|
||||
* ["bwgan"](https://github.com/bwgan)
|
||||
* [Siim Raud](https://github.com/2ndalpha)
|
||||
* ["geoporalis"](https://github.com/geoporalis)
|
||||
* [Andrew Malota](https://github.com/2bitoperations)
|
||||
|
||||
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
|
||||
|
||||
+63
-18
@@ -90,7 +90,9 @@ following section *completely*. Thank you! :)
|
||||
the people maintaining them instead.
|
||||
|
||||
2. Please make sure to **test out the current version** of OctoPrint to see
|
||||
whether the problem you are encountering still exists.
|
||||
whether the problem you are encountering still exists, and **test without
|
||||
any non-bundled plugins enabled** to make sure it's not a misbehaving
|
||||
plugin causing the issue at hand.
|
||||
|
||||
If you are feeling up to it you might also want to try the current development
|
||||
version of OctoPrint (if you aren't already). Refer to the [FAQ](https://github.com/foosel/OctoPrint/wiki/FAQ)
|
||||
@@ -104,12 +106,26 @@ following section *completely*. Thank you! :)
|
||||
fixing it. Take the time to filter through possible duplicates and be really
|
||||
sure that your problem definitely is a new one. Try more than one search query
|
||||
(e.g. do not only search for "webcam" if you happen to run into an issue
|
||||
with your webcam, also search for "timelapse" etc).
|
||||
with your webcam, also search for "timelapse" etc). Do not only read the subject lines
|
||||
of tickets that look like they might be related, but also read the ticket itself!
|
||||
|
||||
**Very important:** Please make absolutely sure that if you find a bug that looks like
|
||||
it is the same as your's, it actually behaves the same as your's. E.g. if someone gives steps
|
||||
to reproduce his bug that looks like your's, reproduce the bug like that if possible,
|
||||
and only add a "me too" if you actually can reproduce the same
|
||||
issue. Also **provide all information** as [described below](#what-should-i-include-in-a-bug-report)
|
||||
and whatever was additionally requested over the course of the ticket
|
||||
even if you "only" add to an existing ticket. The more information available regarding a bug, the higher
|
||||
the chances of reproducing and solving it. But "me too" on an actually unrelated ticket
|
||||
makes it more difficult due to on top of having to figure out the original problem
|
||||
there's now also a [red herring](https://en.wikipedia.org/wiki/Red_herring) interfering - so please be
|
||||
very diligent here!
|
||||
|
||||
### What should I include in a bug report?
|
||||
|
||||
Always use the following template (you can remove what's within `[...]`, that's
|
||||
only provided here as some additional information for you):
|
||||
only provided here as some additional information for you), **even if only adding a
|
||||
"me too" to an existing ticket**:
|
||||
|
||||
#### What were you doing?
|
||||
|
||||
@@ -155,6 +171,8 @@ only provided here as some additional information for you):
|
||||
|
||||
I have read the FAQ.
|
||||
|
||||
Copy-paste this template **completely**. Do not skip any lines!
|
||||
|
||||
### Where can I find which version and branch I'm on?
|
||||
|
||||
You can find out all of them by taking a look into the lower left corner of the
|
||||
@@ -214,43 +232,67 @@ See [How to open the Javascript Console in different browsers](https://webmaster
|
||||
implement your feature as a plugin, create a "Brainstorming" ticket to get
|
||||
the discussion going on how best to solve *this* in OctoPrint's plugin
|
||||
system - maybe that's the actual PR you have been waiting for to contribute :)
|
||||
2. If you plan to make **any large changes to the code or appearance, please
|
||||
open a "Brainstorming" ticket first** so that we can determine if it's a
|
||||
good time for your specific pull request. It might be that we're currently
|
||||
in the process of making heavy changes to the code locations you'd target
|
||||
as well, or your approach doesn't fit the general "project vision", and
|
||||
that would just cause unnecessary work and frustration for everyone or
|
||||
2. If you plan to make **any large or otherwise disruptive changes to the
|
||||
code or appearance, please open a "Brainstorming" ticket first** so
|
||||
that we can determine if it's a good time for your specific pull
|
||||
request. It might be that we're currently in the process of making
|
||||
heavy changes to the code locations you'd target as well, or your
|
||||
approach doesn't fit the general "project vision", and that would
|
||||
just cause unnecessary work and frustration for everyone or
|
||||
possibly get the PR rejected.
|
||||
3. Create your pull request **from a custom branch** on your end (e.g.
|
||||
`dev/myNewFeature`)[1] **against the `devel` branch**. Create **one pull request
|
||||
per feature/bug fix**. If your PR contains an important bug fix, we will
|
||||
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:
|
||||
|
||||
4. Make sure there are **only relevant changes** included in your PR. No
|
||||
changes to unrelated files, no additional files that don't belong (e.g.
|
||||
commits of your full virtual environment). Make sure your PR consists
|
||||
**ideally of only one commit** (use git's rebase and squash functionality).
|
||||
5. 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
|
||||
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
|
||||
* If your PR needs to make changes to the Stylesheets, change the
|
||||
``.less`` files from which the CSS is compiled.
|
||||
* Make sure you do not add dead code (e.g. commented out left-overs
|
||||
from experiments).
|
||||
6. Ensure your changes **pass the existing unit tests**. PRs that break
|
||||
those cannot be accepted.
|
||||
7. **Test your changes thoroughly**. That also means testing with usage
|
||||
scenarios you don't normally use, e.g. if you only use access control, test
|
||||
without and vice versa. If you only test with your printer, test with the
|
||||
virtual printer and vice versa. State in your pull request how your tested
|
||||
your changes. Ideally **add unit tests** - OctoPrint severly 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 does**,
|
||||
8. 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)
|
||||
chances it will get merged fast. There is a template provided below
|
||||
that can help you here.
|
||||
9. Don't forget to **add yourself to the [AUTHORS](./AUTHORS.md)
|
||||
file** :)
|
||||
|
||||
Template to use for Pull Request descriptions:
|
||||
|
||||
```
|
||||
#### What does this PR do and why is it necessary?
|
||||
|
||||
#### How was it tested? How can it be tested by the reviewer?
|
||||
|
||||
#### Any background context you want to provide?
|
||||
|
||||
#### What are the relevant tickets if any?
|
||||
|
||||
#### Screenshots (if appropriate)
|
||||
|
||||
#### Further notes
|
||||
```
|
||||
|
||||
## What do the branches mean?
|
||||
|
||||
There are three main branches in OctoPrint:
|
||||
@@ -322,6 +364,9 @@ the local version identifier to allow for an exact determination of the active c
|
||||
* 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.
|
||||
* 2016-02-16: Added requirement to add information from template to existing
|
||||
tickets as well, explained issue with "me too" red herrings.
|
||||
* 2016-03-14: Some more requirements for PRs, and a PR template.
|
||||
|
||||
## Footnotes
|
||||
* [1] - If you are wondering why, the problem is that anything that you add
|
||||
|
||||
@@ -611,6 +611,27 @@ Use the following settings to configure the serial connection to the printer:
|
||||
additionalPorts:
|
||||
- /dev/myPrinterSymlink
|
||||
|
||||
# Commands which are known to take a long time to be acknowledged by the firmware. E.g.
|
||||
# homing, dwelling, auto leveling etc. Defaults to the below commands.
|
||||
longRunningCommands:
|
||||
- G4
|
||||
- G28
|
||||
- G29
|
||||
- G30
|
||||
- G32
|
||||
- M400
|
||||
- M226
|
||||
|
||||
# Commands which need to always be send with a checksum. Defaults to only M110
|
||||
checksumRequiringCommands:
|
||||
- M110
|
||||
|
||||
# Command to send in order to initiate a handshake with the printer.
|
||||
# Defaults to "M110 N0" which simply resets the line numbers in the firmware and which
|
||||
# should be acknowledged with a simple "ok".
|
||||
helloCommand:
|
||||
- M110 N0
|
||||
|
||||
.. _sec-configuration-config_yaml-server:
|
||||
|
||||
Server
|
||||
|
||||
@@ -50,7 +50,7 @@ defaults = dict(
|
||||
wall_thickness=0.8,
|
||||
solid_layer_thickness=0.6,
|
||||
print_temperature=[220, 0, 0, 0],
|
||||
print_bed_temperature=70,
|
||||
print_bed_temperature=0,
|
||||
platform_adhesion=PlatformAdhesionTypes.NONE,
|
||||
filament_diameter=[2.85, 0, 0, 0],
|
||||
filament_flow=100.0,
|
||||
|
||||
@@ -61,6 +61,7 @@ class VirtualPrinter():
|
||||
self._selectedSdFileSize = None
|
||||
self._selectedSdFilePos = None
|
||||
self._writingToSd = False
|
||||
self._writingToSdHandle = None
|
||||
self._newSdFilePos = None
|
||||
self._heatupThread = None
|
||||
|
||||
@@ -72,6 +73,8 @@ class VirtualPrinter():
|
||||
|
||||
self._echoOnM117 = settings().getBoolean(["devel", "virtualPrinter", "echoOnM117"])
|
||||
|
||||
self._brokenM29 = settings().getBoolean(["devel", "virtualPrinter", "brokenM29"])
|
||||
|
||||
self.currentLine = 0
|
||||
self.lastN = 0
|
||||
|
||||
@@ -88,6 +91,10 @@ class VirtualPrinter():
|
||||
|
||||
self._killed = False
|
||||
|
||||
self._triggerResendAt100 = True
|
||||
self._triggerResendWithTimeoutAt105 = True
|
||||
self._triggeredResendWithTimeoutAt105 = False
|
||||
|
||||
waitThread = threading.Thread(target=self._sendWaitAfterTimeout)
|
||||
waitThread.start()
|
||||
|
||||
@@ -145,6 +152,10 @@ class VirtualPrinter():
|
||||
linenumber = int(re.search("N([0-9]+)", data).group(1))
|
||||
self.lastN = linenumber
|
||||
self.currentLine = linenumber
|
||||
|
||||
self._triggerResendAt100 = True
|
||||
self._triggerResendWithTimeoutAt105 = True
|
||||
|
||||
self._sendOk()
|
||||
continue
|
||||
elif data.startswith("N"):
|
||||
@@ -153,10 +164,18 @@ class VirtualPrinter():
|
||||
if linenumber != expected:
|
||||
self._triggerResend(actual=linenumber)
|
||||
continue
|
||||
elif self.currentLine == 101:
|
||||
elif linenumber == 100 and self._triggerResendAt100:
|
||||
# simulate a resend at line 100
|
||||
self._triggerResendAt100 = False
|
||||
self._triggerResend(expected=100)
|
||||
continue
|
||||
elif linenumber == 105 and self._triggerResendWithTimeoutAt105 and not self._writingToSd:
|
||||
# simulate a resend with timeout at line 105
|
||||
self._triggerResendWithTimeoutAt105 = False
|
||||
self._triggerResend(expected=105)
|
||||
self._dont_answer = True
|
||||
self.lastN = linenumber
|
||||
continue
|
||||
else:
|
||||
self.lastN = linenumber
|
||||
data = data.split(None, 1)[1].strip()
|
||||
@@ -164,9 +183,8 @@ class VirtualPrinter():
|
||||
data += "\n"
|
||||
|
||||
# shortcut for writing to SD
|
||||
if self._writingToSd and not self._selectedSdFile is None and not "M29" in data:
|
||||
with open(self._selectedSdFile, "a") as f:
|
||||
f.write(data)
|
||||
if self._writingToSdHandle is not None and not "M29" in data:
|
||||
self._writingToSdHandle.write(data)
|
||||
self._sendOk()
|
||||
continue
|
||||
|
||||
@@ -223,6 +241,8 @@ class VirtualPrinter():
|
||||
elif 'M29' in data:
|
||||
if self._sdCardReady:
|
||||
self._finishSdFile()
|
||||
if self._brokenM29:
|
||||
continue
|
||||
elif 'M30' in data:
|
||||
if self._sdCardReady:
|
||||
filename = data.split(None, 1)[1].strip()
|
||||
@@ -580,60 +600,89 @@ class VirtualPrinter():
|
||||
else:
|
||||
self.outgoing.put("error writing to file")
|
||||
|
||||
handle = None
|
||||
try:
|
||||
handle = open(file, "w")
|
||||
except:
|
||||
self.outgoing.put("error writing to file")
|
||||
if handle is not None:
|
||||
try:
|
||||
handle.close()
|
||||
except:
|
||||
pass
|
||||
self._writingToSdHandle = handle
|
||||
self._writingToSd = True
|
||||
self._selectedSdFile = file
|
||||
self.outgoing.put("Writing to file: %s" % filename)
|
||||
|
||||
def _finishSdFile(self):
|
||||
try:
|
||||
self._writingToSdHandle.close()
|
||||
except:
|
||||
pass
|
||||
finally:
|
||||
self._writingToSdHandle = None
|
||||
self._writingToSd = False
|
||||
self._selectedSdFile = None
|
||||
self.outgoing.put("Done saving file")
|
||||
|
||||
def _sdPrintingWorker(self):
|
||||
self._selectedSdFilePos = 0
|
||||
with open(self._selectedSdFile, "r") as f:
|
||||
for line in iter(f.readline, ""):
|
||||
if self._killed:
|
||||
break
|
||||
try:
|
||||
with open(self._selectedSdFile, "r") as f:
|
||||
for line in iter(f.readline, ""):
|
||||
if self._killed:
|
||||
break
|
||||
|
||||
# reset position if requested by client
|
||||
if self._newSdFilePos is not None:
|
||||
f.seek(self._newSdFilePos)
|
||||
self._newSdFilePos = None
|
||||
# reset position if requested by client
|
||||
if self._newSdFilePos is not None:
|
||||
f.seek(self._newSdFilePos)
|
||||
self._newSdFilePos = None
|
||||
|
||||
# read current file position
|
||||
self._selectedSdFilePos = f.tell()
|
||||
# read current file position
|
||||
self._selectedSdFilePos = f.tell()
|
||||
|
||||
# if we are paused, wait for unpausing
|
||||
self._sdPrintingSemaphore.wait()
|
||||
# if we are paused, wait for unpausing
|
||||
self._sdPrintingSemaphore.wait()
|
||||
|
||||
# set target temps
|
||||
if 'M104' in line or 'M109' in line:
|
||||
self._parseHotendCommand(line)
|
||||
if 'M140' in line or 'M190' in line:
|
||||
self._parseBedCommand(line)
|
||||
# set target temps
|
||||
if 'M104' in line or 'M109' in line:
|
||||
self._parseHotendCommand(line)
|
||||
elif 'M140' in line or 'M190' in line:
|
||||
self._parseBedCommand(line)
|
||||
elif line.startswith("G0") or line.startswith("G1") or line.startswith("G2") or line.startswith("G3"):
|
||||
# simulate reprap buffered commands via a Queue with maxsize which internally simulates the moves
|
||||
self.buffered.put(line)
|
||||
|
||||
time.sleep(settings().getFloat(["devel", "virtualPrinter", "throttle"]))
|
||||
except AttributeError:
|
||||
if self.outgoing is not None:
|
||||
raise
|
||||
|
||||
self._sdPrintingSemaphore.clear()
|
||||
self._selectedSdFilePos = 0
|
||||
self._sdPrinter = None
|
||||
self.outgoing.put("Done printing file")
|
||||
if not self._killed:
|
||||
self._sdPrintingSemaphore.clear()
|
||||
self._selectedSdFilePos = 0
|
||||
self._sdPrinter = None
|
||||
self.outgoing.put("Done printing file")
|
||||
|
||||
def _waitForHeatup(self, heater):
|
||||
delta = 1
|
||||
delay = 1
|
||||
if heater.startswith("tool"):
|
||||
toolNum = int(heater[len("tool"):])
|
||||
while not self._killed and (self.temp[toolNum] < self.targetTemp[toolNum] - delta or self.temp[toolNum] > self.targetTemp[toolNum] + delta):
|
||||
self._simulateTemps(delta=delta)
|
||||
self.outgoing.put("T:%0.2f" % self.temp[toolNum])
|
||||
time.sleep(delay)
|
||||
elif heater == "bed":
|
||||
while not self._killed and (self.bedTemp < self.bedTargetTemp - delta or self.bedTemp > self.bedTargetTemp + delta):
|
||||
self._simulateTemps(delta=delta)
|
||||
self.outgoing.put("B:%0.2f" % self.bedTemp)
|
||||
time.sleep(delay)
|
||||
|
||||
try:
|
||||
if heater.startswith("tool"):
|
||||
toolNum = int(heater[len("tool"):])
|
||||
while not self._killed and (self.temp[toolNum] < self.targetTemp[toolNum] - delta or self.temp[toolNum] > self.targetTemp[toolNum] + delta):
|
||||
self._simulateTemps(delta=delta)
|
||||
self.outgoing.put("T:%0.2f" % self.temp[toolNum])
|
||||
time.sleep(delay)
|
||||
elif heater == "bed":
|
||||
while not self._killed and (self.bedTemp < self.bedTargetTemp - delta or self.bedTemp > self.bedTargetTemp + delta):
|
||||
self._simulateTemps(delta=delta)
|
||||
self.outgoing.put("B:%0.2f" % self.bedTemp)
|
||||
time.sleep(delay)
|
||||
except AttributeError:
|
||||
if self.outgoing is not None:
|
||||
raise
|
||||
|
||||
def _deleteSdFile(self, filename):
|
||||
if filename.startswith("/"):
|
||||
@@ -698,12 +747,12 @@ class VirtualPrinter():
|
||||
|
||||
try:
|
||||
line = self.outgoing.get(timeout=self._read_timeout)
|
||||
time.sleep(settings().getFloat(["devel", "virtualPrinter", "throttle"]))
|
||||
return line
|
||||
except Queue.Empty:
|
||||
return ""
|
||||
|
||||
def close(self):
|
||||
self._killed = True
|
||||
self.incoming = None
|
||||
self.outgoing = None
|
||||
self.buffered = None
|
||||
|
||||
@@ -17,7 +17,7 @@ import time
|
||||
|
||||
from octoprint import util as util
|
||||
from octoprint.events import eventManager, Events
|
||||
from octoprint.filemanager import FileDestinations
|
||||
from octoprint.filemanager import FileDestinations, NoSuchStorage
|
||||
from octoprint.plugin import plugin_manager, ProgressPlugin
|
||||
from octoprint.printer import PrinterInterface, PrinterCallback, UnknownScript
|
||||
from octoprint.printer.estimation import TimeEstimationHelper
|
||||
@@ -62,10 +62,6 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
self._currentZ = None
|
||||
|
||||
self._progress = None
|
||||
self._printTime = None
|
||||
self._printTimeLeft = None
|
||||
|
||||
self._printAfterSelect = False
|
||||
self._posAfterSelect = None
|
||||
|
||||
@@ -93,7 +89,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
on_update=self._sendCurrentDataCallbacks,
|
||||
on_add_temperature=self._sendAddTemperatureCallbacks,
|
||||
on_add_log=self._sendAddLogCallbacks,
|
||||
on_add_message=self._sendAddMessageCallbacks
|
||||
on_add_message=self._sendAddMessageCallbacks,
|
||||
on_get_progress=self._updateProgressDataCallback
|
||||
)
|
||||
self._stateMonitor.reset(
|
||||
state={"text": self.get_state_string(), "flags": self._getStateFlags()},
|
||||
@@ -364,7 +361,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
self._printAfterSelect = printAfterSelect
|
||||
self._posAfterSelect = pos
|
||||
self._comm.selectFile("/" + path if sd else path, sd)
|
||||
self._setProgressData(0, None, None, None)
|
||||
self._setProgressData(completion=0)
|
||||
self._setCurrentZ(None)
|
||||
|
||||
def unselect_file(self):
|
||||
@@ -372,7 +369,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
return
|
||||
|
||||
self._comm.unselectFile()
|
||||
self._setProgressData(0, None, None, None)
|
||||
self._setProgressData(completion=0)
|
||||
self._setCurrentZ(None)
|
||||
|
||||
def start_print(self, pos=None):
|
||||
@@ -403,7 +400,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
self._fileManager.delete_recovery_data()
|
||||
|
||||
self._lastProgressReport = None
|
||||
self._setProgressData(0, None, None, None)
|
||||
self._setProgressData(completion=0)
|
||||
self._setCurrentZ(None)
|
||||
self._comm.startPrint(pos=pos)
|
||||
|
||||
@@ -427,7 +424,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
# reset progress, height, print time
|
||||
self._setCurrentZ(None)
|
||||
self._setProgressData(None, None, None, None)
|
||||
self._setProgressData()
|
||||
|
||||
# mark print as failure
|
||||
if self._selectedFile is not None:
|
||||
@@ -597,7 +594,24 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
return result
|
||||
|
||||
def _setProgressData(self, progress, filepos, printTime, cleanedPrintTime):
|
||||
def _setProgressData(self, completion=None, filepos=None, printTime=None, printTimeLeft=None):
|
||||
self._stateMonitor.set_progress(dict(completion=int(completion * 100) if completion is not None else None,
|
||||
filepos=filepos,
|
||||
printTime=int(printTime) if printTime is not None else None,
|
||||
printTimeLeft=int(printTimeLeft) if printTimeLeft is not None else None))
|
||||
|
||||
def _updateProgressDataCallback(self):
|
||||
if self._comm is None:
|
||||
progress = None
|
||||
filepos = None
|
||||
printTime = None
|
||||
cleanedPrintTime = None
|
||||
else:
|
||||
progress = self._comm.getPrintProgress()
|
||||
filepos = self._comm.getPrintFilepos()
|
||||
printTime = self._comm.getPrintTime()
|
||||
cleanedPrintTime = self._comm.getCleanedPrintTime()
|
||||
|
||||
estimatedTotalPrintTime = self._estimateTotalPrintTime(progress, cleanedPrintTime)
|
||||
totalPrintTime = estimatedTotalPrintTime
|
||||
|
||||
@@ -613,16 +627,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
sub_progress = 1.0
|
||||
totalPrintTime = (1 - sub_progress) * statisticalTotalPrintTime + sub_progress * estimatedTotalPrintTime
|
||||
|
||||
self._progress = progress
|
||||
self._printTime = printTime
|
||||
self._printTimeLeft = totalPrintTime - cleanedPrintTime if (totalPrintTime is not None and cleanedPrintTime is not None) else None
|
||||
|
||||
self._stateMonitor.set_progress({
|
||||
"completion": self._progress * 100 if self._progress is not None else None,
|
||||
"filepos": filepos,
|
||||
"printTime": int(self._printTime) if self._printTime is not None else None,
|
||||
"printTimeLeft": int(self._printTimeLeft) if self._printTimeLeft is not None else None
|
||||
})
|
||||
printTimeLeft = totalPrintTime - cleanedPrintTime if (totalPrintTime is not None and cleanedPrintTime is not None) else None
|
||||
|
||||
if progress:
|
||||
progress_int = int(progress * 100)
|
||||
@@ -630,6 +635,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
self._lastProgressReport = progress_int
|
||||
self._reportPrintProgressToPlugins(progress_int)
|
||||
|
||||
return dict(completion=progress * 100 if progress is not None else None,
|
||||
filepos=filepos,
|
||||
printTime=int(printTime) if printTime is not None else None,
|
||||
printTimeLeft=int(printTimeLeft) if printTimeLeft is not None else None)
|
||||
|
||||
def _addTemperatureData(self, temp, bedTemp):
|
||||
currentTimeUtc = int(time.time())
|
||||
@@ -784,11 +793,12 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
self._analysisQueue.resume() # printing done, put those cpu cycles to good use
|
||||
elif state == comm.MachineCom.STATE_PRINTING:
|
||||
self._analysisQueue.pause() # do not analyse files while printing
|
||||
elif state == comm.MachineCom.STATE_CLOSED or state == comm.MachineCom.STATE_CLOSED_WITH_ERROR:
|
||||
|
||||
if state == comm.MachineCom.STATE_CLOSED or state == comm.MachineCom.STATE_CLOSED_WITH_ERROR:
|
||||
if self._comm is not None:
|
||||
self._comm = None
|
||||
|
||||
self._setProgressData(0, None, None, None)
|
||||
self._setProgressData(completion=0)
|
||||
self._setCurrentZ(None)
|
||||
self._setJobData(None, None, None)
|
||||
|
||||
@@ -807,7 +817,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
Triggers storage of new values for printTime, printTimeLeft and the current progress.
|
||||
"""
|
||||
|
||||
self._setProgressData(self._comm.getPrintProgress(), self._comm.getPrintFilepos(), self._comm.getPrintTime(), self._comm.getCleanedPrintTime())
|
||||
self._stateMonitor.trigger_progress_update()
|
||||
|
||||
def on_comm_z_change(self, newZ):
|
||||
"""
|
||||
@@ -837,7 +847,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
def on_comm_print_job_done(self):
|
||||
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._comm.getPrintTime(), True, self._printerProfileManager.get_current_or_default()["id"])
|
||||
self._setProgressData(1.0, self._selectedFile["filesize"], self._comm.getPrintTime(), 0)
|
||||
self._setProgressData(completion=1.0, filepos=self._selectedFile["filesize"], printTime=self._comm.getPrintTime(), printTimeLeft=0)
|
||||
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
|
||||
self._fileManager.delete_recovery_data()
|
||||
|
||||
@@ -845,7 +855,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
self._sdStreaming = True
|
||||
|
||||
self._setJobData(filename, filesize, True)
|
||||
self._setProgressData(0.0, 0, 0, None)
|
||||
self._setProgressData(completion=0.0, filepos=0, printTime=0)
|
||||
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
|
||||
|
||||
def on_comm_file_transfer_done(self, filename):
|
||||
@@ -858,22 +868,28 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
self._setCurrentZ(None)
|
||||
self._setJobData(None, None, None)
|
||||
self._setProgressData(None, None, None, None)
|
||||
self._setProgressData()
|
||||
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
|
||||
|
||||
def on_comm_force_disconnect(self):
|
||||
self.disconnect()
|
||||
|
||||
def on_comm_record_fileposition(self, origin, name, pos):
|
||||
self._fileManager.save_recovery_data(origin, name, pos)
|
||||
try:
|
||||
self._fileManager.save_recovery_data(origin, name, pos)
|
||||
except NoSuchStorage:
|
||||
pass
|
||||
except:
|
||||
self._logger.exception("Error while trying to persist print recovery data")
|
||||
|
||||
class StateMonitor(object):
|
||||
def __init__(self, interval=0.5, on_update=None, on_add_temperature=None, on_add_log=None, on_add_message=None):
|
||||
def __init__(self, interval=0.5, on_update=None, on_add_temperature=None, on_add_log=None, on_add_message=None, on_get_progress=None):
|
||||
self._interval = interval
|
||||
self._update_callback = on_update
|
||||
self._on_add_temperature = on_add_temperature
|
||||
self._on_add_log = on_add_log
|
||||
self._on_add_message = on_add_message
|
||||
self._on_get_progress = on_get_progress
|
||||
|
||||
self._state = None
|
||||
self._job_data = None
|
||||
@@ -882,16 +898,24 @@ class StateMonitor(object):
|
||||
self._current_z = None
|
||||
self._progress = None
|
||||
|
||||
self._progress_dirty = False
|
||||
|
||||
self._offsets = {}
|
||||
|
||||
self._change_event = threading.Event()
|
||||
self._state_lock = threading.Lock()
|
||||
self._progress_lock = threading.Lock()
|
||||
|
||||
self._last_update = time.time()
|
||||
self._worker = threading.Thread(target=self._work)
|
||||
self._worker.daemon = True
|
||||
self._worker.start()
|
||||
|
||||
def _get_current_progress(self):
|
||||
if callable(self._on_get_progress):
|
||||
return self._on_get_progress()
|
||||
return self._progress
|
||||
|
||||
def reset(self, state=None, job_data=None, progress=None, current_z=None):
|
||||
self.set_state(state)
|
||||
self.set_job_data(job_data)
|
||||
@@ -923,9 +947,16 @@ class StateMonitor(object):
|
||||
self._job_data = job_data
|
||||
self._change_event.set()
|
||||
|
||||
def trigger_progress_update(self):
|
||||
with self._progress_lock:
|
||||
self._progress_dirty = True
|
||||
self._change_event.set()
|
||||
|
||||
def set_progress(self, progress):
|
||||
self._progress = progress
|
||||
self._change_event.set()
|
||||
with self._progress_lock:
|
||||
self._progress_dirty = False
|
||||
self._progress = progress
|
||||
self._change_event.set()
|
||||
|
||||
def set_temp_offsets(self, offsets):
|
||||
self._offsets = offsets
|
||||
@@ -935,19 +966,24 @@ class StateMonitor(object):
|
||||
while True:
|
||||
self._change_event.wait()
|
||||
|
||||
with self._state_lock:
|
||||
now = time.time()
|
||||
delta = now - self._last_update
|
||||
additional_wait_time = self._interval - delta
|
||||
if additional_wait_time > 0:
|
||||
time.sleep(additional_wait_time)
|
||||
now = time.time()
|
||||
delta = now - self._last_update
|
||||
additional_wait_time = self._interval - delta
|
||||
if additional_wait_time > 0:
|
||||
time.sleep(additional_wait_time)
|
||||
|
||||
with self._state_lock:
|
||||
data = self.get_current_data()
|
||||
self._update_callback(data)
|
||||
self._last_update = time.time()
|
||||
self._change_event.clear()
|
||||
|
||||
def get_current_data(self):
|
||||
with self._progress_lock:
|
||||
if self._progress_dirty:
|
||||
self._progress = self._get_current_progress()
|
||||
self._progress_dirty = False
|
||||
|
||||
return {
|
||||
"state": self._state,
|
||||
"job": self._job_data,
|
||||
|
||||
@@ -370,7 +370,7 @@ class Server():
|
||||
|
||||
server_routes = self._router.urls + [
|
||||
# various downloads
|
||||
(r"/downloads/timelapse/([^/]*\.mpg)", util.tornado.LargeResponseHandler, joined_dict(dict(path=s.getBaseFolder("timelapse")), download_handler_kwargs, no_hidden_files_validator)),
|
||||
(r"/downloads/timelapse/([^/]*\.mp[g4])", util.tornado.LargeResponseHandler, joined_dict(dict(path=s.getBaseFolder("timelapse")), download_handler_kwargs, no_hidden_files_validator)),
|
||||
(r"/downloads/files/local/(.*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=s.getBaseFolder("uploads")), download_handler_kwargs, no_hidden_files_validator, additional_mime_types)),
|
||||
(r"/downloads/logs/([^/]*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=s.getBaseFolder("logs")), download_handler_kwargs, admin_validator)),
|
||||
# camera snapshot
|
||||
|
||||
@@ -86,8 +86,11 @@ def getSettings():
|
||||
"log": s.getBoolean(["serial", "log"]),
|
||||
"additionalPorts": s.get(["serial", "additionalPorts"]),
|
||||
"longRunningCommands": s.get(["serial", "longRunningCommands"]),
|
||||
"checksumRequiringCommands": s.get(["serial", "checksumRequiringCommands"]),
|
||||
"helloCommand": s.get(["serial", "helloCommand"]),
|
||||
"ignoreErrorsFromFirmware": s.getBoolean(["serial", "ignoreErrorsFromFirmware"]),
|
||||
"disconnectOnErrors": s.getBoolean(["serial", "disconnectOnErrors"]),
|
||||
"triggerOkForM29": s.getBoolean(["serial", "triggerOkForM29"])
|
||||
},
|
||||
"folder": {
|
||||
"uploads": s.getBaseFolder("uploads"),
|
||||
@@ -228,8 +231,11 @@ def setSettings():
|
||||
if "timeoutSdStatus" in data["serial"].keys(): s.setFloat(["serial", "timeout", "sdStatus"], data["serial"]["timeoutSdStatus"])
|
||||
if "additionalPorts" in data["serial"] and isinstance(data["serial"]["additionalPorts"], (list, tuple)): s.set(["serial", "additionalPorts"], data["serial"]["additionalPorts"])
|
||||
if "longRunningCommands" in data["serial"] and isinstance(data["serial"]["longRunningCommands"], (list, tuple)): s.set(["serial", "longRunningCommands"], data["serial"]["longRunningCommands"])
|
||||
if "checksumRequiringCommands" in data["serial"] and isinstance(data["serial"]["checksumRequiringCommands"], (list, tuple)): s.set(["serial", "checksumRequiringCommands"], data["serial"]["checksumRequiringCommands"])
|
||||
if "helloCommand" in data["serial"]: s.set(["serial", "helloCommand"], data["serial"]["helloCommand"])
|
||||
if "ignoreErrorsFromFirmware" in data["serial"]: s.setBoolean(["serial", "ignoreErrorsFromFirmware"], data["serial"]["ignoreErrorsFromFirmware"])
|
||||
if "disconnectOnErrors" in data["serial"]: s.setBoolean(["serial", "disconnectOnErrors"], data["serial"]["disconnectOnErrors"])
|
||||
if "triggerOkForM29" in data["serial"]: s.setBoolean(["serial", "triggerOkForM29"], data["serial"]["triggerOkForM29"])
|
||||
|
||||
oldLog = s.getBoolean(["serial", "log"])
|
||||
if "log" in data["serial"].keys(): s.setBoolean(["serial", "log"], data["serial"]["log"])
|
||||
|
||||
@@ -85,9 +85,15 @@ default_settings = {
|
||||
"sdStatus": 1
|
||||
},
|
||||
"additionalPorts": [],
|
||||
"longRunningCommands": ["G4", "G28", "G29", "G30", "G32"],
|
||||
"longRunningCommands": ["G4", "G28", "G29", "G30", "G32", "M400", "M226"],
|
||||
"checksumRequiringCommands": ["M110"],
|
||||
"helloCommand": "M110 N0",
|
||||
"disconnectOnErrors": True,
|
||||
"ignoreErrorsFromFirmware": False
|
||||
"ignoreErrorsFromFirmware": False,
|
||||
"logResends": False,
|
||||
|
||||
# command specific flags
|
||||
"triggerOkForM29": True
|
||||
},
|
||||
"server": {
|
||||
"host": "0.0.0.0",
|
||||
@@ -305,7 +311,8 @@ default_settings = {
|
||||
"sendWait": True,
|
||||
"waitInterval": 1.0,
|
||||
"supportM112": True,
|
||||
"echoOnM117": True
|
||||
"echoOnM117": True,
|
||||
"brokenM29": True
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -347,16 +347,16 @@ function DataUpdater(allViewModels) {
|
||||
} else if (type == "PrintCancelled") {
|
||||
if (payload.firmwareError) {
|
||||
new PNotify({
|
||||
title: gettext("Unhandled firmware error"),
|
||||
text: _.sprintf(gettext("The firmware reported an unhandled error. Due to that the ongoing print job was cancelled. Error: %(firmwareError)s"), payload),
|
||||
title: gettext("Unhandled communication error"),
|
||||
text: _.sprintf(gettext("There was an unhandled error while talking to the printer. Due to that the ongoing print job was cancelled. Error: %(firmwareError)s"), payload),
|
||||
type: "error",
|
||||
hide: false
|
||||
});
|
||||
}
|
||||
} else if (type == "Error") {
|
||||
new PNotify({
|
||||
title: gettext("Unhandled firmware error"),
|
||||
text: _.sprintf(gettext("The firmware reported an unhandled error. Due to that OctoPrint disconnected. Error: %(error)s"), payload),
|
||||
title: gettext("Unhandled communication error"),
|
||||
text: _.sprintf(gettext("The was an unhandled error while talking to the printer. Due to that OctoPrint disconnected. Error: %(error)s"), payload),
|
||||
type: "error",
|
||||
hide: false
|
||||
});
|
||||
|
||||
@@ -469,7 +469,7 @@ $(function() {
|
||||
|
||||
self._enableSdDropzone = function(enable) {
|
||||
var options = {
|
||||
url: API_BASEURL + "files/local",
|
||||
url: API_BASEURL + "files/sdcard",
|
||||
dataType: "json",
|
||||
dropZone: enable ? self.sdTarget : null,
|
||||
done: self._handleUploadDone,
|
||||
|
||||
@@ -136,8 +136,11 @@ $(function() {
|
||||
self.serial_log = ko.observable(undefined);
|
||||
self.serial_additionalPorts = ko.observable(undefined);
|
||||
self.serial_longRunningCommands = ko.observable(undefined);
|
||||
self.serial_checksumRequiringCommands = ko.observable(undefined);
|
||||
self.serial_helloCommand = ko.observable(undefined);
|
||||
self.serial_ignoreErrorsFromFirmware = ko.observable(undefined);
|
||||
self.serial_disconnectOnErrors = ko.observable(undefined);
|
||||
self.serial_triggerOkForM29 = ko.observable(undefined);
|
||||
|
||||
self.folder_uploads = ko.observable(undefined);
|
||||
self.folder_timelapse = ko.observable(undefined);
|
||||
@@ -452,8 +455,11 @@ $(function() {
|
||||
self.serial_log(response.serial.log);
|
||||
self.serial_additionalPorts(response.serial.additionalPorts.join("\n"));
|
||||
self.serial_longRunningCommands(response.serial.longRunningCommands.join(", "));
|
||||
self.serial_checksumRequiringCommands(response.serial.checksumRequiringCommands.join(", "));
|
||||
self.serial_helloCommand(response.serial.helloCommand);
|
||||
self.serial_ignoreErrorsFromFirmware(response.serial.ignoreErrorsFromFirmware);
|
||||
self.serial_disconnectOnErrors(response.serial.disconnectOnErrors);
|
||||
self.serial_triggerOkForM29(response.serial.triggerOkForM29);
|
||||
|
||||
self.folder_uploads(response.folder.uploads);
|
||||
self.folder_timelapse(response.folder.timelapse);
|
||||
@@ -541,8 +547,11 @@ $(function() {
|
||||
"log": self.serial_log(),
|
||||
"additionalPorts": commentableLinesToArray(self.serial_additionalPorts()),
|
||||
"longRunningCommands": splitTextToArray(self.serial_longRunningCommands(), ",", true),
|
||||
"checksumRequiringCommands": splitTextToArray(self.serial_checksumRequiringCommands(), ",", true),
|
||||
"helloCommand": self.serial_helloCommand(),
|
||||
"ignoreErrorsFromFirmware": self.serial_ignoreErrorsFromFirmware(),
|
||||
"disconnectOnErrors": self.serial_disconnectOnErrors()
|
||||
"disconnectOnErrors": self.serial_disconnectOnErrors(),
|
||||
"triggerOkForM29": self.serial_triggerOkForM29()
|
||||
},
|
||||
"folder": {
|
||||
"uploads": self.folder_uploads(),
|
||||
|
||||
@@ -70,13 +70,6 @@
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label" for="settings-serialLongRunningCommands">{{ _('Long running commands') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" id="settings-serialLongRunningCommands" data-bind="value: serial_longRunningCommands">
|
||||
<span class="help-inline">{{ _('Use this to specify the commands known to take a long time to complete without output from your printer and hence might cause timeout issues. Just the G or M code, comma separated.')|format(glob_url="http://docs.python.org/2/library/glob.html") }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label" for="settings-serialAdditionalPorts">{{ _('Additional serial ports') }}</label>
|
||||
<div class="controls">
|
||||
@@ -98,4 +91,37 @@
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div><small><a href="#" class="muted" onclick="$(this).children().toggleClass('icon-caret-right icon-caret-down').parent().parent().parent().next().slideToggle('fast')"><i class="icon-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
|
||||
<div class="hide">
|
||||
<div class="control-group" title="{{ _('Command to send to the firmware on first handshake attempt.') }}">
|
||||
<label class="control-label" for="settings-serialHelloCommand">{{ _('"Hello" command') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" id="settings-serialHelloCommand" data-bind="value: serial_helloCommand">
|
||||
<span class="help-inline">{{ _('Use this to specify a different command than the default <code>M110</code> to send to the printer on initial connection to trigger a communication handshake.') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" title="{{ _('Commands that are know to run long and hence should suppress communication timeouts from being triggered.') }}">
|
||||
<label class="control-label" for="settings-serialLongRunningCommands">{{ _('Long running commands') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" id="settings-serialLongRunningCommands" data-bind="value: serial_longRunningCommands">
|
||||
<span class="help-inline">{{ _('Use this to specify the commands known to take a long time to complete without output from your printer and hence might cause timeout issues. Just the G or M code, comma separated.') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" title="{{ _('Commands that always require a line number and checksum to be sent with them.') }}">
|
||||
<label class="control-label" for="settings-serialChecksumRequiringCommands">{{ _('Commands that always require a checksum') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" id="settings-serialChecksumRequiringCommands" data-bind="value: serial_checksumRequiringCommands">
|
||||
<span class="help-inline">{{ _('Use this to specify which commands <strong>always</strong> need to be sent with a checksum. Comma separated list.') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: serial_triggerOkForM29" id="settings-triggerOkForM29"> {{ _('Generate additional <code>ok</code> for <code>M29</code>') }} <span class="label">{{ _('Most Marlin < v1.1.0') }}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</form>
|
||||
@@ -62,7 +62,7 @@ def get_finished_timelapses():
|
||||
files = []
|
||||
basedir = settings().getBaseFolder("timelapse")
|
||||
for osFile in os.listdir(basedir):
|
||||
if not fnmatch.fnmatch(osFile, "*.mpg"):
|
||||
if not fnmatch.fnmatch(osFile, "*.mp[g4]"):
|
||||
continue
|
||||
statResult = os.stat(os.path.join(basedir, osFile))
|
||||
files.append({
|
||||
@@ -99,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):
|
||||
|
||||
@@ -18,6 +18,7 @@ import threading
|
||||
from functools import wraps
|
||||
import warnings
|
||||
import contextlib
|
||||
import Queue as queue
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -816,12 +817,9 @@ class RepeatedTimer(threading.Thread):
|
||||
|
||||
class CountedEvent(object):
|
||||
|
||||
def __init__(self, value=0, max=None, name=None):
|
||||
logger_name = __name__ + ".CountedEvent" + (".{name}".format(name=name) if name is not None else "")
|
||||
self._logger = logging.getLogger(logger_name)
|
||||
|
||||
def __init__(self, value=0, maximum=None, **kwargs):
|
||||
self._counter = 0
|
||||
self._max = max
|
||||
self._max = kwargs.get("max", maximum)
|
||||
self._mutex = threading.Lock()
|
||||
self._event = threading.Event()
|
||||
|
||||
@@ -846,17 +844,14 @@ class CountedEvent(object):
|
||||
return self._counter == 0
|
||||
|
||||
def _internal_set(self, value):
|
||||
self._logger.debug("New counter value: {value}".format(value=value))
|
||||
self._counter = value
|
||||
if self._counter <= 0:
|
||||
self._counter = 0
|
||||
self._event.clear()
|
||||
self._logger.debug("Cleared event")
|
||||
else:
|
||||
if self._max is not None and self._counter > self._max:
|
||||
self._counter = self._max
|
||||
self._event.set()
|
||||
self._logger.debug("Set event")
|
||||
|
||||
|
||||
class InvariantContainer(object):
|
||||
@@ -890,3 +885,43 @@ class InvariantContainer(object):
|
||||
|
||||
def __iter__(self):
|
||||
return self._data.__iter__()
|
||||
|
||||
|
||||
class TypedQueue(queue.Queue):
|
||||
|
||||
def __init__(self, maxsize=0):
|
||||
queue.Queue.__init__(self, maxsize=maxsize)
|
||||
self._lookup = set()
|
||||
|
||||
def put(self, item, item_type=None, *args, **kwargs):
|
||||
queue.Queue.put(self, (item, item_type), *args, **kwargs)
|
||||
|
||||
def get(self, *args, **kwargs):
|
||||
item, _ = queue.Queue.get(self, *args, **kwargs)
|
||||
return item
|
||||
|
||||
def _put(self, item):
|
||||
_, item_type = item
|
||||
if item_type is not None:
|
||||
if item_type in self._lookup:
|
||||
raise TypeAlreadyInQueue(item_type, "Type {} is already in queue".format(item_type))
|
||||
else:
|
||||
self._lookup.add(item_type)
|
||||
|
||||
queue.Queue._put(self, item)
|
||||
|
||||
def _get(self):
|
||||
item = queue.Queue._get(self)
|
||||
_, item_type = item
|
||||
|
||||
if item_type is not None:
|
||||
self._lookup.discard(item_type)
|
||||
|
||||
return item
|
||||
|
||||
|
||||
class TypeAlreadyInQueue(Exception):
|
||||
def __init__(self, t, *args, **kwargs):
|
||||
Exception.__init__(self, *args, **kwargs)
|
||||
self.type = t
|
||||
|
||||
+551
-307
File diff suppressed because it is too large.
Load diff
+24
-20
@@ -124,34 +124,34 @@ class PipCaller(object):
|
||||
all_stderr = []
|
||||
try:
|
||||
while p.returncode is None:
|
||||
line = p.stderr.readline(timeout=0.5)
|
||||
if line:
|
||||
line = self._convert_line(line)
|
||||
self._log_stderr(line)
|
||||
all_stderr.append(line)
|
||||
lines = p.stderr.readlines(timeout=0.5)
|
||||
if lines:
|
||||
lines = self._convert_lines(lines)
|
||||
self._log_stderr(*lines)
|
||||
all_stderr += lines
|
||||
|
||||
line = p.stdout.readline(timeout=0.5)
|
||||
if line:
|
||||
line = self._convert_line(line)
|
||||
self._log_stdout(line)
|
||||
all_stdout.append(line)
|
||||
lines = p.stdout.readlines(timeout=0.5)
|
||||
if lines:
|
||||
lines = self._convert_lines(lines)
|
||||
self._log_stdout(*lines)
|
||||
all_stdout += lines
|
||||
|
||||
p.commands[0].poll()
|
||||
|
||||
finally:
|
||||
p.close()
|
||||
|
||||
stderr = p.stderr.text
|
||||
if stderr:
|
||||
split_lines = map(self._convert_line, stderr.split("\n"))
|
||||
self._log_stderr(*split_lines)
|
||||
all_stderr += split_lines
|
||||
lines = p.stderr.readlines()
|
||||
if lines:
|
||||
lines = map(self._convert_line, lines)
|
||||
self._log_stderr(*lines)
|
||||
all_stderr += lines
|
||||
|
||||
stdout = p.stdout.text
|
||||
if stdout:
|
||||
split_lines = map(self._convert_line, stdout.split("\n"))
|
||||
self._log_stdout(*split_lines)
|
||||
all_stdout += split_lines
|
||||
lines = p.stdout.readlines()
|
||||
if lines:
|
||||
lines = map(self._convert_line, lines)
|
||||
self._log_stdout(*lines)
|
||||
all_stdout += lines
|
||||
|
||||
return p.returncode, all_stdout, all_stderr
|
||||
|
||||
@@ -240,6 +240,10 @@ class PipCaller(object):
|
||||
def _log_stderr(self, *lines):
|
||||
self.on_log_stderr(*lines)
|
||||
|
||||
@staticmethod
|
||||
def _convert_lines(lines):
|
||||
return map(PipCaller._convert_line, lines)
|
||||
|
||||
@staticmethod
|
||||
def _convert_line(line):
|
||||
return to_unicode(_clean_ansi(line), errors="replace")
|
||||
@@ -10,6 +10,9 @@ 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
|
||||
|
||||
@@ -100,3 +103,70 @@ class TimelapseTest(unittest.TestCase):
|
||||
"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)
|
||||
@@ -0,0 +1,417 @@
|
||||
# coding=utf-8
|
||||
"""
|
||||
Unit tests for ``octoprint.util.comm``.
|
||||
"""
|
||||
|
||||
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) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
from collections import deque
|
||||
import Queue as queue
|
||||
import re
|
||||
import time
|
||||
import threading
|
||||
|
||||
import unittest
|
||||
import mock
|
||||
|
||||
|
||||
import octoprint.util.comm
|
||||
|
||||
|
||||
class FakeBareboneFirmware(object):
|
||||
|
||||
def __init__(self, serial_mock):
|
||||
self.serial_mock = serial_mock
|
||||
|
||||
self.serial_mock.readline.side_effect = self.readline
|
||||
self.serial_mock.write.side_effect = self.write
|
||||
|
||||
self.on_receive = None
|
||||
|
||||
self.outgoing = queue.Queue()
|
||||
self.incoming = queue.Queue()
|
||||
|
||||
self._written = deque([])
|
||||
self._read = deque([])
|
||||
|
||||
self._conditioned_answers = []
|
||||
|
||||
self._produce_read_timeout = 0
|
||||
self._produce_write_timeout = 0
|
||||
self._finishing = False
|
||||
|
||||
self._receive_lock = threading.Lock()
|
||||
|
||||
def produce_read_timeout(self):
|
||||
self._produce_read_timeout = True
|
||||
|
||||
def readline(self):
|
||||
line = self._get_next_line()
|
||||
self._read.append(line)
|
||||
return line
|
||||
|
||||
def write(self, data):
|
||||
with self._receive_lock:
|
||||
if self._finishing:
|
||||
return
|
||||
|
||||
if self._produce_write_timeout:
|
||||
self._produce_write_timeout -= 1
|
||||
if self._produce_write_timeout <= 0:
|
||||
self._produce_write_timeout = 0
|
||||
import serial
|
||||
raise serial.SerialTimeoutException()
|
||||
|
||||
self._written.append(data)
|
||||
self._on_received_data(data)
|
||||
|
||||
for condition, lines in self._conditioned_answers:
|
||||
if callable(condition) and condition(data):
|
||||
self.return_lines(*lines)
|
||||
|
||||
def assert_written(self, *data):
|
||||
if not data:
|
||||
return True
|
||||
|
||||
all_written = list(self._written)
|
||||
while all_written:
|
||||
written = all_written[0]
|
||||
if written == data[0]:
|
||||
break
|
||||
all_written.pop(0)
|
||||
else:
|
||||
raise AssertionError("{!r} is not contained in written data".format(data))
|
||||
|
||||
return self._check_written(all_written, data)
|
||||
|
||||
def assert_written_exactly(self, *data):
|
||||
if not data:
|
||||
return True
|
||||
|
||||
all_written = list(self._written)
|
||||
return self._check_written(all_written, data)
|
||||
|
||||
def return_lines(self, *lines):
|
||||
for line in lines:
|
||||
if not line.endswith("\n"):
|
||||
line += "\n"
|
||||
self.outgoing.put(line)
|
||||
|
||||
def return_lines_if(self, condition, *lines):
|
||||
self._conditioned_answers.append((condition, lines))
|
||||
|
||||
def finish(self):
|
||||
self._finishing = True
|
||||
self.outgoing.join()
|
||||
|
||||
def _check_written(self, expected, actual):
|
||||
zipped = zip(expected, actual)
|
||||
for a, b in zipped:
|
||||
assert a == b
|
||||
return True
|
||||
|
||||
def _get_next_line(self):
|
||||
if self._produce_read_timeout:
|
||||
self._produce_read_timeout -= 1
|
||||
if self._produce_read_timeout <= 0:
|
||||
self._produce_read_timeout = 0
|
||||
return ""
|
||||
|
||||
try:
|
||||
line = self.outgoing.get(timeout=self.serial_mock.timeout)
|
||||
self.outgoing.task_done()
|
||||
return line
|
||||
except queue.Empty:
|
||||
return ""
|
||||
|
||||
def _on_received_data(self, data):
|
||||
if callable(self.on_receive):
|
||||
return self.on_receive(self, data)
|
||||
return False
|
||||
|
||||
|
||||
class FakeGcodeFirmware(FakeBareboneFirmware):
|
||||
|
||||
command_regex = re.compile("^([GMTF])(\d+)")
|
||||
|
||||
def __init__(self, serial_mock, simulate_reset=True, require_checksum=False):
|
||||
FakeBareboneFirmware.__init__(self, serial_mock)
|
||||
|
||||
self._require_checksum = require_checksum
|
||||
self._line_number = 0
|
||||
|
||||
if simulate_reset:
|
||||
self.return_lines("start")
|
||||
else:
|
||||
import random
|
||||
self._line_number = random.randrange(1, stop=2342)
|
||||
|
||||
def _on_received_data(self, data):
|
||||
print("firmware - received data: {!r}".format(data))
|
||||
|
||||
if FakeBareboneFirmware._on_received_data(self, data):
|
||||
return True
|
||||
|
||||
data = data.strip()
|
||||
|
||||
# strip checksum
|
||||
if "*" in data:
|
||||
pos = data.rfind("*")
|
||||
checksum = int(data[pos+1:])
|
||||
data = data[:pos]
|
||||
|
||||
if checksum != self._get_checksum(data):
|
||||
self._trigger_resend(checksum_wrong=True)
|
||||
return True
|
||||
|
||||
elif self._require_checksum:
|
||||
self.return_lines("Error: Missing checksum")
|
||||
return True
|
||||
|
||||
# track line numbers
|
||||
if "N" in data and "M110" in data:
|
||||
linenumber = int(re.search("N([0-9]+)", data).group(1))
|
||||
self._line_number = linenumber
|
||||
self._trigger_ok()
|
||||
return True
|
||||
|
||||
elif data.startswith("N"):
|
||||
match = re.search("N([0-9]+)", data)
|
||||
|
||||
prefix = match.group(0)
|
||||
linenumber = int(match.group(1))
|
||||
expected = self._line_number + 1
|
||||
if linenumber != expected:
|
||||
self._trigger_resend(expected=expected, actual=linenumber)
|
||||
return True
|
||||
|
||||
self._line_number = linenumber
|
||||
data = data[len(prefix):].strip()
|
||||
|
||||
if self._process_line(data):
|
||||
self._trigger_ok()
|
||||
|
||||
return True
|
||||
|
||||
def _trigger_ok(self):
|
||||
print("firmware - sending ok")
|
||||
self.return_lines("ok")
|
||||
|
||||
def _trigger_resend(self, checksum_wrong=False, actual=None, expected=None):
|
||||
if expected is None:
|
||||
expected = self._line_number + 1
|
||||
|
||||
if actual is not None:
|
||||
print("firmware - Triggering resend for expected line incl. ok")
|
||||
self.return_lines("Error: expected line {} got {}".format(expected, actual),
|
||||
"Resend: {}".format(expected),
|
||||
"ok")
|
||||
|
||||
elif checksum_wrong:
|
||||
print("firmware - Triggering resend for wrong checksum incl. ok")
|
||||
self.return_lines("Error: Wrong checksum",
|
||||
"Resend: {}".format(expected),
|
||||
"ok")
|
||||
|
||||
def _process_line(self, line):
|
||||
command_match = self.command_regex.match(line)
|
||||
|
||||
if command_match is None:
|
||||
return False
|
||||
|
||||
command = command_match.group(0)
|
||||
letter = command_match.group(1)
|
||||
|
||||
# if we have a method _gcode_G, _gcode_M or _gcode_T, execute that first
|
||||
letter_handler = "_gcode_{}".format(letter)
|
||||
if hasattr(self, letter_handler):
|
||||
code = command_match.group(2)
|
||||
handled = getattr(self, letter_handler)(code, line)
|
||||
if handled:
|
||||
return False
|
||||
|
||||
# then look for a method _gcode_<command> and execute that if it exists
|
||||
command_handler = "_gcode_{}".format(command)
|
||||
if hasattr(self, command_handler):
|
||||
handled = getattr(self, command_handler)(line)
|
||||
if handled:
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def _get_checksum(line):
|
||||
checksum = 0
|
||||
for c in line:
|
||||
checksum ^= ord(c)
|
||||
return checksum
|
||||
|
||||
|
||||
class CommCallbackHelper(octoprint.util.comm.MachineComPrintCallback):
|
||||
|
||||
def __init__(self):
|
||||
self._states = deque([])
|
||||
|
||||
import threading
|
||||
self._state_change_event = threading.Event()
|
||||
|
||||
def wait_for_state(self, *states, **kwargs):
|
||||
import octoprint.util.comm
|
||||
|
||||
timeout = kwargs.get("timeout", 10)
|
||||
|
||||
if not states:
|
||||
return True
|
||||
|
||||
offset = len(self._states)
|
||||
|
||||
while True:
|
||||
if not self._state_change_event.wait(timeout=timeout):
|
||||
raise AssertionError("Timeout while waiting for any of states {}".format(states))
|
||||
current_states = list(self._states)[offset:]
|
||||
if current_states:
|
||||
current_state = current_states[-1]
|
||||
if current_state in states:
|
||||
return True
|
||||
elif current_state in (octoprint.util.comm.MachineCom.STATE_ERROR,
|
||||
octoprint.util.comm.MachineCom.STATE_CLOSED_WITH_ERROR,
|
||||
octoprint.util.comm.MachineCom.STATE_CLOSED):
|
||||
raise AssertionError("Didn't get any of states {} but an error/a close instead: {}".format(states, current_state))
|
||||
|
||||
|
||||
def on_comm_state_change(self, state):
|
||||
self._states.append(state)
|
||||
self._state_change_event.set()
|
||||
|
||||
def on_comm_log(self, message):
|
||||
print("on_comm_log - {:.3f}: {}".format(time.time(), message))
|
||||
|
||||
def assert_states(self, *states):
|
||||
all_states = list(self._states)
|
||||
|
||||
while all_states:
|
||||
state = all_states[0]
|
||||
if state == states[0]:
|
||||
break
|
||||
all_states.pop(0)
|
||||
else:
|
||||
raise AssertionError("{!r} is not contained in states".format(states))
|
||||
|
||||
return self._check_states(states, all_states)
|
||||
|
||||
def assert_states_exactly(self, *states):
|
||||
all_states = list(self._states)
|
||||
return self._check_states(states, all_states)
|
||||
|
||||
def _check_states(self, expected, actual):
|
||||
zipped = zip(expected, actual)
|
||||
for a, b in zipped:
|
||||
assert a == b
|
||||
return True
|
||||
|
||||
|
||||
class CommsTestCase(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
import serial
|
||||
from octoprint.settings import default_settings
|
||||
from octoprint.printer.profile import PrinterProfileManager
|
||||
|
||||
self.default_settings = default_settings
|
||||
|
||||
# mock serial
|
||||
self.serial_patcher = mock.patch("octoprint.util.comm.serial")
|
||||
self.serial_module = self.serial_patcher.start()
|
||||
self.serial_module.Serial = mock.MagicMock()
|
||||
|
||||
self.serial = mock.MagicMock(spec=serial.Serial)
|
||||
def constructor(*args, **kwargs):
|
||||
self.serial.timeout = kwargs.get("timeout", None)
|
||||
return self.serial
|
||||
self.serial_module.Serial.side_effect = constructor
|
||||
|
||||
# mock settings
|
||||
self.settings_patcher = mock.patch("octoprint.util.comm.settings")
|
||||
settings = self.settings_patcher.start()
|
||||
self.settings = settings.return_value
|
||||
self._mock_settings()
|
||||
|
||||
# mock plugin manager
|
||||
self.plugin_manager_patcher = mock.patch("octoprint.plugin.plugin_manager")
|
||||
self.plugin_manager = self.plugin_manager_patcher.start()
|
||||
self._mock_hooks()
|
||||
|
||||
# mock printer profile manager
|
||||
self.printer_profile_manager = mock.MagicMock(spec=PrinterProfileManager)
|
||||
self.printer_profile_manager.get_current_or_default.return_value = dict(heatedBed=False,
|
||||
extruder=dict(count=1))
|
||||
|
||||
# fake firmware
|
||||
self.firmware = self._create_firmware()
|
||||
|
||||
# comm callback helper
|
||||
self.callback = CommCallbackHelper()
|
||||
|
||||
def tearDown(self):
|
||||
self.plugin_manager_patcher.stop()
|
||||
self.settings_patcher.stop()
|
||||
self.serial_patcher.stop()
|
||||
|
||||
def _start_comm(self, port, baudrate):
|
||||
self.comm = octoprint.util.comm.MachineCom(port=port,
|
||||
baudrate=baudrate,
|
||||
callbackObject=self.callback,
|
||||
printerProfileManager=self.printer_profile_manager)
|
||||
return self.comm
|
||||
|
||||
def _stop_comm(self, timeout=10.0):
|
||||
self.firmware.finish()
|
||||
self.comm.close(timeout=timeout)
|
||||
|
||||
def _wait_for_operational(self, additional=0.0):
|
||||
self.callback.wait_for_state(octoprint.util.comm.MachineCom.STATE_OPERATIONAL)
|
||||
time.sleep(additional)
|
||||
|
||||
def _create_firmware(self):
|
||||
return FakeGcodeFirmware(self.serial)
|
||||
|
||||
def _mock_hooks(self, hooks=None):
|
||||
if hooks == None:
|
||||
hooks = dict()
|
||||
|
||||
def get_hooks(hook):
|
||||
return hooks.get(hook, dict())
|
||||
self.plugin_manager.return_value.get_hooks.side_effect = get_hooks
|
||||
|
||||
def _mock_settings(self, overrides=None):
|
||||
from octoprint.util import dict_merge
|
||||
merged = dict_merge(self.default_settings, overrides)
|
||||
|
||||
def get(path, *args, **kwargs):
|
||||
if len(path) == 3 and path[0:2] == ["serial", "timeout"]:
|
||||
first, second, third = path
|
||||
if first not in ("serial", "feature"):
|
||||
return None
|
||||
return merged[first][second][third]
|
||||
elif len(path) == 2:
|
||||
first, second = path
|
||||
if first not in ("serial", "feature"):
|
||||
return None
|
||||
return merged[first][second]
|
||||
else:
|
||||
return None
|
||||
|
||||
def getBoolean(path, *args, **kwargs):
|
||||
return get(path, *args, **kwargs)
|
||||
|
||||
def getFloat(path, *args, **kwargs):
|
||||
return get(path, *args, **kwargs)
|
||||
|
||||
self.settings.get.side_effect = get
|
||||
self.settings.getFloat.side_effect = getFloat
|
||||
self.settings.getBoolean.side_effect = getBoolean
|
||||
@@ -0,0 +1,148 @@
|
||||
# coding=utf-8
|
||||
"""
|
||||
Unit tests for ``octoprint.util.comm``.
|
||||
"""
|
||||
|
||||
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) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
from . import CommsTestCase, FakeGcodeFirmware
|
||||
|
||||
import octoprint.util.comm
|
||||
|
||||
import mock
|
||||
from ddt import ddt, data, unpack
|
||||
|
||||
|
||||
class BasicCommsTest(CommsTestCase):
|
||||
|
||||
def _perform_simple_open_test(self, setting_overrides, expected_written_lines, not_written):
|
||||
# prepare
|
||||
self._mock_settings(overrides=setting_overrides)
|
||||
|
||||
# run
|
||||
self._start_comm("/dev/ttyUSB0", 115200)
|
||||
self._wait_for_operational(additional=1.0)
|
||||
self._stop_comm()
|
||||
|
||||
# verify
|
||||
self.serial_module.Serial.assert_called_once_with("/dev/ttyUSB0",
|
||||
115200,
|
||||
timeout=self.default_settings["serial"]["timeout"]["connection"],
|
||||
writeTimeout=10000,
|
||||
parity=octoprint.util.comm.serial.PARITY_ODD)
|
||||
self.assertEquals(self.serial.close.call_count, 2)
|
||||
self.assertEquals(self.serial.open.call_count, 1)
|
||||
self.assertEqual(self.serial.parity, octoprint.util.comm.serial.PARITY_NONE)
|
||||
|
||||
expected_writes = []
|
||||
for line in expected_written_lines:
|
||||
expected_writes.append(mock.call(line + "\n"))
|
||||
self.serial.write.assert_has_calls(expected_writes, any_order=True)
|
||||
|
||||
for line in not_written:
|
||||
self.assertNotIn(mock.call(line + "\n"), self.serial.write.mock_calls)
|
||||
|
||||
|
||||
@ddt
|
||||
class BasicCommsResetTest(BasicCommsTest):
|
||||
|
||||
@data((dict(feature=dict(sdSupport=True,
|
||||
sdAlwaysAvailable=False,
|
||||
waitForStartOnConnect=False)),
|
||||
["N0 M110 N0*125", # hello from tickling
|
||||
"N0 M110 N0*125", # hello from start
|
||||
"N0 M110 N0*125", # line number reset from connected handler
|
||||
"M21"],
|
||||
["M20"]), # sd card init from connected handler
|
||||
|
||||
# wait for start
|
||||
(dict(feature=dict(sdSupport=True,
|
||||
sdAlwaysAvailable=False,
|
||||
waitForStartOnConnect=True)),
|
||||
["N0 M110 N0*125", # hello from start
|
||||
"N0 M110 N0*125", # line number reset from connected handler
|
||||
"M21"], # sd card init from connected handler
|
||||
["M20"]), # no M20 (no sd init success message)
|
||||
|
||||
# no sd
|
||||
(dict(feature=dict(sdSupport=False,
|
||||
sdAlwaysAvailable=False,
|
||||
waitForStartOnConnect=False)),
|
||||
["N0 M110 N0*125", # hello from tickling
|
||||
"N0 M110 N0*125", # hello from start
|
||||
"N0 M110 N0*125"], # line number reset from connected handler
|
||||
["M20", "M21"]), # no M20 or M21 (no sd card support)
|
||||
|
||||
# no sd, wait for start
|
||||
(dict(feature=dict(sdSupport=False,
|
||||
sdAlwaysAvailable=False,
|
||||
waitForStartOnConnect=True)),
|
||||
["N0 M110 N0*125", # hello from start
|
||||
"N0 M110 N0*125"], # line number reset from connected handler
|
||||
["M20", "M21"]), # no M20 or M21 (no sd card support)
|
||||
|
||||
# sd assumed available, wait for start
|
||||
(dict(feature=dict(sdSupport=True,
|
||||
sdAlwaysAvailable=True,
|
||||
waitForStartOnConnect=True)),
|
||||
["N0 M110 N0*125", # hello from start
|
||||
"N0 M110 N0*125", # line number reset from connected handler
|
||||
"M21", # sd init, no response necessary
|
||||
"M20"], # sd list (init assumed to be done)
|
||||
[]),
|
||||
)
|
||||
@unpack
|
||||
def test_simple_open(self, setting_overrides, expected_written_lines, not_written):
|
||||
self._perform_simple_open_test(setting_overrides, expected_written_lines, not_written)
|
||||
|
||||
def _create_firmware(self):
|
||||
return FakeGcodeFirmware(self.serial, simulate_reset=True)
|
||||
|
||||
@ddt
|
||||
class BasicCommsNoResetTest(BasicCommsTest):
|
||||
|
||||
@data((dict(feature=dict(sdSupport=True,
|
||||
sdAlwaysAvailable=False,
|
||||
waitForStartOnConnect=False)),
|
||||
["N0 M110 N0*125", # hello from tickling
|
||||
"N0 M110 N0*125", # line number reset from connected handler
|
||||
"M21"],
|
||||
["M20"]), # sd card init from connected handler
|
||||
|
||||
# no sd
|
||||
(dict(feature=dict(sdSupport=False,
|
||||
sdAlwaysAvailable=False,
|
||||
waitForStartOnConnect=False)),
|
||||
["N0 M110 N0*125", # hello from tickling
|
||||
"N0 M110 N0*125"], # line number reset from connected handler
|
||||
["M20", "M21"]), # no M20 or M21 (no sd card support)
|
||||
|
||||
# no sd
|
||||
(dict(feature=dict(sdSupport=False,
|
||||
sdAlwaysAvailable=False,
|
||||
waitForStartOnConnect=False)),
|
||||
["N0 M110 N0*125", # hello from tickling
|
||||
"N0 M110 N0*125"], # line number reset from connected handler
|
||||
["M20", "M21"]), # no M20 or M21 (no sd card support)
|
||||
|
||||
# sd assumed available
|
||||
(dict(feature=dict(sdSupport=True,
|
||||
sdAlwaysAvailable=True,
|
||||
waitForStartOnConnect=False)),
|
||||
["N0 M110 N0*125", # hello from tickling
|
||||
"N0 M110 N0*125", # line number reset from connected handler
|
||||
"M21", # sd init, no response necessary
|
||||
"M20"], # sd list (init assumed to be done)
|
||||
[]),
|
||||
)
|
||||
@unpack
|
||||
def test_simple_open(self, setting_overrides, expected_written_lines, not_written):
|
||||
self._perform_simple_open_test(setting_overrides, expected_written_lines, not_written)
|
||||
|
||||
def _create_firmware(self):
|
||||
return FakeGcodeFirmware(self.serial, simulate_reset=False)
|
||||
Reference in new issue
Block a user