Ejemplo n.º 1
0
def dimmer_checker(dt):
    global dimmer_day
    global dimmer_night
    global bl_warning
    curtime = datetime.datetime.now()
    curtime = curtime.strftime("%H:%M:%S")

    if ((curtime > dimmer_night) &
        (curtime > dimmer_day)) | ((curtime < dimmer_night) &
                                   (curtime < dimmer_day)):
        print("[INFO   ] Night Mode Active")
        try:
            bl.set_brightness(appSettings['dimmer']['night_value'],
                              smooth=True,
                              duration=10)
        except Exception:
            print(bl_warning)
    else:
        print("[INFO   ] Day Mode Active")
        try:
            bl.set_brightness(appSettings['dimmer']['day_value'],
                              smooth=True,
                              duration=10)
        except Exception:
            print(bl_warning)
def decreaseBrightness(inc):
    current = bl.get_actual_brightness()
    target = current + (25 * inc)
    if current > 11:
        if target < 11:
            target = 11
        bl.set_brightness(target, smooth=False)
Ejemplo n.º 3
0
 def increaseBrightness(self):
     current = bl.get_actual_brightness()
     target = current + 25
     if current < 255:
         if target > 255:
             target = 255
         bl.set_brightness(target, smooth=True, duration=1)
Ejemplo n.º 4
0
 def decreaseBrightness(self):
     current = bl.get_actual_brightness()
     target = current - 25
     if current > 11:
         if target < 11:
             target = 11
         bl.set_brightness(target, smooth=True, duration=1)
Ejemplo n.º 5
0
 def changeSlider(self, value):
     global bl_warning
     print(int(value))
     try:
         bl.set_brightness(int(value))
     except Exception:
         print(bl_warning)
Ejemplo n.º 6
0
Archivo: main.py Proyecto: drwonky/NC
 def startup(self):
     try:
         bl.set_brightness(self.config.getint('screen', 'brightness'),
                           False)
     except:
         pass
     self.wifi_reconnect()
def increaseBrightness(inc):
    current = bl.get_actual_brightness()
    target = current + (25 * inc)
    if current < 255:
        if target > 255:
            target = 255
        bl.set_brightness(target, smooth=False)
Ejemplo n.º 8
0
    def sensor_tap(self, pin_no, state, timestamp):

        time_since_last_tap = (datetime.now() - self.last_tap).total_seconds()
        self.last_tap = datetime.now()

        if (time_since_last_tap > 1):
            #This is a new tap
            self.tap_count = self.tap_count + 1
            self.last_tap = datetime.now()
            self.last_activity = self.last_tap
            print(self.tap_count)
            print(time_since_last_tap)

            #turn up brightness if lower
            if (self.screen_status == SCREEN_OFF):
                bl.set_brightness(LOW_BRIGHTNESS)
                self.screen_status = SCREEN_LOW
            elif (self.screen_status == SCREEN_LOW):
                bl.set_brightness(HIGH_BRIGHTNESS)
                self.screen_status = SCREEN_HIGH

            #turn off alarm if sounding
            for alarm in Alarms:
                if (alarm.status == ALARM_STATUS_SOUNDING):
                    alarm.snooze()
                    print("Found sounding alarm")
Ejemplo n.º 9
0
 def change_backlight(self, value):
     """Method that sets the backlight to a certain value."""
     Logger.info('Application: change_backlight(' + str(value) +
                 ') rpienable = ' + self.config.get('system', 'rpienable'))
     # only if the ini file says it's ok
     if self.config.getboolean('system', 'rpienable'):
         import rpi_backlight as bl
         # set the brightness
         bl.set_brightness(int(value), smooth=True, duration=1)
Ejemplo n.º 10
0
 def hide(self):
     self.menuActive = False
     if "arm" in platform.machine():
         import rpi_backlight as bl
         bl.set_brightness(100)
     self.radio.playAfterSandby()
     time.sleep(0.2)
     super().hide()
     time.sleep(0.2)
     self.radio.show()
Ejemplo n.º 11
0
 def set_brightness(self, value):
     if self.MIN_BRIGHTNESS <= value <= self.max:
         if not self.dummy:
             bl.set_brightness(int(value))
         self.dispatch('on_brightness_change', value)
         Logger.info(
             'BrightnessHandler: setting brightness to {}'.format(value))
     else:
         raise ValueError(
             "Brightness value must be between {} and {}".format(
                 self.MIN_BRIGHTNESS, self.max))
Ejemplo n.º 12
0
def motionSensor(channel):
    if GPIO.input(21):
        global counter
        counter += 1
        global timeout
        timeout = 0
        print("motion detected {}".format(counter))
        try:
            bl.set_brightness(255)
        except (OSError, IOError) as err:
            if err.errno == 13:
                print("permission denied {}".format(err.errno))
Ejemplo n.º 13
0
 def show(self):
     self.menuActive = True
     if "arm" in platform.machine():
         import rpi_backlight as bl
         bl.set_brightness(15)
     ypos = random.randint(0, 220)
     self.clock.labelTime.setGeometry(QtCore.QRect(190, ypos, 441, 181))
     self.clock.labelDate.setGeometry(QtCore.QRect(190, ypos + 180, 481,
                                                   51))
     self.radio.sDialog.hideSelectStation()
     self.radio.stop()
     super().show()
def lightcheck():
	#Read Ch0 Word
	data = bus.read_i2c_block_data(TSLaddr, chan0 | TSLcmd, 2)
	#Read CH1 Word
	data1 = bus.read_i2c_block_data(TSLaddr, chan1 | TSLcmd, 2)
	# Convert the data to Integer
	ch0 = data[1] * 256 + data[0]
	ch1 = data1[1] * 256 + data1[0]
	vResults = ch0-ch1 #get visable light results
	translated = remap(vResults, oMin, oMax, nMin, nMax)
	print("Reading = ",vResults,"Mapped = ",translated)
	
	#subprocess.Popen(['echo {} > /sys/class/backlight/rpi_backlight/brightness'.format(translated)], shell=True)
	bl.set_brightness(translated, smooth=True, duration=2)
	time.sleep(5)
Ejemplo n.º 15
0
def PIRChange(channel):
    global SwitchDisplay, DisplayOffCount

    if GPIO.input(PIRPin) == GPIO.LOW:
        SwitchDisplay = 0
        DisplayOffCount = COUNT
        #print 'Tick 1-0 um ' + datetime.datetime.now().strftime("%H:%M:%S")

    else:
        SwitchDisplay = 1
        print 'Tick 0-1 um ' + datetime.datetime.now().strftime("%H:%M:%S")
        if (screen.get_power() != True):
            screen.set_power(True)
            screen.set_brightness(255, smooth=True, duration=3)
        DisplayOffCount = COUNT
Ejemplo n.º 16
0
    def update_clock(self, dt):
        #Set clock label
        self.clock_string = datetime.now().strftime("%H:%M")

        #Check if there is something to do
        for alarm in Alarms:
            if (alarm.should_sound()):
                self.sound_alarm(alarm)

        #check how long the last activity was
        time_since_last_activity = (datetime.now() -
                                    self.last_activity).total_seconds()

        #Set low screen brightness
        if (time_since_last_activity > 10
                and self.screen_status == SCREEN_HIGH):
            bl.set_brightness(LOW_BRIGHTNESS)
            self.screen_status = SCREEN_LOW
Ejemplo n.º 17
0
def updateGeneralSettings():
    """
    ### API Path   `/api/updateGeneralSettings`
    ### Request Type: `POST`
    Changes general settings. Currently only brightness is possible """
    logger.debug(json.dumps(request.get_json(), indent=2, sort_keys=False))
    params = request.get_json()
    if(simul):
        return 'Simulation', Status.HTTP_OK_BASIC;

    brightness = int(params["brightness"])

    if(brightness > 255 or brightness < 0):
        return "Invalid Range for brightness", Status.HTTP_BAD_REQUEST

    backlight.set_brightness(brightness)

    return 'Changes Applied', Status.HTTP_OK_BASIC
Ejemplo n.º 18
0
def adjust_brightness(measured_level):

  if measured_level <= 5:
    set_brightness(15,True, 3)
 
  elif measured_level <= 40 and measured_level > 5:
    set_brightness(15,True, 3)
 
  elif measured_level < 80 and measured_level > 40:
    set_brightness(75,True, 3)

  else:
    set_brightness(220, True, 3)
Ejemplo n.º 19
0
    def pressed(self, instance):
        try:
            import rpi_backlight as bl
        except ImportError:
            # TODO: add logging here
            print('No library to change brightness')
            return

        self.current_brightness = (self.current_brightness + 1) % len(self.brightnesses)
        brightness_data = self.brightnesses[self.current_brightness]
        brightness = brightness_data[1]
        self.text = brightness_data[0]
        bl.set_brightness(brightness)

        self.current_brightness = (self.current_brightness + 1) % len(self.brightnesses)
        brightness_data = self.brightnesses[self.current_brightness]
        brightness = brightness_data[1]
        self.text = brightness_data[0]
        bl.set_brightness(brightness)

        return True
Ejemplo n.º 20
0
def on_message(client, userdata, message):
    try:
        global broker_statetopic
        print("[INFO   ] MQTT Message: ", str(message.payload.decode("utf-8")))
        print("[INFO   ] MQTT Topic: ", str(message.topic))
        msgPreformat = str(message.payload.decode("utf-8"))
        msgFormatted = str.replace(msgPreformat, "_", " ").upper()
        if (message.topic == broker_statetopic):
            App.get_running_app().root.ids.status.text = msgFormatted
        broker_lastmsg = msgFormatted
        if (msgFormatted == "PENDING"):
            App.get_running_app().root.ids.bar.value = 0
            App.get_running_app().root.ids.bar.max = 60
            doProg = Clock.schedule_interval(progBar, 0.5)
        elif (message.topic == "panel/backlight"):
            try:
                bl.set_brightness(int(message.payload.decode("utf-8")))
            except Exception as e:
                print(bl_warning)
                print(e)
    except Exception as e:
        print(e)
Ejemplo n.º 21
0
def read_and_emulate_mouse(event, touch):
    global startX
    global startY
    global startTime
    global shouldRun

    if event == TS_PRESS:
        # print("Got Press", touch)
        (startX, startY) = touch.position
        startTime = time.time()
    # if event == TS_RELEASE:
    #     print("Got release", touch)
    # if event == TS_MOVE:
    #     print("Got move", touch.position)

    (x, y) = touch.position
    (last_x, last_y) = touch.last_position

    movement = math.sqrt(pow(x - startX, 2) + pow(y - startY, 2))
    # top left: brightness
    if startX < 10 and startY > 469 and x <= 200:
        call(["amixer", "cset", "numid=1", "--", str(floor(x / 2)) + '%'])
    # bottom left: volume
    if startX < 10 and startY < 10 and x <= 244:
        bl.set_brightness(x + 11)
    # top right: quit parsec
    if startX > 788 and startY < 10:
        if movement < 20 and event == TS_RELEASE and (time.time() -
                                                      startTime) >= 3:
            call(["killall", "parsec"])
            call(["killall", "screen"])
            call(["./touchscreen"])
            shouldRun = False
            exit()
    if startX > 788 and startY > 469:
        if movement < 20 and event == TS_RELEASE and (time.time() -
                                                      startTime) >= 3:
            call(["killall", "screen"])
            call(["screen", "-dm", "-S", "jcdriver", "./go/bin/jcdriver"])
Ejemplo n.º 22
0
 def __init__(self, gui, dia):
     self.gui = gui
     self.dia = dia
     self.menuActive = True
     
     if "arm" in platform.machine():
         print("ARM Detected, so probably Rapberry")
         import rpi_backlight as bl
         import lircradio
        
         # Backlight
         bl.set_brightness(100) # start up with full brightness
         
         # LIRC remote
         lircQueue = queue.Queue()
         
         self.LircObject = lircradio.LircInterface(lircQueue)
         self.LircObject.start()
         
         self.LircHandler = lircradio.LircHandler(lircQueue)
         self.lircTimer = QtCore.QTimer()
         self.lircTimer.timeout.connect(self.LircHandler.timerCall)
         self.lircTimer.start(1000)
         self.LircHandler.addCallback("ok", self.ok_clicked)
         self.LircHandler.addCallback("back", self.back_clicked)
         self.LircHandler.addCallback("up", self.up_clicked)
         self.LircHandler.addCallback("down", self.down_clicked)
         self.LircHandler.addCallback("left", self.left_clicked)
         self.LircHandler.addCallback("right", self.right_clicked)
         self.LircHandler.addCallback("power", self.power_clicked)
     else:
         print("No ARM, so no Rapberry")
         
     self.sDialog = station.SelectStation()
     dia.setStyleSheet("QWidget#Dialog {background-image: url(Music-Record-Vinyl-800-480.jpg);}")
     self.cDialog = clock.Clock(self)
     
     self.infoTimer = QtCore.QTimer()
     self.infoTimer.timeout.connect(self.timercall)
     self.infoTimer.start(5000)
     
     font = QtGui.QFont()
     font.setFamily("Droid Sans")
     font.setPointSize(28)
     font.setBold(True)
     font.setWeight(75)
     
     self.labelStation = labelClickable.QLabelClickable(self.dia)
     self.labelStation.setFont(font)
     self.labelStation.setGeometry(28, 415, 750, 60)
     self.labelStation.setText("<font color='lightGray'> Back </font>")
     self.labelStation.clicked.connect(self.selectStation_clicked)
     self.showArtist("")
     self.showSong("")
     self.getLastPlayed()
     
     self.showStation(self.last_name)
     self.showTime()
     self.showPicture(self.last_image)
     
     self.client = mpd.MPDClient()       # create client object
     self.client.timeout = 2             # network timeout in seconds (floats allowed), default: None
     self.client.idletimeout = None      # timeout for fetching the result of the idle command is handled seperately, default: None
     
     self.number = 0
     self.clear()
     self.addStation(self.lasturl)
     print("Starting")
     self.play(self.number)
     self.status = "playing"
     self.getShowInfo()
Ejemplo n.º 23
0
def Sheila_Core():  
    try:
        #Local time variables for Sheila
        startTime = time.time()
        seconds = 0
        minutes = 0
        
        #This function initializes the UI
        rootW=setupGUI()
        
        #This function sets the screen to OFF for the initialization
        blAdjust(11)
             
        #This command clears the terminal window for easier reading
        os.system('cls' if os.name == 'nt' else 'clear')

        #Quick message at the start to record start time
        bootTime=datetime.now()
        say("Hello, booting up, the time is " + str(bootTime.hour) + " " + str(bootTime.minute))
        
        #Setup of flags/initialized classes that will be used later
        weather = Weather()
        alarmFlag = True
        detFlag = False
        
        locale = weather.lookup(12588678)
        condition = locale.condition
        time.sleep(.8)
        say("The weather is currently " + condition.text + " and it is currently " + condition.temp + " degrees celsius.")
        
        while True:
            
            #This section sets up the alarm clock functionality 
            currentTime = datetime.now().time() 
            if currentTime.hour == 6 and alarmFlag is True:             
                locale = weather.lookup(12588678)
                condition = locale.condition()
                            
                say("Good morning, Andy. It is time to get up and start your day.")
                say("The time is currently " + str(currentTime.hour) + " " + str(currentTime.minute))
                say("The weather is currently " + condition.text() + " and it is currently " + condition.temp() + " degrees celsius.")
                alarmFlag = False
            if currentTime.hour > 6 and alarmFlag is False:
                alarmFlag = True

            #Incrementing the time counter
            seconds = int(time.time() - startTime) - minutes * 60
            if seconds >= 60 :
                minutes += 1
                seconds = 0
                
            #This is the voice input stream
            inputVO = VO.recordAndInterpret()

            #This section handles the VO interpretation
            fullVOSplit = inputVO.split()
            for word in fullVOSplit:
                if word.lower() == "sheila" and detFlag is False:
                    print("--------------------------------------------------")
                    print("...I heard my name...")
                    print("--------------------------------------------------")
                    say("I heard you, you said: " + str(inputVO))
                    detFlag = True
                    print("--------------------------------------------------")
                    print("...Detection flag set to True...")
                    print("--------------------------------------------------")
                    break
                elif detFlag is True:
                    pass

            #If more than 3 minutes have passed, reset detflag
            if minutes > 3:
                minutes = 0
                seconds = 0
                startTime = time.time()
                detFlag = False
                print("--------------------------------------------------")
                print("...Detection flag set to False...")
                print("--------------------------------------------------")

    except KeyboardInterrupt:
        bl.set_brightness(255, smooth=False, duration = 0.1)
        rootW.destroy()
        sys.exit()
Ejemplo n.º 24
0
def blAdjust(brightness):
    bl.set_brightness(brightness, smooth=True, duration = 0.25)
Ejemplo n.º 25
0
 def doFadeIn(self, duration=5):
     bl.set_brightness(255, smooth=True, duration=duration)
Ejemplo n.º 26
0
 def doOff(self):
     bl.set_brightness(self.offLvl)
Ejemplo n.º 27
0
 def doOn(self):
     bl.set_brightness(255)
Ejemplo n.º 28
0
 def doFadeOut(self, duration=5):
     bl.set_brightness(self.offLvl, smooth=True, duration=duration)
Ejemplo n.º 29
0
def read_and_emulate_mouse(event, touch):
    global startX
    global startY
    global startTime
    global shouldRun
    global brightLast
    global killid
    global layerList
    if event == TS_RELEASE:
        os.system("sudo kill " + "$(ps aux | grep '[p]ngview' | awk '{print $2}')")
        layerList = []
    if event == TS_PRESS:
        (startX, startY) = touch.position
        startTime = time.time()

    (x, y) = touch.position
    (last_x, last_y) = touch.last_position

    movement = math.sqrt(pow(x - startX, 2) + pow(y - startY, 2))
    # top left: brightness
    if startX < 244 and startY < 140 and x <= 244:
        bl.set_brightness(x + 11)
        brightnessValue = x + 11
        brightnessPng = ""
        if brightnessValue >= 5 and brightnessValue < 29:
            brightnessPng = "10"
        elif brightnessValue >= 30 and brightnessValue < 54:
            brightnessPng = "20"
        elif brightnessValue >= 55 and brightnessValue < 79:
            brightnessPng = "30"
        elif brightnessValue >= 80 and brightnessValue < 104:
            brightnessPng = "40"
        elif brightnessValue >= 105 and brightnessValue < 129:
            brightnessPng = "50"
        elif brightnessValue >= 130 and brightnessValue < 154:
            brightnessPng = "60"
        elif brightnessValue >= 155 and brightnessValue < 179:
            brightnessPng = "70"
        elif brightnessValue >= 180 and brightnessValue < 204:
            brightnessPng = "80"        
        elif brightnessValue >= 205 and brightnessValue < 230:
            brightnessPng = "90"
        elif brightnessValue >= 231:
            brightnessPng = "100"
        if brightLast != brightnessPng and brightnessPng != "":
            brightLast = brightnessPng
            if len(layerList) == 0:
                os.system("/home/pi/swipi-retro/assets/Pngview" + "/pngview -b 0 -l 3000" + "1" + " -x 260 -y 150 " + "/home/pi/swipi-retro/assets/icons/brightness/" + "bar" + ".png &")			
            os.system("/home/pi/swipi-retro/assets/Pngview" + "/pngview -b 0 -l 3000" + brightnessPng + " -x 260 -y 150 " + "/home/pi/swipi-retro/assets/icons/brightness/" + brightnessPng + ".png &")
            killBrightnessID = check_output("ps aux | grep '[p]ngview' | awk '{print $2}'", shell=True)
            killBrightnessID = killBrightnessID.decode("utf-8")
            killBrightnessID = killBrightnessID.replace("\n", " ")
            killBrightnessID = killBrightnessID.split(" ")
            for layer in killBrightnessID:
                if layer != "" and layer not in layerList:
                    layerList.append(layer)
            if len(layerList) == 3:
                killThisID = str(layerList[1])
                os.system("sudo kill " + killThisID)
                layerList.remove(layerList[1])
    # bottom left: volume
    if startX < 244 and startY > 340 and x <= 244:
        call(["amixer", "cset", "numid=1", "--", str(floor(x/2.44)) + '%'])
    
    #top right: kill jcDriver
    if startX > 556 and startY < 140:
        if movement < 20 and event == TS_RELEASE and (time.time() - startTime) >= 2:
            call(["sudo", "screen", "-S", "jcDriver", "-X", "quit"])
            call(["sudo", "screen", "-dmSL", "jcDriver", "jcdriver"])
    #bottom right: switch Displaymode
    if startX > 556 and startY > 340:
        if movement < 20 and event == TS_RELEASE and (time.time() - startTime) >= 2:
            stateFile = open(screenState, 'r')
            state = stateFile.readline()
            state = str(state)
            stateFile.close()
            if (state == "lcd"):
                SP.call('echo "hdmi" > /home/pi/swipi-retro/assets/currentDisplayMode', shell=True)
                SP.call(['sudo','/home/pi/swipi-retro/assets/hdmi_out'])
            else :
                SP.call('echo "lcd" > /home/pi/swipi-retro/assets/currentDisplayMode', shell=True)
                SP.call(['sudo','/home/pi/swipi-retro/assets/lcd_out'])
Ejemplo n.º 30
0
 def __init__(self, offLvl=64):
     bl.set_brightness(offLvl)
     self.state = self.LEDState.off
     self.level = offLvl
     self.offLvl = offLvl