Skip to content

Instantly share code, notes, and snippets.

@daid
Created November 12, 2013 14:54
Show Gist options
  • Save daid/81134b50e1f27b672481 to your computer and use it in GitHub Desktop.
Save daid/81134b50e1f27b672481 to your computer and use it in GitHub Desktop.
__copyright__ = "Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License"
import threading
import json
import httplib as httpclient
import urllib
import time
#Class to connect and print files with the doodle3d.com wifi box
class doodle3dConnect(object):
def __init__(self):
self._http = None
self._connected = False
self._printing = False
self._fileBlocks = []
self._blockIndex = None
self.checkThread = threading.Thread(target=self._checkForDoodle3D)
self.checkThread.daemon = True
self.checkThread.start()
def loadFile(self, filename):
if self._printing:
return
self._fileBlocks = []
block = []
blockSize = 0
f = open(filename, "r")
for line in f:
if ';' in line:
line = line[:line.index(';')]
line = line.strip()
#Strip out spaces in G0 and G1 lines, the firmware does not care about them, and it saves about 10% space.
if line.startswith('G0') or line.startswith('G1'):
line = line.replace(' ', '')
if len(line) < 1:
continue
if blockSize + len(line) > 2048:
self._fileBlocks.append('\n'.join(block))
block = []
blockSize = 0
blockSize += len(line) + 1
block.append(line)
self._fileBlocks.append('\n'.join(block))
f.close()
def startPrint(self):
if self._printing:
return
self._blockIndex = 0
self._printing = True
def stopPrint(self):
if not self._printing:
return
if self._request('POST', '/d3dapi/printer/stop'):
self._printing = False
def isConnected(self):
return self._connected
def isPrinting(self):
return self._printing
def _checkForDoodle3D(self):
while True:
stateReply = self._request('GET', '/d3dapi/printer/state')
if stateReply is None: #No API, wait 1 minute before looking for Doodle3D again.
self._connected = False
time.sleep(60)
continue
if not stateReply: #API gave back an error (this can happen if the Doodle3D box is connecting to the printer)
self._connected = False
time.sleep(5)
continue
self._connected = True
if stateReply['data']['state'] == 'idle':
if self._printing:
if self._blockIndex < len(self._fileBlocks):
if self._request('POST', '/d3dapi/printer/print', {'gcode': self._fileBlocks[self._blockIndex], 'start': 'True', 'first': 'True'}):
self._blockIndex += 1
else:
self._printing = False
if stateReply['data']['state'] == 'printing':
if self._printing:
if self._blockIndex < len(self._fileBlocks):
reply = self._request('POST', '/d3dapi/printer/print', {'gcode': self._fileBlocks[self._blockIndex]}), self._blockIndex, len(self._fileBlocks)
if reply:
self._blockIndex += 1
else:
print 'Progress:', self._request('GET', '/d3dapi/printer/progress')
time.sleep(5)
else:
#Got a printing state without us having send the print file, set the state to printing, but make sure we never send anything.
self._printing = True
self._blockIndex = len(self._fileBlocks)
def _request(self, method, path, postData = None):
if self._http is None:
self._http = httpclient.HTTPConnection('draw.doodle3d.com')
try:
if postData is not None:
self._http.request(method, path, urllib.urlencode(postData), {"Content-type": "application/x-www-form-urlencoded"})
else:
self._http.request(method, path)
except:
print 'err', method, path
self._http.close()
return None
try:
response = self._http.getresponse()
responseText = response.read()
except:
print 'err2', method, path
self._http.close()
return None
try:
response = json.loads(responseText)
except ValueError:
print 'err3', method, path, responseText
self._http.close()
return None
if response['status'] != 'success':
return False
return response
if __name__ == '__main__':
d = doodle3dConnect()
print 'Searching for Doodle3D box'
while not d.isConnected():
time.sleep(1)
if d.isPrinting():
print 'Doodle3D already printing! Requesting stop!'
d.stopPrint()
#print 'Doodle3D box found, printing!'
#d.loadFile("C:/Models/belt-tensioner-wave_export.gcode")
#d.startPrint()
#while d.isPrinting():
# time.sleep(1)
#d.stopPrint()
#print 'Done'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment