def testGetProvidingPowerSource(self):
     type = power.PowerManagement().get_providing_power_source_type()
     self.assertIsNotNone(type)
     self.assertIsInstance(type, int)
     self.assertIn(type, [
         power.POWER_TYPE_AC, power.POWER_TYPE_BATTERY, power.POWER_TYPE_UPS
     ])
Beispiel #2
0
    def remaining(self):
        estimate = 0.0
        power_now = 0.0
        try:
            estimate = power.PowerManagement().get_time_remaining_estimate()
            # do not show remaining if on AC
            if estimate == power.common.TIME_REMAINING_UNLIMITED:
                return None
            elif estimate == power.common.TIME_REMAINING_UNKNOWN:
                return ""
            else:
                for path in self._batteries:
                    try:
                        with open("{}/power_now".format(path)) as o:
                            power_now += int(o.read())
                    except IOError:
                        return "n/a"
                    except Exception:
                        errors += 1

                estimate = float(self.energy_now / power_now)
        except Exception:
            return ""
        return bumblebee.util.durationfmt(
            estimate * 60, shorten=True, suffix=True)  # estimate is in minutes
Beispiel #3
0
def get_power_info():
    ans = power.PowerManagement().get_providing_power_source_type()
    if not ans:
        print ("Plugged into wall socket")
    else:
        print ("On battery")
    return None
Beispiel #4
0
 def testGetRemainingEstimate(self):
     estimate = power.PowerManagement().get_time_remaining_estimate()
     self.assertIsNotNone(estimate)
     self.assertIsInstance(estimate, float)
     self.assertTrue(estimate == power.TIME_REMAINING_UNKNOWN
                     or estimate == power.TIME_REMAINING_UNLIMITED
                     or estimate >= 0.0)
 def testGetLowBatteryWarningLevel(self):
     level = power.PowerManagement().get_low_battery_warning_level()
     self.assertIsNotNone(level)
     self.assertIsInstance(level, int)
     self.assertIn(level, [
         power.LOW_BATTERY_WARNING_NONE, power.LOW_BATTERY_WARNING_EARLY,
         power.LOW_BATTERY_WARNING_FINAL
     ])
def take_action(music_file, volume, horaBegin, horaEnd,
                atual):  #notificacao da percentagem da bateria

    command_above = "notify-send 'Bateria acima de 60'%"
    command_below = "notify-send 'Bateria abaixo de 60%'"
    command_Corrente = "notify-send 'Em modo Corrente'"
    command_bat = "notify-send 'Em modo Bateria'"
    times = 0

    ans = power.PowerManagement().get_providing_power_source_type()
    if not ans:
        #Modo Corrente
        subprocess.Popen(["/bin/bash", "-c", command_Corrente])
        charge = int(read_status())
        times = 0
        time.sleep(30)
        take_action(music_file, volume, horaBegin, horaEnd, atual)

    else:
        #Modo Bateria
        subprocess.Popen(["/bin/bash", "-c", command_bat])
        charge = int(read_status())
        time.sleep(5)

        print(atual < horaEnd or atual == horaBegin)

        if ((atual < horaEnd or atual == horaBegin)):

            if charge > 60:
                print "> 60"
                subprocess.Popen(["/bin/bash", "-c", command_above])
                time.sleep(10)
                take_action(music_file, volume, horaBegin, horaEnd, atual)

                if times == 0:
                    subprocess.Popen(["/bin/bash", "-c", command_below])
                    times = 1
                else:
                    times = 0
                    time.sleep(5)
                    take_action(music_file, volume, horaBegin, horaEnd, atual)

            elif charge < 60:
                print "< 60"
                play_music(music_file, volume)
                time.sleep(10)
                take_action(music_file, volume, horaBegin, horaEnd, atual)

                if times == 0:
                    subprocess.Popen(["/bin/bash", "-c", command_below])
                    times = 1
                else:
                    times = 0
                    time.sleep(10)
                    take_action(music_file, volume, horaBegin, horaEnd, atual)
        else:
            time.sleep(15)
            take_action(music_file, volume, horaBegin, horaEnd, atual)
Beispiel #7
0
 def remaining(self):
     try:
         estimate = power.PowerManagement().get_time_remaining_estimate()
         # do not show remaining if on AC
         if estimate == power.common.TIME_REMAINING_UNLIMITED:
             return None
         return estimate * 60  # return value in seconds
     except Exception as e:
         return -1
     return -1
Beispiel #8
0
def check_for_charger():
    try:
        ans = power.PowerManagement().get_providing_power_source_type()
        global charger_plugged_in
        if not ans:
            charger_plugged_in = True
        else:
            charger_plugged_in = False
    except:
        pass
Beispiel #9
0
 def remaining(self):
     estimate = 0.0
     try:
         estimate = power.PowerManagement().get_time_remaining_estimate()
         # do not show remaining if on AC
         if estimate == power.common.TIME_REMAINING_UNLIMITED:
             return None
         if estimate == power.common.TIME_REMAINING_UNKNOWN:
             return ""
     except Exception:
         return ""
     return bumblebee.util.durationfmt(estimate*60, shorten=True, suffix=True) # estimate is in minutes
Beispiel #10
0
def set_autofreq():
    print("\n" + "-" * 28 + " CPU frequency scaling " + "-" * 28 + "\n")

    # get battery state
    bat_state = power.PowerManagement().get_providing_power_source_type()

    # determine which governor should be used
    if bat_state == power.POWER_TYPE_AC:
        print("Battery is: charging")
        set_performance()
    elif bat_state == power.POWER_TYPE_BATTERY:
        print("Battery is: discharging")
        set_powersave()
    else:
        print("Couldn't determine battery status. Please report this issue.")
Beispiel #11
0
    def __init__(self, plugin, bar):
        UI.PopupWindow.__init__(self, bar, plugin)
        self.power = power.PowerManagement()
        self.firstAttempt = True

        box = gtk.HBox(False, 4)
        box.set_border_width(2)
        self.add(box)
        self.label = gtk.Label()
        self.label.set_use_markup(True)
        self.label.set_markup('no battery ..')
        box.pack_start(self.label)
        box.show_all()

        gobject.timeout_add(4000, self.initial_update_status)
        gobject.timeout_add(60000, self.update_status)
Beispiel #12
0
	def __init__(self, parent, printerConnection):
		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()))
		self._printerConnection = printerConnection
		self._lastUpdateTime = 0

		self.SetSizer(wx.BoxSizer())
		self.panel = wx.Panel(self)
		self.GetSizer().Add(self.panel, 1, flag=wx.EXPAND)
		self.sizer = wx.GridBagSizer(2, 2)
		self.panel.SetSizer(self.sizer)

		self.powerWarningText = wx.StaticText(parent=self.panel,
			id=-1,
			label=_("Your computer is running on battery power.\nConnect your computer to AC power or your print might not finish."),
			style=wx.ALIGN_CENTER)
		self.powerWarningText.SetBackgroundColour('red')
		self.powerWarningText.SetForegroundColour('white')
		self.powerManagement = power.PowerManagement()
		self.powerWarningTimer = wx.Timer(self)
		self.Bind(wx.EVT_TIMER, self.OnPowerWarningChange, self.powerWarningTimer)
		self.OnPowerWarningChange(None)
		self.powerWarningTimer.Start(10000)


		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"))


		self.connectButton = wx.Button(self.panel, -1, _("Connect"))
		#self.loadButton = wx.Button(self.panel, -1, 'Load')
		self.printButton = wx.Button(self.panel, -1, _("Print"))
		self.pauseButton = wx.Button(self.panel, -1, _("Pause"))
		self.cancelButton = wx.Button(self.panel, -1, _("Cancel print"))
		self.errorLogButton = wx.Button(self.panel, -1, _("Error log"))
		self.progress = wx.Gauge(self.panel, -1, range=1000)

		self.sizer.Add(self.powerWarningText, pos=(0, 0), span=(1, 5), flag=wx.EXPAND|wx.BOTTOM, border=5)
		self.sizer.Add(self.statsText, pos=(1, 0), span=(1, 5), flag=wx.LEFT, border=5)
		self.sizer.Add(self.connectButton, pos=(2, 0))
		#self.sizer.Add(self.loadButton, pos=(2,1))
		self.sizer.Add(self.printButton, pos=(2, 1))
		self.sizer.Add(self.pauseButton, pos=(2, 2))
		self.sizer.Add(self.cancelButton, pos=(2, 3))
		self.sizer.Add(self.errorLogButton, pos=(2, 4))
		self.sizer.Add(self.progress, pos=(3, 0), span=(1, 5), flag=wx.EXPAND)

		self.Bind(wx.EVT_CLOSE, self.OnClose)
		self.connectButton.Bind(wx.EVT_BUTTON, self.OnConnect)
		#self.loadButton.Bind(wx.EVT_BUTTON, self.OnLoad)
		self.printButton.Bind(wx.EVT_BUTTON, self.OnPrint)
		self.pauseButton.Bind(wx.EVT_BUTTON, self.OnPause)
		self.cancelButton.Bind(wx.EVT_BUTTON, self.OnCancel)
		self.errorLogButton.Bind(wx.EVT_BUTTON, self.OnErrorLog)

		self.Layout()
		self.Fit()
		self.Centre()

		self.progress.SetMinSize(self.progress.GetSize())

		self.statsText.SetLabel('\n\n\n\n\n\n')

		self._updateButtonStates()

		self._printerConnection.addCallback(self._doPrinterConnectionUpdate)

		if self._printerConnection.hasActiveConnection() and not self._printerConnection.isActiveConnectionOpen():
			self._printerConnection.openActiveConnection()
		preventComputerFromSleeping(True)
Beispiel #13
0
 def testGetRemainingEstimate(self):
     estimate = power.PowerManagement().get_time_remaining_estimate()
     self.assertIsNotNone(estimate)
     self.assertIsInstance(estimate, float)
     self.assertTrue(estimate == -1.0 or estimate == -2.0 or estimate >= 0.0)
def power_source_type():
    power_type = power.PowerManagement().get_providing_power_source_type()
    return POWER_TYPE_MAP[power_type]
Beispiel #15
0
	def __init__(self, printerConnection):
		super(printWindow, self).__init__(None, -1, title=_("Printing"))
		self._printerConnection = printerConnection
		self.lastUpdateTime = 0

		self.SetSizer(wx.BoxSizer())
		self.panel = wx.Panel(self)
		self.GetSizer().Add(self.panel, 1, flag=wx.EXPAND)
		self.sizer = wx.GridBagSizer(2, 2)
		self.panel.SetSizer(self.sizer)

		sb = wx.StaticBox(self.panel, label=_("Statistics"))
		boxsizer = wx.StaticBoxSizer(sb, wx.VERTICAL)

		self.powerWarningText = wx.StaticText(parent=self.panel,
			id=-1,
			label=_("Your computer is running on battery power.\nConnect your computer to AC power or your print might not finish."),
			style=wx.ALIGN_CENTER)
		self.powerWarningText.SetBackgroundColour('red')
		self.powerWarningText.SetForegroundColour('white')
		boxsizer.AddF(self.powerWarningText, flags=wx.SizerFlags().Expand().Border(wx.BOTTOM, 10))
		self.powerManagement = power.PowerManagement()
		self.powerWarningTimer = wx.Timer(self)
		self.Bind(wx.EVT_TIMER, self.OnPowerWarningChange, self.powerWarningTimer)
		self.OnPowerWarningChange(None)
		self.powerWarningTimer.Start(10000)

		self.statsText = wx.StaticText(self.panel, -1, _("Filament: ####.##m #.##g\nEstimated print time: #####:##\nMachine state:\nDetecting baudrateXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"))
		boxsizer.Add(self.statsText, flag=wx.LEFT, border=5)

		self.sizer.Add(boxsizer, pos=(0, 0), span=(7, 1), flag=wx.EXPAND)

		self.connectButton = wx.Button(self.panel, -1, _("Connect"))
		#self.loadButton = wx.Button(self.panel, -1, 'Load')
		self.printButton = wx.Button(self.panel, -1, _("Print"))
		self.pauseButton = wx.Button(self.panel, -1, _("Pause"))
		self.cancelButton = wx.Button(self.panel, -1, _("Cancel print"))
		self.errorLogButton = wx.Button(self.panel, -1, _("Error log"))
		self.progress = wx.Gauge(self.panel, -1, range=1000)

		self.sizer.Add(self.connectButton, pos=(1, 1), flag=wx.EXPAND)
		#self.sizer.Add(self.loadButton, pos=(1,1), flag=wx.EXPAND)
		self.sizer.Add(self.printButton, pos=(2, 1), flag=wx.EXPAND)
		self.sizer.Add(self.pauseButton, pos=(3, 1), flag=wx.EXPAND)
		self.sizer.Add(self.cancelButton, pos=(4, 1), flag=wx.EXPAND)
		self.sizer.Add(self.errorLogButton, pos=(5, 1), flag=wx.EXPAND)
		self.sizer.Add(self.progress, pos=(7, 0), span=(1, 7), flag=wx.EXPAND)

		nb = wx.Notebook(self.panel)
		self.tabs = nb
		self.sizer.Add(nb, pos=(0, 2), span=(7, 4), flag=wx.EXPAND)

		self.temperaturePanel = wx.Panel(nb)
		sizer = wx.GridBagSizer(2, 2)
		self.temperaturePanel.SetSizer(sizer)

		self.temperatureSelect = wx.SpinCtrl(self.temperaturePanel, -1, '0', size=(21 * 3, 21), style=wx.SP_ARROW_KEYS)
		self.temperatureSelect.SetRange(0, 400)
		self.temperatureHeatUp = wx.Button(self.temperaturePanel, -1, str(int(profile.getProfileSettingFloat('print_temperature'))) + 'C')
		self.bedTemperatureLabel = wx.StaticText(self.temperaturePanel, -1, _("BedTemp:"))
		self.bedTemperatureSelect = wx.SpinCtrl(self.temperaturePanel, -1, '0', size=(21 * 3, 21), style=wx.SP_ARROW_KEYS)
		self.bedTemperatureSelect.SetRange(0, 400)
		self.bedTemperatureLabel.Show(False)
		self.bedTemperatureSelect.Show(False)

		self.temperatureGraph = TemperatureGraph(self.temperaturePanel)

		sizer.Add(wx.StaticText(self.temperaturePanel, -1, _("Temp:")), pos=(0, 0))
		sizer.Add(self.temperatureSelect, pos=(0, 1))
		sizer.Add(self.temperatureHeatUp, pos=(0, 2))
		sizer.Add(self.bedTemperatureLabel, pos=(1, 0))
		sizer.Add(self.bedTemperatureSelect, pos=(1, 1))
		sizer.Add(self.temperatureGraph, pos=(2, 0), span=(1, 3), flag=wx.EXPAND)
		sizer.AddGrowableRow(2)
		sizer.AddGrowableCol(2)

		nb.AddPage(self.temperaturePanel, 'Temp')

		self.directControlPanel = wx.Panel(nb)

		sizer = wx.GridBagSizer(2, 2)
		self.directControlPanel.SetSizer(sizer)
		sizer.Add(PrintCommandButton(self, ['G91', 'G1 Y100 F6000', 'G90'], 'print-move-y100.png'), pos=(0, 3))
		sizer.Add(PrintCommandButton(self, ['G91', 'G1 Y10 F6000', 'G90'], 'print-move-y10.png'), pos=(1, 3))
		sizer.Add(PrintCommandButton(self, ['G91', 'G1 Y1 F6000', 'G90'], 'print-move-y1.png'), pos=(2, 3))

		sizer.Add(PrintCommandButton(self, ['G91', 'G1 Y-1 F6000', 'G90'], 'print-move-y-1.png'), pos=(4, 3))
		sizer.Add(PrintCommandButton(self, ['G91', 'G1 Y-10 F6000', 'G90'], 'print-move-y-10.png'), pos=(5, 3))
		sizer.Add(PrintCommandButton(self, ['G91', 'G1 Y-100 F6000', 'G90'], 'print-move-y-100.png'), pos=(6, 3))

		sizer.Add(PrintCommandButton(self, ['G91', 'G1 X-100 F6000', 'G90'], 'print-move-x-100.png'), pos=(3, 0))
		sizer.Add(PrintCommandButton(self, ['G91', 'G1 X-10 F6000', 'G90'], 'print-move-x-10.png'), pos=(3, 1))
		sizer.Add(PrintCommandButton(self, ['G91', 'G1 X-1 F6000', 'G90'], 'print-move-x-1.png'), pos=(3, 2))

		sizer.Add(PrintCommandButton(self, ['G28 X0 Y0'], 'print-move-home.png'), pos=(3, 3))

		sizer.Add(PrintCommandButton(self, ['G91', 'G1 X1 F6000', 'G90'], 'print-move-x1.png'), pos=(3, 4))
		sizer.Add(PrintCommandButton(self, ['G91', 'G1 X10 F6000', 'G90'], 'print-move-x10.png'), pos=(3, 5))
		sizer.Add(PrintCommandButton(self, ['G91', 'G1 X100 F6000', 'G90'], 'print-move-x100.png'), pos=(3, 6))

		sizer.Add(PrintCommandButton(self, ['G91', 'G1 Z10 F200', 'G90'], 'print-move-z10.png'), pos=(0, 8))
		sizer.Add(PrintCommandButton(self, ['G91', 'G1 Z1 F200', 'G90'], 'print-move-z1.png'), pos=(1, 8))
		sizer.Add(PrintCommandButton(self, ['G91', 'G1 Z0.1 F200', 'G90'], 'print-move-z0.1.png'), pos=(2, 8))

		sizer.Add(PrintCommandButton(self, ['G28 Z0'], 'print-move-home.png'), pos=(3, 8))

		sizer.Add(PrintCommandButton(self, ['G91', 'G1 Z-0.1 F200', 'G90'], 'print-move-z-0.1.png'), pos=(4, 8))
		sizer.Add(PrintCommandButton(self, ['G91', 'G1 Z-1 F200', 'G90'], 'print-move-z-1.png'), pos=(5, 8))
		sizer.Add(PrintCommandButton(self, ['G91', 'G1 Z-10 F200', 'G90'], 'print-move-z-10.png'), pos=(6, 8))

		sizer.Add(PrintCommandButton(self, ['G92 E0', 'G1 E2 F120'], 'extrude.png', size=(60, 20)), pos=(1, 10), span=(1, 3), flag=wx.EXPAND)
		sizer.Add(PrintCommandButton(self, ['G92 E0', 'G1 E-2 F120'], 'retract.png', size=(60, 20)), pos=(2, 10), span=(1, 3), flag=wx.EXPAND)

		nb.AddPage(self.directControlPanel, _("Jog"))

		self.termPanel = wx.Panel(nb)
		sizer = wx.GridBagSizer(2, 2)
		self.termPanel.SetSizer(sizer)

		f = wx.Font(8, wx.FONTFAMILY_MODERN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False)
		self.termLog = wx.TextCtrl(self.termPanel, style=wx.TE_MULTILINE | wx.TE_DONTWRAP)
		self.termLog.SetFont(f)
		self.termLog.SetEditable(0)
		self.termInput = wx.TextCtrl(self.termPanel, style=wx.TE_PROCESS_ENTER)
		self.termInput.SetFont(f)
		self._termHistory = []
		self._termHistoryIdx = 0

		sizer.Add(self.termLog, pos=(0, 0), flag=wx.EXPAND)
		sizer.Add(self.termInput, pos=(1, 0), flag=wx.EXPAND)
		sizer.AddGrowableCol(0)
		sizer.AddGrowableRow(0)

		nb.AddPage(self.termPanel, _("Term"))

		self.sizer.AddGrowableRow(6)
		self.sizer.AddGrowableCol(3)

		self.Bind(wx.EVT_CLOSE, self.OnClose)
		self.connectButton.Bind(wx.EVT_BUTTON, self.OnConnect)
		#self.loadButton.Bind(wx.EVT_BUTTON, self.OnLoad)
		self.printButton.Bind(wx.EVT_BUTTON, self.OnPrint)
		self.pauseButton.Bind(wx.EVT_BUTTON, self.OnPause)
		self.cancelButton.Bind(wx.EVT_BUTTON, self.OnCancel)
		self.errorLogButton.Bind(wx.EVT_BUTTON, self.OnErrorLog)

		self.Bind(wx.EVT_BUTTON, lambda e: (self.temperatureSelect.SetValue(int(profile.getProfileSettingFloat('print_temperature'))), self.machineCom.sendCommand("M104 S%d" % (int(profile.getProfileSettingFloat('print_temperature'))))), self.temperatureHeatUp)
		self.Bind(wx.EVT_SPINCTRL, self.OnTempChange, self.temperatureSelect)
		self.Bind(wx.EVT_SPINCTRL, self.OnBedTempChange, self.bedTemperatureSelect)

		self.Bind(wx.EVT_TEXT_ENTER, self.OnTermEnterLine, self.termInput)
		self.termInput.Bind(wx.EVT_CHAR, self.OnTermKey)

		self.Layout()
		self.Fit()
		self.Centre()

		self.statsText.SetMinSize(self.statsText.GetSize())
		self.statsText.SetLabel(self._printerConnection.getStatusString())

		self.UpdateButtonStates()

		if webcam.hasWebcamSupport():
			#Need to call the camera class on the GUI thread, or else it won't work. Shame as it hangs the GUI for about 2 seconds.
			wx.CallAfter(self._webcamCheck)

		self._printerConnection.addCallback(self._doPrinterConnectionUpdate)
Beispiel #16
0
        self.assertIsNotNone(estimate)
        self.assertIsInstance(estimate, float)
        self.assertTrue(estimate == -1.0 or estimate == -2.0 or estimate >= 0.0)

    def testGetProvidingPowerSource(self):
        type = power.PowerManagement().get_providing_power_source_type()
        self.assertIsNotNone(type)
        self.assertIsInstance(type, int)
        self.assertIn(type, [power.POWER_TYPE_AC, power.POWER_TYPE_BATTERY, power.POWER_TYPE_UPS])


class TestObserver(power.PowerManagementObserver):
    def on_power_sources_change(self, power_management):
        print "on_power_sources_change"

    def on_time_remaining_change(self, power_management):
        print "on_time_remaining_change"


if __name__ == "__main__":
    o = TestObserver()
    p = power.PowerManagement()
    p.add_observer(o)
    try:
        print "Power management observer is registered"
        import time
        while True:
            time.sleep(1)
    finally:
        p.remove_observer(o)
def power_remaining_estimate():
    estimate = power.PowerManagement().get_time_remaining_estimate()
    if estimate < 0:
        return estimate
    # API returns minutes, Prometheus prefers seconds as the standard.
    return estimate * 60
	def __init__(self, parent, printerConnection):
		super(printWindowAdvanced, 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()))
		self._printerConnection = printerConnection
		self._lastUpdateTime = time.time()
		self._printDuration = 0
		self._lastDurationTime = None
		self._isPrinting = False

		self.SetSizer(wx.BoxSizer(wx.VERTICAL))
		self.toppanel = wx.Panel(self)
		self.topsizer = wx.GridBagSizer(2, 2)
		self.toppanel.SetSizer(self.topsizer)
		self.toppanel.SetBackgroundColour(wx.WHITE)
		self.topsizer.SetEmptyCellSize((125, 1))
		self.panel = wx.Panel(self)
		self.sizer = wx.GridBagSizer(2, 2)
		self.sizer.SetEmptyCellSize((125, 1))
		self.panel.SetSizer(self.sizer)
		self.panel.SetBackgroundColour(wx.WHITE)
		self.GetSizer().Add(self.toppanel, 0, flag=wx.EXPAND)
		self.GetSizer().Add(self.panel, 1, flag=wx.EXPAND)

		self._fullscreenTemperature = None
		self._termHistory = []
		self._termHistoryIdx = 0

		self._mapImage = wx.Image(resources.getPathForImage('print-window-map.png'))
		self._colorCommandMap = {}

		# Move X
		self._addMovementCommand(0, 0, 255, self._moveX, 100)
		self._addMovementCommand(0, 0, 240, self._moveX, 10)
		self._addMovementCommand(0, 0, 220, self._moveX, 1)
		self._addMovementCommand(0, 0, 200, self._moveX, 0.1)
		self._addMovementCommand(0, 0, 180, self._moveX, -0.1)
		self._addMovementCommand(0, 0, 160, self._moveX, -1)
		self._addMovementCommand(0, 0, 140, self._moveX, -10)
		self._addMovementCommand(0, 0, 120, self._moveX, -100)

		# Move Y
		self._addMovementCommand(0, 255, 0, self._moveY, -100)
		self._addMovementCommand(0, 240, 0, self._moveY, -10)
		self._addMovementCommand(0, 220, 0, self._moveY, -1)
		self._addMovementCommand(0, 200, 0, self._moveY, -0.1)
		self._addMovementCommand(0, 180, 0, self._moveY, 0.1)
		self._addMovementCommand(0, 160, 0, self._moveY, 1)
		self._addMovementCommand(0, 140, 0, self._moveY, 10)
		self._addMovementCommand(0, 120, 0, self._moveY, 100)

		# Move Z
		self._addMovementCommand(255, 0, 0, self._moveZ, 10)
		self._addMovementCommand(220, 0, 0, self._moveZ, 1)
		self._addMovementCommand(200, 0, 0, self._moveZ, 0.1)
		self._addMovementCommand(180, 0, 0, self._moveZ, -0.1)
		self._addMovementCommand(160, 0, 0, self._moveZ, -1)
		self._addMovementCommand(140, 0, 0, self._moveZ, -10)

		# Extrude/Retract
		self._addMovementCommand(255, 80, 0, self._moveE, 10)
		self._addMovementCommand(255, 180, 0, self._moveE, -10)

		# Home
		self._addMovementCommand(255, 255, 0, self._homeXYZ, None)
		self._addMovementCommand(240, 255, 0, self._homeXYZ, "X")
		self._addMovementCommand(220, 255, 0, self._homeXYZ, "Y")
		self._addMovementCommand(200, 255, 0, self._homeXYZ, "Z")

		self.powerWarningText = wx.StaticText(parent=self.toppanel,
			id=-1,
			label=_("Your computer is running on battery power.\nConnect your computer to AC power or your print might not finish."),
			style=wx.ALIGN_CENTER)
		self.powerWarningText.SetBackgroundColour('red')
		self.powerWarningText.SetForegroundColour('white')
		if power:
			self.powerManagement = power.PowerManagement()
		else:
			self.powerManagement = None
		self.powerWarningTimer = wx.Timer(self)
		self.Bind(wx.EVT_TIMER, self.OnPowerWarningChange, self.powerWarningTimer)
		self.OnPowerWarningChange(None)
		self.powerWarningTimer.Start(10000)

		self.pauseTimer = wx.Timer(self)
		self.Bind(wx.EVT_TIMER, self.OnPauseTimer, self.pauseTimer)

		self.connectButton = wx.Button(self.toppanel, -1, _("Connect"), size=(125, 30))
		self.printButton = wx.Button(self.toppanel, -1, _("Print"), size=(125, 30))
		self.cancelButton = wx.Button(self.toppanel, -1, _("Cancel"), size=(125, 30))
		self.errorLogButton = wx.Button(self.toppanel, -1, _("Error log"), size=(125, 30))
		self.motorsOffButton = wx.Button(self.toppanel, -1, _("Motors off"), size=(125, 30))
		self.movementBitmap = wx.StaticBitmap(self.panel, -1, wx.BitmapFromImage(wx.Image(
				resources.getPathForImage('print-window.png'))), (0, 0))
		self.temperatureBitmap = wx.StaticBitmap(self.panel, -1, wx.BitmapFromImage(wx.Image(
				resources.getPathForImage('print-window-temperature.png'))), (0, 0))
		self.temperatureField = TemperatureField(self.panel, self._setHotendTemperature)
		self.temperatureBedBitmap = wx.StaticBitmap(self.panel, -1, wx.BitmapFromImage(wx.Image(
				resources.getPathForImage('print-window-temperature-bed.png'))), (0, 0))
		self.temperatureBedField = TemperatureField(self.panel, self._setBedTemperature)
		self.temperatureGraph = TemperatureGraph(self.panel)
		self.temperatureGraph.SetMinSize((250, 100))
		self.progress = wx.Gauge(self.panel, -1, range=1000)

		f = wx.Font(8, wx.FONTFAMILY_MODERN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False)
		self._termLog = wx.TextCtrl(self.panel, style=wx.TE_MULTILINE)
		self._termLog.SetFont(f)
		self._termLog.SetEditable(0)
		self._termLog.SetMinSize((385, -1))
		self._termInput = wx.TextCtrl(self.panel, style=wx.TE_PROCESS_ENTER)
		self._termInput.SetFont(f)

		self.Bind(wx.EVT_TEXT_ENTER, self.OnTermEnterLine, self._termInput)
		self._termInput.Bind(wx.EVT_CHAR, self.OnTermKey)

		self.topsizer.Add(self.powerWarningText, pos=(0, 0), span=(1, 6), flag=wx.EXPAND|wx.BOTTOM, border=5)
		self.topsizer.Add(self.connectButton, pos=(1, 0), flag=wx.LEFT, border=2)
		self.topsizer.Add(self.printButton, pos=(1, 1), flag=wx.LEFT, border=2)
		self.topsizer.Add(self.cancelButton, pos=(1, 2), flag=wx.LEFT, border=2)
		self.topsizer.Add(self.errorLogButton, pos=(1, 4), flag=wx.LEFT, border=2)
		self.topsizer.Add(self.motorsOffButton, pos=(1, 5), flag=wx.LEFT|wx.RIGHT, border=2)
		self.sizer.Add(self.movementBitmap, pos=(0, 0), span=(2, 3))
		self.sizer.Add(self.temperatureGraph, pos=(2, 0), span=(4, 2), flag=wx.EXPAND)
		self.sizer.Add(self.temperatureBitmap, pos=(2, 2))
		self.sizer.Add(self.temperatureField, pos=(3, 2))
		self.sizer.Add(self.temperatureBedBitmap, pos=(4, 2))
		self.sizer.Add(self.temperatureBedField, pos=(5, 2))
		self.sizer.Add(self._termLog, pos=(0, 3), span=(5, 3), flag=wx.EXPAND|wx.RIGHT, border=5)
		self.sizer.Add(self._termInput, pos=(5, 3), span=(1, 3), flag=wx.EXPAND|wx.RIGHT, border=5)
		self.sizer.Add(self.progress, pos=(7, 0), span=(1, 6), flag=wx.EXPAND|wx.BOTTOM)

		self.Bind(wx.EVT_SIZE, self.OnSize)
		self.Bind(wx.EVT_CLOSE, self.OnClose)
		self.movementBitmap.Bind(wx.EVT_LEFT_DOWN, self.OnMovementClick)
		self.temperatureGraph.Bind(wx.EVT_LEFT_UP, self.OnTemperatureClick)
		self.connectButton.Bind(wx.EVT_BUTTON, self.OnConnect)
		self.printButton.Bind(wx.EVT_BUTTON, self.OnPrint)
		self.cancelButton.Bind(wx.EVT_BUTTON, self.OnCancel)
		self.errorLogButton.Bind(wx.EVT_BUTTON, self.OnErrorLog)
		self.motorsOffButton.Bind(wx.EVT_BUTTON, self.OnMotorsOff)

		self.Layout()
		self.Fit()
		self.Refresh()
		self.progress.SetMinSize(self.progress.GetSize())
		self._updateButtonStates()

		self._printerConnection.addCallback(self._doPrinterConnectionUpdate)

		if self._printerConnection.hasActiveConnection() and \
		   not self._printerConnection.isActiveConnectionOpen():
			self._printerConnection.openActiveConnection()
def power_warning_level():
    level = power.PowerManagement().get_low_battery_warning_level()
    return POWER_WARNING_LEVEL_MAP[level]
Beispiel #20
0
    def __init__(self):
        super(printWindow, self).__init__(None, -1, title='Printing')
        self.machineCom = None
        self.gcode = None
        self.gcodeList = None
        self.sendList = []
        self.temp = None
        self.bedTemp = None
        self.bufferLineCount = 4
        self.sendCnt = 0
        self.feedrateRatioOuterWall = 1.0
        self.feedrateRatioInnerWall = 1.0
        self.feedrateRatioFill = 1.0
        self.feedrateRatioSupport = 1.0
        self.pause = False
        self.termHistory = []
        self.termHistoryIdx = 0

        self.cam = None
        if webcam.hasWebcamSupport():
            self.cam = webcam.webcam()
            if not self.cam.hasCamera():
                self.cam = None

        self.SetSizer(wx.BoxSizer())
        self.panel = wx.Panel(self)
        self.GetSizer().Add(self.panel, 1, flag=wx.EXPAND)
        self.sizer = wx.GridBagSizer(2, 2)
        self.panel.SetSizer(self.sizer)

        sb = wx.StaticBox(self.panel, label="Statistics")
        boxsizer = wx.StaticBoxSizer(sb, wx.VERTICAL)

        self.powerWarningText = wx.StaticText(
            parent=self.panel,
            id=-1,
            label=
            "Your computer is running on battery power.\nConnect your computer to AC power or your print might not finish.",
            style=wx.ALIGN_CENTER)
        self.powerWarningText.SetBackgroundColour('red')
        self.powerWarningText.SetForegroundColour('white')
        boxsizer.AddF(self.powerWarningText,
                      flags=wx.SizerFlags().Expand().Border(wx.BOTTOM, 10))
        self.powerManagement = power.PowerManagement()
        self.powerWarningTimer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.OnPowerWarningChange,
                  self.powerWarningTimer)
        self.OnPowerWarningChange(None)
        self.powerWarningTimer.Start(10000)

        self.statsText = wx.StaticText(
            self.panel, -1,
            "Filament: ####.##m #.##g\nEstimated print time: #####:##\nMachine state:\nDetecting baudrateXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
        )
        boxsizer.Add(self.statsText, flag=wx.LEFT, border=5)

        self.sizer.Add(boxsizer, pos=(0, 0), span=(7, 1), flag=wx.EXPAND)

        self.connectButton = wx.Button(self.panel, -1, 'Connect')
        #self.loadButton = wx.Button(self.panel, -1, 'Load')
        self.printButton = wx.Button(self.panel, -1, 'Print')
        self.pauseButton = wx.Button(self.panel, -1, 'Pause')
        self.cancelButton = wx.Button(self.panel, -1, 'Cancel print')
        self.machineLogButton = wx.Button(self.panel, -1, 'Error log')
        self.progress = wx.Gauge(self.panel, -1)

        self.sizer.Add(self.connectButton, pos=(1, 1), flag=wx.EXPAND)
        #self.sizer.Add(self.loadButton, pos=(1,1), flag=wx.EXPAND)
        self.sizer.Add(self.printButton, pos=(2, 1), flag=wx.EXPAND)
        self.sizer.Add(self.pauseButton, pos=(3, 1), flag=wx.EXPAND)
        self.sizer.Add(self.cancelButton, pos=(4, 1), flag=wx.EXPAND)
        self.sizer.Add(self.machineLogButton, pos=(5, 1), flag=wx.EXPAND)
        self.sizer.Add(self.progress, pos=(7, 0), span=(1, 7), flag=wx.EXPAND)

        nb = wx.Notebook(self.panel)
        self.sizer.Add(nb, pos=(0, 2), span=(7, 4), flag=wx.EXPAND)

        self.temperaturePanel = wx.Panel(nb)
        sizer = wx.GridBagSizer(2, 2)
        self.temperaturePanel.SetSizer(sizer)

        self.temperatureSelect = wx.SpinCtrl(self.temperaturePanel,
                                             -1,
                                             '0',
                                             size=(21 * 3, 21),
                                             style=wx.SP_ARROW_KEYS)
        self.temperatureSelect.SetRange(0, 400)
        self.bedTemperatureLabel = wx.StaticText(self.temperaturePanel, -1,
                                                 "BedTemp:")
        self.bedTemperatureSelect = wx.SpinCtrl(self.temperaturePanel,
                                                -1,
                                                '0',
                                                size=(21 * 3, 21),
                                                style=wx.SP_ARROW_KEYS)
        self.bedTemperatureSelect.SetRange(0, 400)
        self.bedTemperatureLabel.Show(False)
        self.bedTemperatureSelect.Show(False)

        self.temperatureGraph = temperatureGraph(self.temperaturePanel)

        sizer.Add(wx.StaticText(self.temperaturePanel, -1, "Temp:"),
                  pos=(0, 0))
        sizer.Add(self.temperatureSelect, pos=(0, 1))
        sizer.Add(self.bedTemperatureLabel, pos=(1, 0))
        sizer.Add(self.bedTemperatureSelect, pos=(1, 1))
        sizer.Add(self.temperatureGraph,
                  pos=(2, 0),
                  span=(1, 2),
                  flag=wx.EXPAND)
        sizer.AddGrowableRow(2)
        sizer.AddGrowableCol(1)

        nb.AddPage(self.temperaturePanel, 'Temp')

        self.directControlPanel = wx.Panel(nb)

        sizer = wx.GridBagSizer(2, 2)
        self.directControlPanel.SetSizer(sizer)
        sizer.Add(PrintCommandButton(self, ['G91', 'G1 Y100 F6000', 'G90'],
                                     'print-move-y100.png'),
                  pos=(0, 3))
        sizer.Add(PrintCommandButton(self, ['G91', 'G1 Y10 F6000', 'G90'],
                                     'print-move-y10.png'),
                  pos=(1, 3))
        sizer.Add(PrintCommandButton(self, ['G91', 'G1 Y1 F6000', 'G90'],
                                     'print-move-y1.png'),
                  pos=(2, 3))

        sizer.Add(PrintCommandButton(self, ['G91', 'G1 Y-1 F6000', 'G90'],
                                     'print-move-y-1.png'),
                  pos=(4, 3))
        sizer.Add(PrintCommandButton(self, ['G91', 'G1 Y-10 F6000', 'G90'],
                                     'print-move-y-10.png'),
                  pos=(5, 3))
        sizer.Add(PrintCommandButton(self, ['G91', 'G1 Y-100 F6000', 'G90'],
                                     'print-move-y-100.png'),
                  pos=(6, 3))

        sizer.Add(PrintCommandButton(self, ['G91', 'G1 X-100 F6000', 'G90'],
                                     'print-move-x-100.png'),
                  pos=(3, 0))
        sizer.Add(PrintCommandButton(self, ['G91', 'G1 X-10 F6000', 'G90'],
                                     'print-move-x-10.png'),
                  pos=(3, 1))
        sizer.Add(PrintCommandButton(self, ['G91', 'G1 X-1 F6000', 'G90'],
                                     'print-move-x-1.png'),
                  pos=(3, 2))

        sizer.Add(PrintCommandButton(self, ['G28 X0 Y0'],
                                     'print-move-home.png'),
                  pos=(3, 3))

        sizer.Add(PrintCommandButton(self, ['G91', 'G1 X1 F6000', 'G90'],
                                     'print-move-x1.png'),
                  pos=(3, 4))
        sizer.Add(PrintCommandButton(self, ['G91', 'G1 X10 F6000', 'G90'],
                                     'print-move-x10.png'),
                  pos=(3, 5))
        sizer.Add(PrintCommandButton(self, ['G91', 'G1 X100 F6000', 'G90'],
                                     'print-move-x100.png'),
                  pos=(3, 6))

        sizer.Add(PrintCommandButton(self, ['G91', 'G1 Z10 F200', 'G90'],
                                     'print-move-z10.png'),
                  pos=(0, 8))
        sizer.Add(PrintCommandButton(self, ['G91', 'G1 Z1 F200', 'G90'],
                                     'print-move-z1.png'),
                  pos=(1, 8))
        sizer.Add(PrintCommandButton(self, ['G91', 'G1 Z0.1 F200', 'G90'],
                                     'print-move-z0.1.png'),
                  pos=(2, 8))

        sizer.Add(PrintCommandButton(self, ['G28 Z0'], 'print-move-home.png'),
                  pos=(3, 8))

        sizer.Add(PrintCommandButton(self, ['G91', 'G1 Z-0.1 F200', 'G90'],
                                     'print-move-z-0.1.png'),
                  pos=(4, 8))
        sizer.Add(PrintCommandButton(self, ['G91', 'G1 Z-1 F200', 'G90'],
                                     'print-move-z-1.png'),
                  pos=(5, 8))
        sizer.Add(PrintCommandButton(self, ['G91', 'G1 Z-10 F200', 'G90'],
                                     'print-move-z-10.png'),
                  pos=(6, 8))

        sizer.Add(PrintCommandButton(self, ['G92 E0', 'G1 E2 F120'],
                                     'extrude.png',
                                     size=(60, 20)),
                  pos=(1, 10),
                  span=(1, 3),
                  flag=wx.EXPAND)
        sizer.Add(PrintCommandButton(self, ['G92 E0', 'G1 E-2 F120'],
                                     'retract.png',
                                     size=(60, 20)),
                  pos=(2, 10),
                  span=(1, 3),
                  flag=wx.EXPAND)

        nb.AddPage(self.directControlPanel, 'Jog')

        self.speedPanel = wx.Panel(nb)
        sizer = wx.GridBagSizer(2, 2)
        self.speedPanel.SetSizer(sizer)

        self.outerWallSpeedSelect = wx.SpinCtrl(self.speedPanel,
                                                -1,
                                                '100',
                                                size=(21 * 3, 21),
                                                style=wx.SP_ARROW_KEYS)
        self.outerWallSpeedSelect.SetRange(5, 1000)
        self.innerWallSpeedSelect = wx.SpinCtrl(self.speedPanel,
                                                -1,
                                                '100',
                                                size=(21 * 3, 21),
                                                style=wx.SP_ARROW_KEYS)
        self.innerWallSpeedSelect.SetRange(5, 1000)
        self.fillSpeedSelect = wx.SpinCtrl(self.speedPanel,
                                           -1,
                                           '100',
                                           size=(21 * 3, 21),
                                           style=wx.SP_ARROW_KEYS)
        self.fillSpeedSelect.SetRange(5, 1000)
        self.supportSpeedSelect = wx.SpinCtrl(self.speedPanel,
                                              -1,
                                              '100',
                                              size=(21 * 3, 21),
                                              style=wx.SP_ARROW_KEYS)
        self.supportSpeedSelect.SetRange(5, 1000)

        sizer.Add(wx.StaticText(self.speedPanel, -1, "Outer wall:"),
                  pos=(0, 0))
        sizer.Add(self.outerWallSpeedSelect, pos=(0, 1))
        sizer.Add(wx.StaticText(self.speedPanel, -1, "%"), pos=(0, 2))
        sizer.Add(wx.StaticText(self.speedPanel, -1, "Inner wall:"),
                  pos=(1, 0))
        sizer.Add(self.innerWallSpeedSelect, pos=(1, 1))
        sizer.Add(wx.StaticText(self.speedPanel, -1, "%"), pos=(1, 2))
        sizer.Add(wx.StaticText(self.speedPanel, -1, "Fill:"), pos=(2, 0))
        sizer.Add(self.fillSpeedSelect, pos=(2, 1))
        sizer.Add(wx.StaticText(self.speedPanel, -1, "%"), pos=(2, 2))
        sizer.Add(wx.StaticText(self.speedPanel, -1, "Support:"), pos=(3, 0))
        sizer.Add(self.supportSpeedSelect, pos=(3, 1))
        sizer.Add(wx.StaticText(self.speedPanel, -1, "%"), pos=(3, 2))

        nb.AddPage(self.speedPanel, 'Speed')

        self.termPanel = wx.Panel(nb)
        sizer = wx.GridBagSizer(2, 2)
        self.termPanel.SetSizer(sizer)

        f = wx.Font(8, wx.FONTFAMILY_MODERN, wx.FONTSTYLE_NORMAL,
                    wx.FONTWEIGHT_NORMAL, False)
        self.termLog = wx.TextCtrl(self.termPanel,
                                   style=wx.TE_MULTILINE | wx.TE_DONTWRAP)
        self.termLog.SetFont(f)
        self.termLog.SetEditable(0)
        self.termInput = wx.TextCtrl(self.termPanel, style=wx.TE_PROCESS_ENTER)
        self.termInput.SetFont(f)

        sizer.Add(self.termLog, pos=(0, 0), flag=wx.EXPAND)
        sizer.Add(self.termInput, pos=(1, 0), flag=wx.EXPAND)
        sizer.AddGrowableCol(0)
        sizer.AddGrowableRow(0)

        nb.AddPage(self.termPanel, 'Term')

        if self.cam is not None:
            self.camPage = wx.Panel(nb)
            sizer = wx.GridBagSizer(2, 2)
            self.camPage.SetSizer(sizer)

            self.timelapsEnable = wx.CheckBox(
                self.camPage, -1, 'Enable timelapse movie recording')
            sizer.Add(self.timelapsEnable,
                      pos=(0, 0),
                      span=(1, 2),
                      flag=wx.EXPAND)

            pages = self.cam.propertyPages()
            self.cam.buttons = [self.timelapsEnable]
            for page in pages:
                button = wx.Button(self.camPage, -1, page)
                button.index = pages.index(page)
                sizer.Add(button, pos=(1, pages.index(page)))
                button.Bind(wx.EVT_BUTTON, self.OnPropertyPageButton)
                self.cam.buttons.append(button)

            self.campreviewEnable = wx.CheckBox(self.camPage, -1,
                                                'Show preview')
            sizer.Add(self.campreviewEnable,
                      pos=(2, 0),
                      span=(1, 2),
                      flag=wx.EXPAND)

            self.camPreview = wx.Panel(self.camPage)
            sizer.Add(self.camPreview, pos=(3, 0), span=(1, 2), flag=wx.EXPAND)

            nb.AddPage(self.camPage, 'Camera')
            self.camPreview.timer = wx.Timer(self)
            self.Bind(wx.EVT_TIMER, self.OnCameraTimer, self.camPreview.timer)
            self.camPreview.timer.Start(500)
            self.camPreview.Bind(wx.EVT_ERASE_BACKGROUND,
                                 self.OnCameraEraseBackground)

        self.sizer.AddGrowableRow(6)
        self.sizer.AddGrowableCol(3)

        self.Bind(wx.EVT_CLOSE, self.OnClose)
        self.connectButton.Bind(wx.EVT_BUTTON, self.OnConnect)
        #self.loadButton.Bind(wx.EVT_BUTTON, self.OnLoad)
        self.printButton.Bind(wx.EVT_BUTTON, self.OnPrint)
        self.pauseButton.Bind(wx.EVT_BUTTON, self.OnPause)
        self.cancelButton.Bind(wx.EVT_BUTTON, self.OnCancel)
        self.machineLogButton.Bind(wx.EVT_BUTTON, self.OnMachineLog)

        self.Bind(wx.EVT_SPINCTRL, self.OnTempChange, self.temperatureSelect)
        self.Bind(wx.EVT_SPINCTRL, self.OnBedTempChange,
                  self.bedTemperatureSelect)

        self.Bind(wx.EVT_SPINCTRL, self.OnSpeedChange,
                  self.outerWallSpeedSelect)
        self.Bind(wx.EVT_SPINCTRL, self.OnSpeedChange,
                  self.innerWallSpeedSelect)
        self.Bind(wx.EVT_SPINCTRL, self.OnSpeedChange, self.fillSpeedSelect)
        self.Bind(wx.EVT_SPINCTRL, self.OnSpeedChange, self.supportSpeedSelect)
        self.Bind(wx.EVT_TEXT_ENTER, self.OnTermEnterLine, self.termInput)
        self.termInput.Bind(wx.EVT_CHAR, self.OnTermKey)

        self.Layout()
        self.Fit()
        self.Centre()

        self.statsText.SetMinSize(self.statsText.GetSize())

        self.UpdateButtonStates()
Beispiel #21
0
 def testGetRemainingPercentage(self):
     rem_percentage = power.PowerManagement().get_remaining_percentage()
     self.assertIsNotNone(rem_percentage)
     self.assertIsInstance(rem_percentage, float)
     self.assertTrue(rem_percentage >= 0 and rem_percentage <= 100)
Beispiel #22
0
import power
import time
import notify2
from notify2 import Notification

notify2.init("Charger Warning")
n = Notification("WARNING", "Laptop running on battery. Plug in charger!")
n.set_urgency(notify2.URGENCY_CRITICAL)

while (True):
    source = power.PowerManagement().get_providing_power_source_type()

    if source == power.POWER_TYPE_BATTERY:
        n.show()
        print('NOT CHARGING!')
    else:
        print('CHARGING')
    time.sleep(300)
Beispiel #23
0
    def __init__(self):
        print("Starting System Monitor")
        self.root = Tk()
        self.root.title('System Monitor')
        self.root.iconbitmap('@sysmonitor.xbm')
        # self.root.geometry("600x300+150+150")

        #NoteBook
        self.n = Notebook(self.root)
        self.f1 = Frame(self.n)  # CPU Usage
        self.f2 = Frame(self.n)  # Memory
        self.f3 = Frame(self.n)  # Sensors
        self.f4 = Frame(self.n)  # Graph
        self.f5 = Frame(self.n)  # Processes
        self.n.add(self.f1, text='CPU Usage')
        self.n.add(self.f2, text='Memory')
        self.n.add(self.f3, text='Sensors')
        self.n.add(self.f4, text='Graph')
        self.n.add(self.f5, text='Processes')
        self.n.pack(fill=BOTH)

        ################################################### CPU USAGE ######################################################
        #Current CPU usage
        self.cur_cpu = pc.cpu_percent()
        self.cpu_arr = deque()
        self.cpu_arr.append(self.cur_cpu)

        #Progress Bar to show current CPU usage
        self.cpu_bar = Progressbar(self.f1,
                                   length=300,
                                   value=self.cur_cpu,
                                   mode="determinate")
        self.cpu_bar.pack(padx=5, pady=5, fill=BOTH)

        #Variable string to store current CPU usage
        self.cpu_percent = StringVar()
        self.cpu_percent.set("CPU Usage: " + str(self.cur_cpu) + " %")
        self.cpu_percent_label = Label(self.f1, textvariable=self.cpu_percent)
        self.cpu_percent_label.place(relx=0.5, rely=0.2, anchor=CENTER)

        self.cpu_freq = pc.cpu_freq()
        self.cpu_freq_val = StringVar()
        self.cpu_freq_val.set(
            str("Current CPU Freq: " + str(int(self.cpu_freq[0])) + "/" +
                str(int(self.cpu_freq[2])) + " MHz"))
        self.cpu_freq_label = Label(self.f1, textvariable=self.cpu_freq_val)
        self.cpu_freq_label.place(relx=0.5, rely=0.3, anchor=CENTER)

        self.cpu_count_label = Label(self.f1,
                                     text="Number of CPUs: " +
                                     str(pc.cpu_count()))
        self.cpu_count_label.place(relx=0.5, rely=0.4, anchor=CENTER)

        self.pid = pc.pids()
        self.pid_val = StringVar()
        self.pid_val.set(str("Total Running Processes: " + str(len(self.pid))))
        self.pid_label = Label(self.f1, textvariable=self.pid_val)
        self.pid_label.place(relx=0.5, rely=0.5, anchor=CENTER)

        ######################################################  MEMORY  ####################################################
        self.ram = pc.virtual_memory()
        self.swap = pc.swap_memory()
        self.disk = pc.disk_usage('/home')
        self.ram_percent = self.ram[2]
        self.swap_percent = self.swap[3]
        self.disk_percent = self.disk[3]

        self.memory_window = Panedwindow(self.f2, orient=VERTICAL)
        self.memory_frame1 = Labelframe(self.memory_window,
                                        text='RAM',
                                        width=100,
                                        height=100)
        self.memory_frame2 = Labelframe(self.memory_window,
                                        text='Swap',
                                        width=100,
                                        height=100)
        self.memory_frame3 = Labelframe(self.memory_window,
                                        text='Disk',
                                        width=100,
                                        height=100)
        self.memory_window.add(self.memory_frame1)
        self.memory_window.add(self.memory_frame2)
        self.memory_window.add(self.memory_frame3)

        # RAM Used
        self.ram_bar = Progressbar(self.memory_frame1,
                                   length=300,
                                   value=self.ram_percent,
                                   mode="determinate")
        self.ram_bar.pack(padx=5, pady=5, fill=BOTH)
        self.ram_val = StringVar()
        self.ram_val.set("Ram Used: " + str(self.ram_percent) + "%")
        self.ram_label = Label(self.memory_frame1, textvariable=self.ram_val)
        self.ram_label.pack(side=LEFT, fill=BOTH)

        #Swap Used
        self.swap_bar = Progressbar(self.memory_frame2,
                                    length=300,
                                    value=self.swap_percent,
                                    mode="determinate")
        self.swap_bar.pack(padx=5, pady=5, fill=BOTH)
        self.swap_val = StringVar()
        self.swap_val.set("Swap Used: " + str(self.swap_percent) + "%")
        self.swap_label = Label(self.memory_frame2, textvariable=self.swap_val)
        self.swap_label.pack(side=LEFT, fill=BOTH)

        #Disk Space Used
        self.disk_bar = Progressbar(self.memory_frame3,
                                    length=300,
                                    value=self.disk_percent,
                                    mode="determinate")
        self.disk_bar.pack(padx=5, pady=5, fill=BOTH)
        self.disk_val = StringVar()
        self.disk_val.set("Disk Used: " + str(self.disk_percent) + "%")
        self.disk_label = Label(self.memory_frame3, textvariable=self.disk_val)
        self.disk_label.pack(side=LEFT, fill=BOTH)

        self.memory_frame1.pack(fill=BOTH)
        self.memory_frame2.pack(fill=BOTH)
        self.memory_frame3.pack(fill=BOTH)
        self.memory_window.pack(fill=BOTH)

        ###################################################### SENSORS #####################################################
        #Current Sensor Values
        self.temperature = pc.sensors_temperatures()
        self.battery = pc.sensors_battery()

        self.battery_estimate = ""
        self.power_source = ""
        source = power.PowerManagement().get_providing_power_source_type()
        if (source == power.POWER_TYPE_AC):
            self.power_source = "AC"
        elif (source == power.POWER_TYPE_BATTERY):
            self.power_source = "BATTERY"
        elif (source == power.POWER_TYPE_UPS):
            self.power_source = "UPS"
        else:
            self.power_source = "UNKNOWN"

        self.temp_cur = self.temperature['coretemp'][0][1]
        self.temp_critical = self.temperature['coretemp'][0][3]

        self.sensor_window = Panedwindow(self.f3, orient=VERTICAL)
        self.sensor_frame1 = Labelframe(self.sensor_window,
                                        text='Temperature',
                                        width=100,
                                        height=100)
        self.sensor_frame2 = Labelframe(self.sensor_window,
                                        text='Battery',
                                        width=100,
                                        height=100)
        self.sensor_window.add(self.sensor_frame1)
        self.sensor_window.add(self.sensor_frame2)

        #Progress Bar to show current temperature
        self.temp_bar = Progressbar(self.sensor_frame1,
                                    length=300,
                                    value=self.temp_cur,
                                    mode="determinate",
                                    maximum=self.temp_critical)
        self.temp_bar.pack(padx=5, pady=5, fill=BOTH)

        #Temperature
        self.cur_temp = StringVar()
        self.cur_temp.set("cur_temp: " + str(self.temp_cur) + "`C")
        self.cur_temp_label = Label(self.sensor_frame1,
                                    textvariable=self.cur_temp)
        self.cur_temp_label.pack(side=LEFT, fill=BOTH)
        self.label_temp = Label(self.sensor_frame1,
                                text="critical_temp: " +
                                str(self.temp_critical) + "\u2103")
        self.label_temp.pack(side=RIGHT, fill=BOTH)

        #Battery Status
        self.batt_estimate = StringVar()
        self.batt_estimate.set("Battery Estimate: " +
                               str(self.battery_estimate))
        self.batt_estimate_label = Label(self.sensor_frame2,
                                         textvariable=self.batt_estimate)
        self.batt_estimate_label.pack(fill=BOTH)
        self.label_batt_type = Label(self.sensor_frame2,
                                     text="Power Source: " + self.power_source)
        self.label_batt_type.pack(side=LEFT, fill=BOTH)

        self.sensor_frame1.pack(fill=BOTH)
        self.sensor_frame2.pack(side=LEFT, fill=BOTH)
        self.sensor_window.pack(fill=BOTH)

        ################################################### GRAPH ##########################################################
        #Graph Variables
        self.fig = Figure(figsize=(0.1, 0.1))
        ax = self.fig.add_subplot(111)
        self.line, = ax.plot(range(50))
        ax.axis([0, 50, 0, 100])
        ax.set_title("CPU Usage", fontsize=12)
        ax.set_ylabel("Percentage", fontsize=10)
        ax.set_xlabel("Time", fontsize=10)
        self.canvas = FigureCanvasTkAgg(self.fig, master=self.f4)
        self.canvas.show()
        self.canvas.get_tk_widget().pack(side='top',
                                         fill=BOTH,
                                         expand=1,
                                         ipadx=180)

        ############################################### PROCESSES ##########################################################
        self.kill_process_id = 0

        self.scrollbar = Scrollbar(self.f5)
        self.scrollbar.pack(side=RIGHT, fill=Y)

        self.update_button = Button(self.f5,
                                    text="Update",
                                    command=self.update_processes)
        self.update_button.pack(side=TOP)

        tv = Treeview(self.f5)
        tv['columns'] = ('cpu', 'id', 'status')
        tv.heading("#0", text='Process Name', anchor='w')
        tv.column("#0", anchor="w", width=75)
        tv.heading('cpu', text='% CPU')
        tv.column('cpu', anchor='center', width=40)
        tv.heading('id', text='PID')
        tv.column('id', anchor='center', width=35)
        tv.heading('status', text='Status')
        tv.column('status', anchor='center', width=40)
        tv.pack(fill=BOTH)
        self.treeview = tv

        tv.tag_configure('active', background='green')
        # attach listbox to scrollbar
        self.treeview.config(yscrollcommand=self.scrollbar.set)
        self.scrollbar.config(command=self.treeview.yview)

        self.pMenu = Menu(self.f5, tearoff=0)
        self.pMenu.add_command(label="Kill Process", command=self.kill_process)
        self.pMenu.add_command(label="Kill Process Tree",
                               command=self.kill_process_tree)
        self.pMenu.add_command(label="Cancel")

        self.treeview.bind("<Button-3>", self.process_popup)
        self.treeview.bind("<Button-2>", self.process_popup)

        ################################################### UPDATE #########################################################

        #Call Update() after 100 ms
        self.job1 = self.f1.after(1000, self.update_cpu)
        self.job2 = self.f2.after(1000, self.update_memory)
        self.job3 = self.f3.after(1000, self.update_sensors)
        self.job4 = self.f4.after(1000, self.update_graph)
        self.job5 = self.f5.after(1000, self.update_processes)
        #The Main Loop
        self.root.mainloop()
        #Kill everything once the window is closed.
        print("Killing everything.")
        self.f1.after_cancel(self.job1)
        self.f2.after_cancel(self.job2)
        self.f3.after_cancel(self.job3)
        self.f4.after_cancel(self.job4)
        self.f5.after_cancel(self.job5)
        print("Good Bye!")
        sys.exit()