chiark / gitweb /
Workaround for temperature control issue
[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
140                 def run_command(spinner):
141                         value = spinner.GetValue()
142                         if spinner.last_value != value:
143                                 if spinner.last_value != '' and value != 0:
144                                         spinner.command(spinner.data % value)
145                                 spinner.last_value = value
146
147                 spinner = wx.SpinCtrl(self, -1, style=wx.TE_PROCESS_ENTER)
148                 spinner.SetRange(0, 300)
149                 spinner.SetPosition((x, y))
150                 spinner.SetSize((w, h))
151                 spinner.command = command
152                 spinner.data = data
153                 spinner.last_value = ''
154                 self._buttonList.append(spinner)
155                 self.Bind(wx.EVT_SPINCTRL, lambda e: run_command(spinner), spinner)
156
157         def _getColoredRect(self, r, g, b):
158                 for x in xrange(0, self._mapImage.GetWidth()):
159                         for y in xrange(0, self._mapImage.GetHeight()):
160                                 if self._mapImage.GetRed(x, y) == r and self._mapImage.GetGreen(x, y) == g and self._mapImage.GetBlue(x, y) == b:
161                                         w = 0
162                                         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:
163                                                 w += 1
164                                         h = 0
165                                         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:
166                                                 h += 1
167                                         return x, y, w, h
168                 print "Failed to find color: ", r, g, b
169                 return -1, -1, 1, 1
170
171         def script_sendGCode(self, data = None):
172                 for line in data.split(';'):
173                         line = line.strip()
174                         if len(line) > 0:
175                                 self._printerConnection.sendCommand(line)
176
177         def script_connect(self, data = None):
178                 self._printerConnection.openActiveConnection()
179
180         def script_startPrint(self, data = None):
181                 self._printerConnection.startPrint()
182
183         def script_cancelPrint(self, e):
184                 self._printerConnection.cancelPrint()
185
186         def script_pausePrint(self, e):
187                 self._printerConnection.pause(not self._printerConnection.isPaused())
188
189         def script_showErrorLog(self, e):
190                 LogWindow(self._printerConnection.getErrorLog())
191
192         def OnEraseBackground(self, e):
193                 pass
194
195         def OnDraw(self, e):
196                 dc = wx.BufferedPaintDC(self, self._backgroundImage)
197
198         def OnLeftClick(self, e):
199                 r = self._mapImage.GetRed(e.GetX(), e.GetY())
200                 g = self._mapImage.GetGreen(e.GetX(), e.GetY())
201                 b = self._mapImage.GetBlue(e.GetX(), e.GetY())
202                 if (r, g, b) in self._colorCommandMap:
203                         command = self._colorCommandMap[(r, g, b)]
204                         command[0](command[1])
205
206         def OnClose(self, e):
207                 if self._printerConnection.hasActiveConnection():
208                         if self._printerConnection.isPrinting():
209                                 pass #TODO: Give warning that the close will kill the print.
210                         self._printerConnection.closeActiveConnection()
211                 self._printerConnection.removeCallback(self._doPrinterConnectionUpdate)
212                 #TODO: When multiple printer windows are open, closing one will enable sleeping again.
213                 preventComputerFromSleeping(False)
214                 self.Destroy()
215
216         def OnTermEnterLine(self, e):
217                 if not self._printerConnection.isAbleToSendDirectCommand():
218                         return
219                 line = self._termInput.GetValue()
220                 if line == '':
221                         return
222                 self._addTermLog('> %s\n' % (line))
223                 self._printerConnection.sendCommand(line)
224                 self._termHistory.append(line)
225                 self._termHistoryIdx = len(self._termHistory)
226                 self._termInput.SetValue('')
227
228         def OnTermKey(self, e):
229                 if len(self._termHistory) > 0:
230                         if e.GetKeyCode() == wx.WXK_UP:
231                                 self._termHistoryIdx -= 1
232                                 if self._termHistoryIdx < 0:
233                                         self._termHistoryIdx = len(self._termHistory) - 1
234                                 self._termInput.SetValue(self._termHistory[self._termHistoryIdx])
235                         if e.GetKeyCode() == wx.WXK_DOWN:
236                                 self._termHistoryIdx -= 1
237                                 if self._termHistoryIdx >= len(self._termHistory):
238                                         self._termHistoryIdx = 0
239                                 self._termInput.SetValue(self._termHistory[self._termHistoryIdx])
240                 e.Skip()
241
242         def _addTermLog(self, line):
243                 if self._termLog is not None:
244                         if len(self._termLog.GetValue()) > 10000:
245                                 self._termLog.SetValue(self._termLog.GetValue()[-10000:])
246                         self._termLog.SetInsertionPointEnd()
247                         if type(line) != unicode:
248                                 line = unicode(line, 'utf-8', 'replace')
249                         self._termLog.AppendText(line.encode('utf-8', 'replace'))
250
251         def _updateButtonStates(self):
252                 for button in self._buttonList:
253                         if button.command == self.script_connect:
254                                 button.Show(self._printerConnection.hasActiveConnection())
255                                 button.Enable(not self._printerConnection.isActiveConnectionOpen() and not self._printerConnection.isActiveConnectionOpening())
256                         elif button.command == self.script_pausePrint:
257                                 button.Show(self._printerConnection.hasPause())
258                                 if not self._printerConnection.hasActiveConnection() or self._printerConnection.isActiveConnectionOpen():
259                                         button.Enable(self._printerConnection.isPrinting() or self._printerConnection.isPaused())
260                                 else:
261                                         button.Enable(False)
262                         elif button.command == self.script_startPrint:
263                                 if not self._printerConnection.hasActiveConnection() or self._printerConnection.isActiveConnectionOpen():
264                                         button.Enable(not self._printerConnection.isPrinting())
265                                 else:
266                                         button.Enable(False)
267                         elif button.command == self.script_cancelPrint:
268                                 if not self._printerConnection.hasActiveConnection() or self._printerConnection.isActiveConnectionOpen():
269                                         button.Enable(self._printerConnection.isPrinting())
270                                 else:
271                                         button.Enable(False)
272                         elif button.command == self.script_showErrorLog:
273                                 button.Show(self._printerConnection.isInErrorState())
274                 if self._termInput is not None:
275                         self._termInput.Enable(self._printerConnection.isAbleToSendDirectCommand())
276
277         def _doPrinterConnectionUpdate(self, connection, extraInfo = None):
278                 wx.CallAfter(self.__doPrinterConnectionUpdate, connection, extraInfo)
279                 if self._tempGraph is not None:
280                         temp = []
281                         for n in xrange(0, 4):
282                                 t = connection.getTemperature(0)
283                                 if t is not None:
284                                         temp.append(t)
285                                 else:
286                                         break
287                         self._tempGraph.addPoint(temp, [0] * len(temp), connection.getBedTemperature(), 0)
288
289         def __doPrinterConnectionUpdate(self, connection, extraInfo):
290                 t = time.time()
291                 if self._lastUpdateTime + 0.5 > t and extraInfo is None:
292                         return
293                 self._lastUpdateTime = t
294
295                 if extraInfo is not None:
296                         self._addTermLog('< %s\n' % (extraInfo))
297
298                 self._updateButtonStates()
299                 if self._progressBar is not None:
300                         if connection.isPrinting():
301                                 self._progressBar.SetValue(connection.getPrintProgress() * 1000)
302                         else:
303                                 self._progressBar.SetValue(0)
304                 info = connection.getStatusString()
305                 info += '\n'
306                 if self._printerConnection.getTemperature(0) is not None:
307                         info += 'Temperature: %d' % (self._printerConnection.getTemperature(0))
308                 if self._printerConnection.getBedTemperature() > 0:
309                         info += ' Bed: %d' % (self._printerConnection.getBedTemperature())
310                 if self._infoText is not None:
311                         self._infoText.SetLabel(info)
312                 else:
313                         self.SetTitle(info.replace('\n', ', '))
314
315 class printWindowBasic(wx.Frame):
316         """
317         Printing window for USB printing, network printing, and any other type of printer connection we can think off.
318         This is only a basic window with minimal information.
319         """
320         def __init__(self, parent, printerConnection):
321                 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()))
322                 self._printerConnection = printerConnection
323                 self._lastUpdateTime = 0
324
325                 self.SetSizer(wx.BoxSizer())
326                 self.panel = wx.Panel(self)
327                 self.GetSizer().Add(self.panel, 1, flag=wx.EXPAND)
328                 self.sizer = wx.GridBagSizer(2, 2)
329                 self.panel.SetSizer(self.sizer)
330
331                 self.powerWarningText = wx.StaticText(parent=self.panel,
332                         id=-1,
333                         label=_("Your computer is running on battery power.\nConnect your computer to AC power or your print might not finish."),
334                         style=wx.ALIGN_CENTER)
335                 self.powerWarningText.SetBackgroundColour('red')
336                 self.powerWarningText.SetForegroundColour('white')
337                 self.powerManagement = power.PowerManagement()
338                 self.powerWarningTimer = wx.Timer(self)
339                 self.Bind(wx.EVT_TIMER, self.OnPowerWarningChange, self.powerWarningTimer)
340                 self.OnPowerWarningChange(None)
341                 self.powerWarningTimer.Start(10000)
342
343                 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"))
344
345                 self.connectButton = wx.Button(self.panel, -1, _("Connect"))
346                 #self.loadButton = wx.Button(self.panel, -1, 'Load')
347                 self.printButton = wx.Button(self.panel, -1, _("Print"))
348                 self.pauseButton = wx.Button(self.panel, -1, _("Pause"))
349                 self.cancelButton = wx.Button(self.panel, -1, _("Cancel print"))
350                 self.errorLogButton = wx.Button(self.panel, -1, _("Error log"))
351                 self.progress = wx.Gauge(self.panel, -1, range=1000)
352
353                 self.sizer.Add(self.powerWarningText, pos=(0, 0), span=(1, 5), flag=wx.EXPAND|wx.BOTTOM, border=5)
354                 self.sizer.Add(self.statsText, pos=(1, 0), span=(1, 5), flag=wx.LEFT, border=5)
355                 self.sizer.Add(self.connectButton, pos=(2, 0))
356                 #self.sizer.Add(self.loadButton, pos=(2,1))
357                 self.sizer.Add(self.printButton, pos=(2, 1))
358                 self.sizer.Add(self.pauseButton, pos=(2, 2))
359                 self.sizer.Add(self.cancelButton, pos=(2, 3))
360                 self.sizer.Add(self.errorLogButton, pos=(2, 4))
361                 self.sizer.Add(self.progress, pos=(3, 0), span=(1, 5), flag=wx.EXPAND)
362
363                 self.Bind(wx.EVT_CLOSE, self.OnClose)
364                 self.connectButton.Bind(wx.EVT_BUTTON, self.OnConnect)
365                 #self.loadButton.Bind(wx.EVT_BUTTON, self.OnLoad)
366                 self.printButton.Bind(wx.EVT_BUTTON, self.OnPrint)
367                 self.pauseButton.Bind(wx.EVT_BUTTON, self.OnPause)
368                 self.cancelButton.Bind(wx.EVT_BUTTON, self.OnCancel)
369                 self.errorLogButton.Bind(wx.EVT_BUTTON, self.OnErrorLog)
370
371                 self.Layout()
372                 self.Fit()
373                 self.Centre()
374
375                 self.progress.SetMinSize(self.progress.GetSize())
376                 self.statsText.SetLabel('\n\n\n\n\n\n')
377                 self._updateButtonStates()
378
379                 self._printerConnection.addCallback(self._doPrinterConnectionUpdate)
380
381                 if self._printerConnection.hasActiveConnection() and not self._printerConnection.isActiveConnectionOpen():
382                         self._printerConnection.openActiveConnection()
383                 preventComputerFromSleeping(True)
384
385         def OnPowerWarningChange(self, e):
386                 type = self.powerManagement.get_providing_power_source_type()
387                 if type == power.POWER_TYPE_AC and self.powerWarningText.IsShown():
388                         self.powerWarningText.Hide()
389                         self.panel.Layout()
390                         self.Layout()
391                         self.Fit()
392                         self.Refresh()
393                 elif type != power.POWER_TYPE_AC and not self.powerWarningText.IsShown():
394                         self.powerWarningText.Show()
395                         self.panel.Layout()
396                         self.Layout()
397                         self.Fit()
398                         self.Refresh()
399
400         def OnClose(self, e):
401                 if self._printerConnection.hasActiveConnection():
402                         if self._printerConnection.isPrinting():
403                                 pass #TODO: Give warning that the close will kill the print.
404                         self._printerConnection.closeActiveConnection()
405                 self._printerConnection.removeCallback(self._doPrinterConnectionUpdate)
406                 #TODO: When multiple printer windows are open, closing one will enable sleeping again.
407                 preventComputerFromSleeping(False)
408                 self.Destroy()
409
410         def OnConnect(self, e):
411                 self._printerConnection.openActiveConnection()
412
413         def OnLoad(self, e):
414                 pass
415
416         def OnPrint(self, e):
417                 self._printerConnection.startPrint()
418
419         def OnCancel(self, e):
420                 self._printerConnection.cancelPrint()
421
422         def OnPause(self, e):
423                 self._printerConnection.pause(not self._printerConnection.isPaused())
424
425         def OnErrorLog(self, e):
426                 LogWindow(self._printerConnection.getErrorLog())
427
428         def _doPrinterConnectionUpdate(self, connection, extraInfo = None):
429                 wx.CallAfter(self.__doPrinterConnectionUpdate, connection, extraInfo)
430                 #temp = [connection.getTemperature(0)]
431                 #self.temperatureGraph.addPoint(temp, [0], connection.getBedTemperature(), 0)
432
433         def __doPrinterConnectionUpdate(self, connection, extraInfo):
434                 t = time.time()
435                 if self._lastUpdateTime + 0.5 > t and extraInfo is None:
436                         return
437                 self._lastUpdateTime = t
438
439                 if extraInfo is not None:
440                         self._addTermLog('< %s\n' % (extraInfo))
441
442                 self._updateButtonStates()
443                 if connection.isPrinting():
444                         self.progress.SetValue(connection.getPrintProgress() * 1000)
445                 else:
446                         self.progress.SetValue(0)
447                 info = connection.getStatusString()
448                 info += '\n'
449                 if self._printerConnection.getTemperature(0) is not None:
450                         info += 'Temperature: %d' % (self._printerConnection.getTemperature(0))
451                 if self._printerConnection.getBedTemperature() > 0:
452                         info += ' Bed: %d' % (self._printerConnection.getBedTemperature())
453                 info += '\n\n'
454                 self.statsText.SetLabel(info)
455
456         def _updateButtonStates(self):
457                 self.connectButton.Show(self._printerConnection.hasActiveConnection())
458                 self.connectButton.Enable(not self._printerConnection.isActiveConnectionOpen() and not self._printerConnection.isActiveConnectionOpening())
459                 self.pauseButton.Show(self._printerConnection.hasPause())
460                 if not self._printerConnection.hasActiveConnection() or self._printerConnection.isActiveConnectionOpen():
461                         self.printButton.Enable(not self._printerConnection.isPrinting())
462                         self.pauseButton.Enable(self._printerConnection.isPrinting())
463                         self.cancelButton.Enable(self._printerConnection.isPrinting())
464                 else:
465                         self.printButton.Enable(False)
466                         self.pauseButton.Enable(False)
467                         self.cancelButton.Enable(False)
468                 self.errorLogButton.Show(self._printerConnection.isInErrorState())
469
470 class TemperatureGraph(wx.Panel):
471         def __init__(self, parent):
472                 super(TemperatureGraph, self).__init__(parent)
473
474                 self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
475                 self.Bind(wx.EVT_SIZE, self.OnSize)
476                 self.Bind(wx.EVT_PAINT, self.OnDraw)
477
478                 self._lastDraw = time.time() - 1.0
479                 self._points = []
480                 self._backBuffer = None
481                 self.addPoint([0]*16, [0]*16, 0, 0)
482
483         def OnEraseBackground(self, e):
484                 pass
485
486         def OnSize(self, e):
487                 if self._backBuffer is None or self.GetSize() != self._backBuffer.GetSize():
488                         self._backBuffer = wx.EmptyBitmap(*self.GetSizeTuple())
489                         self.UpdateDrawing(True)
490
491         def OnDraw(self, e):
492                 dc = wx.BufferedPaintDC(self, self._backBuffer)
493
494         def UpdateDrawing(self, force=False):
495                 now = time.time()
496                 if (not force and now - self._lastDraw < 1.0) or self._backBuffer is None:
497                         return
498                 self._lastDraw = now
499                 dc = wx.MemoryDC()
500                 dc.SelectObject(self._backBuffer)
501                 dc.Clear()
502                 dc.SetFont(wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT))
503                 w, h = self.GetSizeTuple()
504                 bgLinePen = wx.Pen('#A0A0A0')
505                 tempPen = wx.Pen('#FF4040')
506                 tempSPPen = wx.Pen('#FFA0A0')
507                 tempPenBG = wx.Pen('#FFD0D0')
508                 bedTempPen = wx.Pen('#4040FF')
509                 bedTempSPPen = wx.Pen('#A0A0FF')
510                 bedTempPenBG = wx.Pen('#D0D0FF')
511
512                 #Draw the background up to the current temperatures.
513                 x0 = 0
514                 t0 = []
515                 bt0 = 0
516                 tSP0 = 0
517                 btSP0 = 0
518                 for temp, tempSP, bedTemp, bedTempSP, t in self._points:
519                         x1 = int(w - (now - t))
520                         for x in xrange(x0, x1 + 1):
521                                 for n in xrange(0, min(len(t0), len(temp))):
522                                         t = float(x - x0) / float(x1 - x0 + 1) * (temp[n] - t0[n]) + t0[n]
523                                         dc.SetPen(tempPenBG)
524                                         dc.DrawLine(x, h, x, h - (t * h / 350))
525                                 bt = float(x - x0) / float(x1 - x0 + 1) * (bedTemp - bt0) + bt0
526                                 dc.SetPen(bedTempPenBG)
527                                 dc.DrawLine(x, h, x, h - (bt * h / 350))
528                         t0 = temp
529                         bt0 = bedTemp
530                         tSP0 = tempSP
531                         btSP0 = bedTempSP
532                         x0 = x1 + 1
533
534                 #Draw the grid
535                 for x in xrange(w, 0, -30):
536                         dc.SetPen(bgLinePen)
537                         dc.DrawLine(x, 0, x, h)
538                 tmpNr = 0
539                 for y in xrange(h - 1, 0, -h * 50 / 350):
540                         dc.SetPen(bgLinePen)
541                         dc.DrawLine(0, y, w, y)
542                         dc.DrawText(str(tmpNr), 0, y - dc.GetFont().GetPixelSize().GetHeight())
543                         tmpNr += 50
544                 dc.DrawLine(0, 0, w, 0)
545                 dc.DrawLine(0, 0, 0, h)
546
547                 #Draw the main lines
548                 x0 = 0
549                 t0 = []
550                 bt0 = 0
551                 tSP0 = []
552                 btSP0 = 0
553                 for temp, tempSP, bedTemp, bedTempSP, t in self._points:
554                         x1 = int(w - (now - t))
555                         for x in xrange(x0, x1 + 1):
556                                 for n in xrange(0, min(len(t0), len(temp))):
557                                         t = float(x - x0) / float(x1 - x0 + 1) * (temp[n] - t0[n]) + t0[n]
558                                         tSP = float(x - x0) / float(x1 - x0 + 1) * (tempSP[n] - tSP0[n]) + tSP0[n]
559                                         dc.SetPen(tempSPPen)
560                                         dc.DrawPoint(x, h - (tSP * h / 350))
561                                         dc.SetPen(tempPen)
562                                         dc.DrawPoint(x, h - (t * h / 350))
563                                 bt = float(x - x0) / float(x1 - x0 + 1) * (bedTemp - bt0) + bt0
564                                 btSP = float(x - x0) / float(x1 - x0 + 1) * (bedTempSP - btSP0) + btSP0
565                                 dc.SetPen(bedTempSPPen)
566                                 dc.DrawPoint(x, h - (btSP * h / 350))
567                                 dc.SetPen(bedTempPen)
568                                 dc.DrawPoint(x, h - (bt * h / 350))
569                         t0 = temp
570                         bt0 = bedTemp
571                         tSP0 = tempSP
572                         btSP0 = bedTempSP
573                         x0 = x1 + 1
574
575                 del dc
576                 self.Refresh(eraseBackground=False)
577                 self.Update()
578
579                 if len(self._points) > 0 and (time.time() - self._points[0][4]) > w + 20:
580                         self._points.pop(0)
581
582         def addPoint(self, temp, tempSP, bedTemp, bedTempSP):
583                 if len(self._points) > 0 and time.time() - self._points[-1][4] < 0.5:
584                         return
585                 for n in xrange(0, len(temp)):
586                         if temp[n] is None:
587                                 temp[n] = 0
588                 for n in xrange(0, len(tempSP)):
589                         if tempSP[n] is None:
590                                 tempSP[n] = 0
591                 if bedTemp is None:
592                         bedTemp = 0
593                 if bedTempSP is None:
594                         bedTempSP = 0
595                 self._points.append((temp[:], tempSP[:], bedTemp, bedTempSP, time.time()))
596                 wx.CallAfter(self.UpdateDrawing)
597
598
599 class LogWindow(wx.Frame):
600         def __init__(self, logText):
601                 super(LogWindow, self).__init__(None, title="Error log")
602                 self.textBox = wx.TextCtrl(self, -1, logText, style=wx.TE_MULTILINE | wx.TE_DONTWRAP | wx.TE_READONLY)
603                 self.SetSize((500, 400))
604                 self.Show(True)