chiark / gitweb /
Merge pull request #908 from Dim3nsioneer/SteamEngine
[cura.git] / Cura / gui / printWindow.py
1 __copyright__ = "Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License"
2
3 import wx
4 import power
5 import time
6 import sys
7 import os
8 import ctypes
9
10 #TODO: This does not belong here!
11 if sys.platform.startswith('win'):
12         def preventComputerFromSleeping(prevent):
13                 """
14                 Function used to prevent the computer from going into sleep mode.
15                 :param prevent: True = Prevent the system from going to sleep from this point on.
16                 :param prevent: False = No longer prevent the system from going to sleep.
17                 """
18                 ES_CONTINUOUS = 0x80000000
19                 ES_SYSTEM_REQUIRED = 0x00000001
20                 #SetThreadExecutionState returns 0 when failed, which is ignored. The function should be supported from windows XP and up.
21                 if prevent:
22                         ctypes.windll.kernel32.SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED)
23                 else:
24                         ctypes.windll.kernel32.SetThreadExecutionState(ES_CONTINUOUS)
25
26 else:
27         def preventComputerFromSleeping(prevent):
28                 #No preventComputerFromSleeping for MacOS and Linux yet.
29                 pass
30
31 class printWindowPlugin(wx.Frame):
32         def __init__(self, parent, printerConnection, filename):
33                 super(printWindowPlugin, self).__init__(parent, -1, style=wx.CLOSE_BOX|wx.CLIP_CHILDREN|wx.CAPTION|wx.SYSTEM_MENU|wx.FRAME_FLOAT_ON_PARENT|wx.MINIMIZE_BOX, title=_("Printing on %s") % (printerConnection.getName()))
34                 self._printerConnection = printerConnection
35                 self._basePath = os.path.dirname(filename)
36                 self._backgroundImage = None
37                 self._colorCommandMap = {}
38                 self._buttonList = []
39                 self._termLog = None
40                 self._termInput = None
41                 self._termHistory = []
42                 self._termHistoryIdx = 0
43                 self._progressBar = None
44                 self._tempGraph = None
45                 self._infoText = None
46                 self._lastUpdateTime = time.time()
47
48                 variables = {
49                         'setImage': self.script_setImage,
50                         'addColorCommand': self.script_addColorCommand,
51                         'addTerminal': self.script_addTerminal,
52                         'addTemperatureGraph': self.script_addTemperatureGraph,
53                         'addProgressbar': self.script_addProgressbar,
54                         'addButton': self.script_addButton,
55                         'addSpinner': self.script_addSpinner,
56
57                         'sendGCode': self.script_sendGCode,
58                         'connect': self.script_connect,
59                         'startPrint': self.script_startPrint,
60                         'pausePrint': self.script_pausePrint,
61                         'cancelPrint': self.script_cancelPrint,
62                         'showErrorLog': self.script_showErrorLog,
63                 }
64                 execfile(filename, variables, variables)
65
66                 self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
67                 self.Bind(wx.EVT_PAINT, self.OnDraw)
68                 self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftClick)
69                 self.Bind(wx.EVT_CLOSE, self.OnClose)
70
71                 self._updateButtonStates()
72
73                 self._printerConnection.addCallback(self._doPrinterConnectionUpdate)
74
75                 if self._printerConnection.hasActiveConnection() and not self._printerConnection.isActiveConnectionOpen():
76                         self._printerConnection.openActiveConnection()
77                 preventComputerFromSleeping(True)
78
79         def script_setImage(self, guiImage, mapImage):
80                 self._backgroundImage = wx.BitmapFromImage(wx.Image(os.path.join(self._basePath, guiImage)))
81                 self._mapImage = wx.Image(os.path.join(self._basePath, mapImage))
82                 self.SetClientSize(self._mapImage.GetSize())
83
84         def script_addColorCommand(self, r, g, b, command, data = None):
85                 self._colorCommandMap[(r, g, b)] = (command, data)
86
87         def script_addTerminal(self, r, g, b):
88                 x, y, w, h = self._getColoredRect(r, g, b)
89                 if x < 0 or self._termLog is not None:
90                         return
91                 f = wx.Font(8, wx.FONTFAMILY_MODERN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False)
92                 self._termLog = wx.TextCtrl(self, style=wx.TE_MULTILINE | wx.TE_DONTWRAP)
93                 self._termLog.SetFont(f)
94                 self._termLog.SetEditable(0)
95                 self._termInput = wx.TextCtrl(self, style=wx.TE_PROCESS_ENTER)
96                 self._termInput.SetFont(f)
97
98                 self._termLog.SetPosition((x, y))
99                 self._termLog.SetSize((w, h - self._termInput.GetSize().GetHeight()))
100                 self._termInput.SetPosition((x, y + h - self._termInput.GetSize().GetHeight()))
101                 self._termInput.SetSize((w, self._termInput.GetSize().GetHeight()))
102                 self.Bind(wx.EVT_TEXT_ENTER, self.OnTermEnterLine, self._termInput)
103                 self._termInput.Bind(wx.EVT_CHAR, self.OnTermKey)
104
105         def script_addTemperatureGraph(self, r, g, b):
106                 x, y, w, h = self._getColoredRect(r, g, b)
107                 if x < 0 or self._tempGraph is not None:
108                         return
109                 self._tempGraph = TemperatureGraph(self)
110
111                 self._tempGraph.SetPosition((x, y))
112                 self._tempGraph.SetSize((w, h))
113
114         def script_addProgressbar(self, r, g, b):
115                 x, y, w, h = self._getColoredRect(r, g, b)
116                 if x < 0:
117                         return
118                 self._progressBar = wx.Gauge(self, -1, range=1000)
119
120                 self._progressBar.SetPosition((x, y))
121                 self._progressBar.SetSize((w, h))
122
123         def script_addButton(self, r, g, b, text, command, data = None):
124                 x, y, w, h = self._getColoredRect(r, g, b)
125                 if x < 0:
126                         return
127                 button = wx.Button(self, -1, _(text))
128                 button.SetPosition((x, y))
129                 button.SetSize((w, h))
130                 button.command = command
131                 button.data = data
132                 self._buttonList.append(button)
133                 self.Bind(wx.EVT_BUTTON, lambda e: command(data), button)
134
135         def script_addSpinner(self, r, g, b, command, data):
136                 x, y, w, h = self._getColoredRect(r, g, b)
137                 if x < 0:
138                         return
139                 spinner = wx.SpinCtrl(self, -1, style=wx.TE_PROCESS_ENTER)
140                 spinner.SetRange(0, 300)
141                 spinner.SetPosition((x, y))
142                 spinner.SetSize((w, h))
143                 spinner.command = command
144                 spinner.data = data
145                 self._buttonList.append(spinner)
146                 self.Bind(wx.EVT_SPINCTRL, lambda e: command(data % (spinner.GetValue())), spinner)
147
148         def _getColoredRect(self, r, g, b):
149                 for x in xrange(0, self._mapImage.GetWidth()):
150                         for y in xrange(0, self._mapImage.GetHeight()):
151                                 if self._mapImage.GetRed(x, y) == r and self._mapImage.GetGreen(x, y) == g and self._mapImage.GetBlue(x, y) == b:
152                                         w = 0
153                                         while x+w < self._mapImage.GetWidth() and self._mapImage.GetRed(x + w, y) == r and self._mapImage.GetGreen(x + w, y) == g and self._mapImage.GetBlue(x + w, y) == b:
154                                                 w += 1
155                                         h = 0
156                                         while y+h < self._mapImage.GetHeight() and self._mapImage.GetRed(x, y + h) == r and self._mapImage.GetGreen(x, y + h) == g and self._mapImage.GetBlue(x, y + h) == b:
157                                                 h += 1
158                                         return x, y, w, h
159                 print "Failed to find color: ", r, g, b
160                 return -1, -1, 1, 1
161
162         def script_sendGCode(self, data = None):
163                 for line in data.split(';'):
164                         line = line.strip()
165                         if len(line) > 0:
166                                 self._printerConnection.sendCommand(line)
167
168         def script_connect(self, data = None):
169                 self._printerConnection.openActiveConnection()
170
171         def script_startPrint(self, data = None):
172                 self._printerConnection.startPrint()
173
174         def script_cancelPrint(self, e):
175                 self._printerConnection.cancelPrint()
176
177         def script_pausePrint(self, e):
178                 self._printerConnection.pause(not self._printerConnection.isPaused())
179
180         def script_showErrorLog(self, e):
181                 LogWindow(self._printerConnection.getErrorLog())
182
183         def OnEraseBackground(self, e):
184                 pass
185
186         def OnDraw(self, e):
187                 dc = wx.BufferedPaintDC(self, self._backgroundImage)
188
189         def OnLeftClick(self, e):
190                 r = self._mapImage.GetRed(e.GetX(), e.GetY())
191                 g = self._mapImage.GetGreen(e.GetX(), e.GetY())
192                 b = self._mapImage.GetBlue(e.GetX(), e.GetY())
193                 if (r, g, b) in self._colorCommandMap:
194                         command = self._colorCommandMap[(r, g, b)]
195                         command[0](command[1])
196
197         def OnClose(self, e):
198                 if self._printerConnection.hasActiveConnection():
199                         if self._printerConnection.isPrinting():
200                                 pass #TODO: Give warning that the close will kill the print.
201                         self._printerConnection.closeActiveConnection()
202                 self._printerConnection.removeCallback(self._doPrinterConnectionUpdate)
203                 #TODO: When multiple printer windows are open, closing one will enable sleeping again.
204                 preventComputerFromSleeping(False)
205                 self.Destroy()
206
207         def OnTermEnterLine(self, e):
208                 if not self._printerConnection.isAbleToSendDirectCommand():
209                         return
210                 line = self._termInput.GetValue()
211                 if line == '':
212                         return
213                 self._addTermLog('> %s\n' % (line))
214                 self._printerConnection.sendCommand(line)
215                 self._termHistory.append(line)
216                 self._termHistoryIdx = len(self._termHistory)
217                 self._termInput.SetValue('')
218
219         def OnTermKey(self, e):
220                 if len(self._termHistory) > 0:
221                         if e.GetKeyCode() == wx.WXK_UP:
222                                 self._termHistoryIdx -= 1
223                                 if self._termHistoryIdx < 0:
224                                         self._termHistoryIdx = len(self._termHistory) - 1
225                                 self._termInput.SetValue(self._termHistory[self._termHistoryIdx])
226                         if e.GetKeyCode() == wx.WXK_DOWN:
227                                 self._termHistoryIdx -= 1
228                                 if self._termHistoryIdx >= len(self._termHistory):
229                                         self._termHistoryIdx = 0
230                                 self._termInput.SetValue(self._termHistory[self._termHistoryIdx])
231                 e.Skip()
232
233         def _addTermLog(self, line):
234                 if self._termLog is not None:
235                         if len(self._termLog.GetValue()) > 10000:
236                                 self._termLog.SetValue(self._termLog.GetValue()[-10000:])
237                         self._termLog.SetInsertionPointEnd()
238                         if type(line) != unicode:
239                                 line = unicode(line, 'utf-8', 'replace')
240                         self._termLog.AppendText(line.encode('utf-8', 'replace'))
241
242         def _updateButtonStates(self):
243                 for button in self._buttonList:
244                         if button.command == self.script_connect:
245                                 button.Show(self._printerConnection.hasActiveConnection())
246                                 button.Enable(not self._printerConnection.isActiveConnectionOpen() and not self._printerConnection.isActiveConnectionOpening())
247                         elif button.command == self.script_pausePrint:
248                                 button.Show(self._printerConnection.hasPause())
249                                 if not self._printerConnection.hasActiveConnection() or self._printerConnection.isActiveConnectionOpen():
250                                         button.Enable(self._printerConnection.isPrinting() or self._printerConnection.isPaused())
251                                 else:
252                                         button.Enable(False)
253                         elif button.command == self.script_startPrint:
254                                 if not self._printerConnection.hasActiveConnection() or self._printerConnection.isActiveConnectionOpen():
255                                         button.Enable(not self._printerConnection.isPrinting())
256                                 else:
257                                         button.Enable(False)
258                         elif button.command == self.script_cancelPrint:
259                                 if not self._printerConnection.hasActiveConnection() or self._printerConnection.isActiveConnectionOpen():
260                                         button.Enable(self._printerConnection.isPrinting())
261                                 else:
262                                         button.Enable(False)
263                         elif button.command == self.script_showErrorLog:
264                                 button.Show(self._printerConnection.isInErrorState())
265                 if self._termInput is not None:
266                         self._termInput.Enable(self._printerConnection.isAbleToSendDirectCommand())
267
268         def _doPrinterConnectionUpdate(self, connection, extraInfo = None):
269                 wx.CallAfter(self.__doPrinterConnectionUpdate, connection, extraInfo)
270                 if self._tempGraph is not None:
271                         temp = []
272                         for n in xrange(0, 4):
273                                 t = connection.getTemperature(0)
274                                 if t is not None:
275                                         temp.append(t)
276                                 else:
277                                         break
278                         self._tempGraph.addPoint(temp, [0] * len(temp), connection.getBedTemperature(), 0)
279
280         def __doPrinterConnectionUpdate(self, connection, extraInfo):
281                 t = time.time()
282                 if self._lastUpdateTime + 0.5 > t and extraInfo is None:
283                         return
284                 self._lastUpdateTime = t
285
286                 if extraInfo is not None:
287                         self._addTermLog('< %s\n' % (extraInfo))
288
289                 self._updateButtonStates()
290                 if self._progressBar is not None:
291                         if connection.isPrinting():
292                                 self._progressBar.SetValue(connection.getPrintProgress() * 1000)
293                         else:
294                                 self._progressBar.SetValue(0)
295                 info = connection.getStatusString()
296                 info += '\n'
297                 if self._printerConnection.getTemperature(0) is not None:
298                         info += 'Temperature: %d' % (self._printerConnection.getTemperature(0))
299                 if self._printerConnection.getBedTemperature() > 0:
300                         info += ' Bed: %d' % (self._printerConnection.getBedTemperature())
301                 if self._infoText is not None:
302                         self._infoText.SetLabel(info)
303                 else:
304                         self.SetTitle(info.replace('\n', ', '))
305
306 class printWindowBasic(wx.Frame):
307         """
308         Printing window for USB printing, network printing, and any other type of printer connection we can think off.
309         This is only a basic window with minimal information.
310         """
311         def __init__(self, parent, printerConnection):
312                 super(printWindowBasic, self).__init__(parent, -1, style=wx.CLOSE_BOX|wx.CLIP_CHILDREN|wx.CAPTION|wx.SYSTEM_MENU|wx.FRAME_TOOL_WINDOW|wx.FRAME_FLOAT_ON_PARENT, title=_("Printing on %s") % (printerConnection.getName()))
313                 self._printerConnection = printerConnection
314                 self._lastUpdateTime = 0
315
316                 self.SetSizer(wx.BoxSizer())
317                 self.panel = wx.Panel(self)
318                 self.GetSizer().Add(self.panel, 1, flag=wx.EXPAND)
319                 self.sizer = wx.GridBagSizer(2, 2)
320                 self.panel.SetSizer(self.sizer)
321
322                 self.powerWarningText = wx.StaticText(parent=self.panel,
323                         id=-1,
324                         label=_("Your computer is running on battery power.\nConnect your computer to AC power or your print might not finish."),
325                         style=wx.ALIGN_CENTER)
326                 self.powerWarningText.SetBackgroundColour('red')
327                 self.powerWarningText.SetForegroundColour('white')
328                 self.powerManagement = power.PowerManagement()
329                 self.powerWarningTimer = wx.Timer(self)
330                 self.Bind(wx.EVT_TIMER, self.OnPowerWarningChange, self.powerWarningTimer)
331                 self.OnPowerWarningChange(None)
332                 self.powerWarningTimer.Start(10000)
333
334                 self.statsText = wx.StaticText(self.panel, -1, _("InfoLine from printer connection\nInfoLine from dialog\nExtra line\nMore lines for layout\nMore lines for layout\nMore lines for layout"))
335
336                 self.connectButton = wx.Button(self.panel, -1, _("Connect"))
337                 #self.loadButton = wx.Button(self.panel, -1, 'Load')
338                 self.printButton = wx.Button(self.panel, -1, _("Print"))
339                 self.pauseButton = wx.Button(self.panel, -1, _("Pause"))
340                 self.cancelButton = wx.Button(self.panel, -1, _("Cancel print"))
341                 self.errorLogButton = wx.Button(self.panel, -1, _("Error log"))
342                 self.progress = wx.Gauge(self.panel, -1, range=1000)
343
344                 self.sizer.Add(self.powerWarningText, pos=(0, 0), span=(1, 5), flag=wx.EXPAND|wx.BOTTOM, border=5)
345                 self.sizer.Add(self.statsText, pos=(1, 0), span=(1, 5), flag=wx.LEFT, border=5)
346                 self.sizer.Add(self.connectButton, pos=(2, 0))
347                 #self.sizer.Add(self.loadButton, pos=(2,1))
348                 self.sizer.Add(self.printButton, pos=(2, 1))
349                 self.sizer.Add(self.pauseButton, pos=(2, 2))
350                 self.sizer.Add(self.cancelButton, pos=(2, 3))
351                 self.sizer.Add(self.errorLogButton, pos=(2, 4))
352                 self.sizer.Add(self.progress, pos=(3, 0), span=(1, 5), flag=wx.EXPAND)
353
354                 self.Bind(wx.EVT_CLOSE, self.OnClose)
355                 self.connectButton.Bind(wx.EVT_BUTTON, self.OnConnect)
356                 #self.loadButton.Bind(wx.EVT_BUTTON, self.OnLoad)
357                 self.printButton.Bind(wx.EVT_BUTTON, self.OnPrint)
358                 self.pauseButton.Bind(wx.EVT_BUTTON, self.OnPause)
359                 self.cancelButton.Bind(wx.EVT_BUTTON, self.OnCancel)
360                 self.errorLogButton.Bind(wx.EVT_BUTTON, self.OnErrorLog)
361
362                 self.Layout()
363                 self.Fit()
364                 self.Centre()
365
366                 self.progress.SetMinSize(self.progress.GetSize())
367                 self.statsText.SetLabel('\n\n\n\n\n\n')
368                 self._updateButtonStates()
369
370                 self._printerConnection.addCallback(self._doPrinterConnectionUpdate)
371
372                 if self._printerConnection.hasActiveConnection() and not self._printerConnection.isActiveConnectionOpen():
373                         self._printerConnection.openActiveConnection()
374                 preventComputerFromSleeping(True)
375
376         def OnPowerWarningChange(self, e):
377                 type = self.powerManagement.get_providing_power_source_type()
378                 if type == power.POWER_TYPE_AC and self.powerWarningText.IsShown():
379                         self.powerWarningText.Hide()
380                         self.panel.Layout()
381                         self.Layout()
382                         self.Fit()
383                         self.Refresh()
384                 elif type != power.POWER_TYPE_AC and not self.powerWarningText.IsShown():
385                         self.powerWarningText.Show()
386                         self.panel.Layout()
387                         self.Layout()
388                         self.Fit()
389                         self.Refresh()
390
391         def OnClose(self, e):
392                 if self._printerConnection.hasActiveConnection():
393                         if self._printerConnection.isPrinting():
394                                 pass #TODO: Give warning that the close will kill the print.
395                         self._printerConnection.closeActiveConnection()
396                 self._printerConnection.removeCallback(self._doPrinterConnectionUpdate)
397                 #TODO: When multiple printer windows are open, closing one will enable sleeping again.
398                 preventComputerFromSleeping(False)
399                 self.Destroy()
400
401         def OnConnect(self, e):
402                 self._printerConnection.openActiveConnection()
403
404         def OnLoad(self, e):
405                 pass
406
407         def OnPrint(self, e):
408                 self._printerConnection.startPrint()
409
410         def OnCancel(self, e):
411                 self._printerConnection.cancelPrint()
412
413         def OnPause(self, e):
414                 self._printerConnection.pause(not self._printerConnection.isPaused())
415
416         def OnErrorLog(self, e):
417                 LogWindow(self._printerConnection.getErrorLog())
418
419         def _doPrinterConnectionUpdate(self, connection, extraInfo = None):
420                 wx.CallAfter(self.__doPrinterConnectionUpdate, connection, extraInfo)
421                 #temp = [connection.getTemperature(0)]
422                 #self.temperatureGraph.addPoint(temp, [0], connection.getBedTemperature(), 0)
423
424         def __doPrinterConnectionUpdate(self, connection, extraInfo):
425                 t = time.time()
426                 if self._lastUpdateTime + 0.5 > t and extraInfo is None:
427                         return
428                 self._lastUpdateTime = t
429
430                 if extraInfo is not None:
431                         self._addTermLog('< %s\n' % (extraInfo))
432
433                 self._updateButtonStates()
434                 if connection.isPrinting():
435                         self.progress.SetValue(connection.getPrintProgress() * 1000)
436                 else:
437                         self.progress.SetValue(0)
438                 info = connection.getStatusString()
439                 info += '\n'
440                 if self._printerConnection.getTemperature(0) is not None:
441                         info += 'Temperature: %d' % (self._printerConnection.getTemperature(0))
442                 if self._printerConnection.getBedTemperature() > 0:
443                         info += ' Bed: %d' % (self._printerConnection.getBedTemperature())
444                 info += '\n\n'
445                 self.statsText.SetLabel(info)
446
447         def _updateButtonStates(self):
448                 self.connectButton.Show(self._printerConnection.hasActiveConnection())
449                 self.connectButton.Enable(not self._printerConnection.isActiveConnectionOpen() and not self._printerConnection.isActiveConnectionOpening())
450                 self.pauseButton.Show(self._printerConnection.hasPause())
451                 if not self._printerConnection.hasActiveConnection() or self._printerConnection.isActiveConnectionOpen():
452                         self.printButton.Enable(not self._printerConnection.isPrinting())
453                         self.pauseButton.Enable(self._printerConnection.isPrinting())
454                         self.cancelButton.Enable(self._printerConnection.isPrinting())
455                 else:
456                         self.printButton.Enable(False)
457                         self.pauseButton.Enable(False)
458                         self.cancelButton.Enable(False)
459                 self.errorLogButton.Show(self._printerConnection.isInErrorState())
460
461 class TemperatureGraph(wx.Panel):
462         def __init__(self, parent):
463                 super(TemperatureGraph, self).__init__(parent)
464
465                 self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
466                 self.Bind(wx.EVT_SIZE, self.OnSize)
467                 self.Bind(wx.EVT_PAINT, self.OnDraw)
468
469                 self._lastDraw = time.time() - 1.0
470                 self._points = []
471                 self._backBuffer = None
472                 self.addPoint([0]*16, [0]*16, 0, 0)
473
474         def OnEraseBackground(self, e):
475                 pass
476
477         def OnSize(self, e):
478                 if self._backBuffer is None or self.GetSize() != self._backBuffer.GetSize():
479                         self._backBuffer = wx.EmptyBitmap(*self.GetSizeTuple())
480                         self.UpdateDrawing(True)
481
482         def OnDraw(self, e):
483                 dc = wx.BufferedPaintDC(self, self._backBuffer)
484
485         def UpdateDrawing(self, force=False):
486                 now = time.time()
487                 if (not force and now - self._lastDraw < 1.0) or self._backBuffer is None:
488                         return
489                 self._lastDraw = now
490                 dc = wx.MemoryDC()
491                 dc.SelectObject(self._backBuffer)
492                 dc.Clear()
493                 dc.SetFont(wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT))
494                 w, h = self.GetSizeTuple()
495                 bgLinePen = wx.Pen('#A0A0A0')
496                 tempPen = wx.Pen('#FF4040')
497                 tempSPPen = wx.Pen('#FFA0A0')
498                 tempPenBG = wx.Pen('#FFD0D0')
499                 bedTempPen = wx.Pen('#4040FF')
500                 bedTempSPPen = wx.Pen('#A0A0FF')
501                 bedTempPenBG = wx.Pen('#D0D0FF')
502
503                 #Draw the background up to the current temperatures.
504                 x0 = 0
505                 t0 = []
506                 bt0 = 0
507                 tSP0 = 0
508                 btSP0 = 0
509                 for temp, tempSP, bedTemp, bedTempSP, t in self._points:
510                         x1 = int(w - (now - t))
511                         for x in xrange(x0, x1 + 1):
512                                 for n in xrange(0, min(len(t0), len(temp))):
513                                         t = float(x - x0) / float(x1 - x0 + 1) * (temp[n] - t0[n]) + t0[n]
514                                         dc.SetPen(tempPenBG)
515                                         dc.DrawLine(x, h, x, h - (t * h / 300))
516                                 bt = float(x - x0) / float(x1 - x0 + 1) * (bedTemp - bt0) + bt0
517                                 dc.SetPen(bedTempPenBG)
518                                 dc.DrawLine(x, h, x, h - (bt * h / 300))
519                         t0 = temp
520                         bt0 = bedTemp
521                         tSP0 = tempSP
522                         btSP0 = bedTempSP
523                         x0 = x1 + 1
524
525                 #Draw the grid
526                 for x in xrange(w, 0, -30):
527                         dc.SetPen(bgLinePen)
528                         dc.DrawLine(x, 0, x, h)
529                 tmpNr = 0
530                 for y in xrange(h - 1, 0, -h * 50 / 300):
531                         dc.SetPen(bgLinePen)
532                         dc.DrawLine(0, y, w, y)
533                         dc.DrawText(str(tmpNr), 0, y - dc.GetFont().GetPixelSize().GetHeight())
534                         tmpNr += 50
535                 dc.DrawLine(0, 0, w, 0)
536                 dc.DrawLine(0, 0, 0, h)
537
538                 #Draw the main lines
539                 x0 = 0
540                 t0 = []
541                 bt0 = 0
542                 tSP0 = []
543                 btSP0 = 0
544                 for temp, tempSP, bedTemp, bedTempSP, t in self._points:
545                         x1 = int(w - (now - t))
546                         for x in xrange(x0, x1 + 1):
547                                 for n in xrange(0, min(len(t0), len(temp))):
548                                         t = float(x - x0) / float(x1 - x0 + 1) * (temp[n] - t0[n]) + t0[n]
549                                         tSP = float(x - x0) / float(x1 - x0 + 1) * (tempSP[n] - tSP0[n]) + tSP0[n]
550                                         dc.SetPen(tempSPPen)
551                                         dc.DrawPoint(x, h - (tSP * h / 300))
552                                         dc.SetPen(tempPen)
553                                         dc.DrawPoint(x, h - (t * h / 300))
554                                 bt = float(x - x0) / float(x1 - x0 + 1) * (bedTemp - bt0) + bt0
555                                 btSP = float(x - x0) / float(x1 - x0 + 1) * (bedTempSP - btSP0) + btSP0
556                                 dc.SetPen(bedTempSPPen)
557                                 dc.DrawPoint(x, h - (btSP * h / 300))
558                                 dc.SetPen(bedTempPen)
559                                 dc.DrawPoint(x, h - (bt * h / 300))
560                         t0 = temp
561                         bt0 = bedTemp
562                         tSP0 = tempSP
563                         btSP0 = bedTempSP
564                         x0 = x1 + 1
565
566                 del dc
567                 self.Refresh(eraseBackground=False)
568                 self.Update()
569
570                 if len(self._points) > 0 and (time.time() - self._points[0][4]) > w + 20:
571                         self._points.pop(0)
572
573         def addPoint(self, temp, tempSP, bedTemp, bedTempSP):
574                 if len(self._points) > 0 and time.time() - self._points[-1][4] < 0.5:
575                         return
576                 for n in xrange(0, len(temp)):
577                         if temp[n] is None:
578                                 temp[n] = 0
579                 for n in xrange(0, len(tempSP)):
580                         if tempSP[n] is None:
581                                 tempSP[n] = 0
582                 if bedTemp is None:
583                         bedTemp = 0
584                 if bedTempSP is None:
585                         bedTempSP = 0
586                 self._points.append((temp[:], tempSP[:], bedTemp, bedTempSP, time.time()))
587                 wx.CallAfter(self.UpdateDrawing)
588
589
590 class LogWindow(wx.Frame):
591         def __init__(self, logText):
592                 super(LogWindow, self).__init__(None, title="Error log")
593                 self.textBox = wx.TextCtrl(self, -1, logText, style=wx.TE_MULTILINE | wx.TE_DONTWRAP | wx.TE_READONLY)
594                 self.SetSize((500, 400))
595                 self.Show(True)