Skip to content

Commit

Permalink
Merge branch 'devel/py3prep'
Browse files Browse the repository at this point in the history
  • Loading branch information
markwal committed Sep 9, 2020
2 parents 9850dfc + 3542c21 commit 0d51688
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 37 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ dist
*.egg*
.DS_Store
*.zip
tags
84 changes: 48 additions & 36 deletions octoprint_polarcloud/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,20 @@
import threading
import logging
import uuid
import Queue
from functools import reduce
try:
import queue
except ImportError:
import Queue as queue
import base64
import datetime
from time import sleep
from StringIO import StringIO
import io
from urlparse import urlparse, urlunparse
from io import StringIO, BytesIO
try:
from urllib.parse import urlparse, urlunparse
except ImportError:
from urlparse import urlparse, urlunparse
import random
import re
import json
Expand All @@ -55,6 +62,7 @@
from octoprint.events import Events
from octoprint.filemanager import FileDestinations
from octoprint.filemanager.util import StreamWrapper
from octoprint.slicing.exceptions import UnknownSlicer, SlicerNotConfigured

# logging.getLogger('socketIO-client').setLevel(logging.DEBUG)
# logging.basicConfig()
Expand Down Expand Up @@ -131,7 +139,7 @@ def __init__(self):
self._connected = False
self._status_now = False
self._challenge = None
self._task_queue = Queue.Queue()
self._task_queue = queue.Queue()
self._polar_status_worker = None
self._upload_location = {}
self._update_interval = 60
Expand Down Expand Up @@ -467,7 +475,7 @@ def _wait_and_process(seconds, ignore_status_now=False):
try:
task = self._task_queue.get_nowait()
task()
except Queue.Empty:
except queue.Empty:
pass
if not ignore_status_now and self._status_now:
self._status_now = False
Expand All @@ -477,14 +485,17 @@ def _wait_and_process(seconds, ignore_status_now=False):
if not self._connected:
self._socket = None
return False
if self._shutdown:
return False
return True
except:
if not self._connected:
# likely throw from disconnect
self._socket = None
else:
self._logger.exception("polar_heartbeat exception")
sleep(5)
if not self._shutdown:
if not self._connected:
# likely throw from disconnect
self._socket = None
else:
self._logger.exception("polar_heartbeat exception")
sleep(5)
return False

try:
Expand All @@ -493,8 +504,9 @@ def _wait_and_process(seconds, ignore_status_now=False):
next_check_versions = datetime.datetime.now()
status_sent = 0
self._create_socket()
self._shutdown = False

while True:
while not self._shutdown:
self._logger.debug("self._socket: {}".format(repr(self._socket)))
if self._socket:
self._logger.debug("_wait_and_process")
Expand Down Expand Up @@ -547,6 +559,8 @@ def _wait_and_process(seconds, ignore_status_now=False):
else:
skip_snapshot = False
self._upload_snapshot()
if self._shutdown:
return

self._logger.info("Socket disconnected, clear and restart")
if status_sent < 3 and not self._disconnect_on_register:
Expand Down Expand Up @@ -601,7 +615,7 @@ def _upload_snapshot(self):
image_size = len(image_bytes)
if self._image_transpose or image_size > self._max_image_size:
self._logger.debug("Recompressing snapshot to smaller size")
buf = StringIO()
buf = BytesIO()
buf.write(image_bytes)
image = Image.open(buf)
image.thumbnail((640, 480))
Expand All @@ -611,7 +625,7 @@ def _upload_snapshot(self):
image = image.transpose(Image.FLIP_TOP_BOTTOM)
if self._settings.global_get(["webcam", "rotate90"]):
image = image.transpose(Image.ROTATE_90)
image_bytes = StringIO()
image_bytes = BytesIO()
image.save(image_bytes, format="jpeg")
image_bytes.seek(0, 2)
new_image_size = image_bytes.tell()
Expand Down Expand Up @@ -689,7 +703,7 @@ def _on_welcome(self, welcome, *args, **kwargs):
self._logger.debug('_on_welcome: {}'.format(repr(welcome)))
if 'challenge' in welcome:
self._challenge = welcome['challenge']
if isinstance(self._challenge, unicode):
if not isinstance(self._challenge, bytes):
self._challenge = self._challenge.encode('utf-8')
self._task_queue.put(self._hello)

Expand All @@ -716,7 +730,7 @@ def _hello(self):
transformImg += 4
self._socket.emit('hello', {
'serialNumber': self._serial,
'signature': base64.b64encode(crypto.sign(self._key, self._challenge, b'sha256')),
'signature': base64.b64encode(crypto.sign(self._key, self._challenge, 'sha256')).decode('utf-8'),
'MAC': get_mac(),
'localIP': get_ip(),
'protocol': '2',
Expand Down Expand Up @@ -888,8 +902,13 @@ def _on_print(self, data, *args, **kwargs):
self._logger.exception("Could not retrieve slicer config file from PolarCloud: {}".format(data['configFile']))
return
slicer = self._get_slicer_name()
(slicing_profile, pos) = self._create_slicing_profile(slicer, req_ini.content)
if not slicing_profile:
slicing_profile = None
try:
(slicing_profile, pos) = self._create_slicing_profile(slicer, req_ini.content)
except (UnknownSlicer, SlicerNotConfigured):
#TODO tell PolarCloud that we don't have a slicer so it can tell the user
pass
if slicing_profile is None:
self._logger.warn("Unable to create slicing profile. Aborting slice and print.")
return

Expand All @@ -906,7 +925,7 @@ def _on_print(self, data, *args, **kwargs):
path = self._file_manager.join_path(FileDestinations.LOCAL, path, "current-print")
pathGcode = path + ".gcode"
path = path + (".gcode" if gcode else ".stl")
self._file_manager.add_file(FileDestinations.LOCAL, path, StreamWrapper(path, io.BytesIO(req_stl.content)), allow_overwrite=True)
self._file_manager.add_file(FileDestinations.LOCAL, path, StreamWrapper(path, BytesIO(req_stl.content)), allow_overwrite=True)
job_id = data['jobId'] if 'jobId' in data else "123"
self._logger.debug("print jobId is {}".format(job_id))
self._logger.debug("print data is {}".format(repr(data)))
Expand Down Expand Up @@ -1182,6 +1201,9 @@ def on_event(self, event, payload):
else:
self._pstate = self.PSTATE_COMPLETE
self._pstate_counter = 3
elif event == Events.SHUTDOWN:
self._shutdown = True
return
elif hasattr(Events, 'PRINTER_STATE_CHANGED') and event == Events.PRINTER_STATE_CHANGED:
self._status_now = True
return
Expand Down Expand Up @@ -1242,26 +1264,15 @@ def readline(self):
self._indent = not self._indent
return line


def config_file_generator(fp):
# prepend a dummy section header (x)
# indent multi-line strings (in triple quotes)
indent = False
line = "[x]"
while line:
if indent:
line = " " + line
if '"""' in line:
indent = not not indent
yield line
line = fp.readline()

# create an in memory "file" of the profile and prepend a dummy section
# header so ConfigParser won't give up so easily
config_file = ConfigFileReader(config_file_bytes)
config_file = ConfigFileReader(config_file_bytes.decode('utf-8'))

import ConfigParser
config = ConfigParser.ConfigParser()
try:
import configparser
except ImportError:
import ConfigParser as configparser
config = configparser.ConfigParser()
try:
config.readfp(config_file)
except:
Expand Down Expand Up @@ -1484,6 +1495,7 @@ def _preparation_worker(self):
self._callback_failed()

__plugin_name__ = "PolarCloud"
__plugin_pythoncompat__ = ">=2.7,<4"

def __plugin_load__():
global __plugin_implementation__
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@
print("May not be able to successfully install with setuptools earlier than 40.0.0. If this fails, upgrade setup tools with 'pip install --upgrade setuptools'.")
else:
plat = distutils.util.get_platform().replace('.', '_').replace('-', '_')
if plat in ['linux_armv7l', 'linux_armv6l'] and not hasattr(sys, 'pypy_version_info'):
if sys.version_info[0:2] == (2, 7) and plat in ['linux_armv7l', 'linux_armv6l'] and not hasattr(sys, 'pypy_version_info'):
plugin_requires = [
"cryptography @ https://markwal.github.io/wheelhouse/cryptography-3.0-cp27-none-" + plat + ".whl",
"cffi @ https://markwal.github.io/wheelhouse/cffi-1.12.1-cp27-none-" + plat + ".whl",
Expand Down

0 comments on commit 0d51688

Please sign in to comment.