Exemplo n.º 1
0
 def _set_value(self):
     sbc.set_brightness(self.slider.get())
Exemplo n.º 2
0
import cv2
from PIL import Image, ImageStat
import numpy
import screen_brightness_control as sbc
from numpy import interp

vc = cv2.VideoCapture(0)

if vc.isOpened():
    rval, frame = vc.read()
else:
    rval = False


def brightness(frame):
    return numpy.mean(frame)


while rval:
    rval, frame = vc.read()
    key = cv2.waitKey(20)
    bright = brightness(frame)
    sbc.set_brightness(int(interp(bright, [1, 255], [0, 100])))
Exemplo n.º 3
0
        length = math.hypot(x2 - x1, y2 - y1)

        length2 = math.hypot(x4 - x3, y4 - y3)

        vol = np.interp(length, volumeRangeToInterpret, [minVol, maxVol])
        volBar = np.interp(length, volumeRangeToInterpret, barRange)
        volPer = np.interp(length, volumeRangeToInterpret, [0, 100])
        volume.SetMasterVolumeLevel(vol, None)

        if length < 50:
            cv2.circle(img, (cx, cy), circleSize, (0, 255, 0), cv2.FILLED)

        bright = np.interp(length2, brightRangeToInterpret, [minBright, maxBright])
        brightBar = np.interp(length2, brightRangeToInterpret, barRange)
        if abs(prevBright-bright) > 5:
            sbc.set_brightness(float(bright))
        prevBright = bright

    img = cv2.resize(img, (0, 0), fx=0.6, fy=0.6)
    cv2.rectangle(img, (50, 150), (85, 400), (255, 0, 255), 3)
    cv2.rectangle(img, (50, int(volBar)), (85, 400), (255, 0, 255), cv2.FILLED)
    cv2.putText(img, f'{int(volPer)} %', (40, 450), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 0, 255), 3)
    cv2.putText(img, 'volume', (20, 500), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 0, 255), 3)

    cv2.rectangle(img, (1000, 150), (1035, 400), (255, 0, 0), 3)
    cv2.rectangle(img, (1000, int(brightBar)), (1035, 400), (255, 0, 0), cv2.FILLED)
    cv2.putText(img, f'{int(bright)} %', (990, 450), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 0, 0), 3)
    cv2.putText(img, 'brightness', (940, 500), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 0, 0), 3)

    cTime = time.time()
    fps = 1 / (cTime - pTime)
Exemplo n.º 4
0
def _set_value(val):
        sbc.set_brightness(int(val))
        pass
Exemplo n.º 5
0
         current_brightness = sbc.get_brightness()
         if 40 < current_brightness[0] <= 60:
             speak("Curent brightness is okay! Want to alter it?")
         elif current_brightness[0] >= 80:
             speak("Brightness is too much! Want to alter it?")
         elif current_brightness[0] <= 30:
             speak("Brightness is too low! Want to alter it?")
         decision = input("Alter Brightness[y/n]:")
         if (decision == 'y'):
             battery_percentage = input(
                 "Enter the brightness percentage. It will increased or decreased according to percenatge:"
             )
             if battery_percentage.endswith("%"):
                 battery_percentage = battery_percentage.replace(
                     "%", " ")
             sbc.set_brightness(int(battery_percentage))
         else:
             pass
 except subprocess.CalledProcessError as e:
     speak("Dev can not work over this command!")
 except KeyboardInterrupt as e:
     confirm = input("Terminate DEV's console[y/n]:")
     if confirm.lower() == 'y':
         engine.say("Roger that!")
         hour = datetime.now().hour
         if hour >= 6 and hour < 12:
             try:
                 speak("Have a good day buddy")
                 sys.exit(0)
             except:
                 break
Exemplo n.º 6
0
        elif 'volume up' in query:
            keyboard = Controller()
            for i in range(10):
                keyboard.press(Key.media_volume_up)
                keyboard.release(Key.media_volume_up)
                time.sleep(0.1)
                continue
        #   =========================================
        elif 'change brightness' in query:
            print("How Many Percent you want change")
            speak("How Many Percent you want change")
            percentage = takeCommand().lower()
            percentage = percentage.replace("%", "")
            print(percentage)
            try:
                sbc.set_brightness(int(percentage))
            except Exception as e:
                speak("Wrong value")
            continue
    #    ==============================================
    #    ==============================================
    #    ==============================================

        elif not query == "none":
            speak(f"Searching {query}")
            try:
                results = wikipedia.summary(query, sentences=2)
                print(results)
                speak(results)

            except Exception as e:
Exemplo n.º 7
0
            ctypes.windll.user32.SystemParametersInfoW(20, 0,
                                                       "E:\\munal\\munal.JPG",
                                                       0)
            speak("Background changed succesfully")

        elif 'lock window' in query or 'lock my window' in query or 'lock my laptop' in query or 'lock my computer' in query:
            speak("locking the device")
            ctypes.windll.user32.LockWorkStation()

        # END Ctypes

    # Brightness Control
        elif "brightness" in query:
            old = sbc.get_brightness()
            if "increase" in query or "raise" in query:
                sbc.set_brightness(old + 25)
                speak(f"increasing brightness")
            elif "max" in query:
                sbc.set_brightness(100)
                speak(f"maximum brightness")
            elif "decrease" in query or "lower" in query:
                speak(f"decreasing brightness")
                sbc.set_brightness(old - 25)
            elif "min" in query:
                speak(f"Mnimun brightness")
                sbc.set_brightness(0)
            else:
                speak(f"Current brightness is {old}")

        #datetime
Exemplo n.º 8
0
        if args.get:
            values = SBC.get_brightness(**kw)
            try:monitors = SBC.list_monitors(**kw)
            except:monitors = None
            if monitors == None:
                print(values)
            else:
                values = [values] if type(values) is int else values
                if args.display == None or type(values)==list:
                    for i in range(len(monitors)):
                        try:print(f'{monitors[i]}: {values[i]}{"%" if values[i]!=None else ""}')
                        except IndexError:break
                else:
                    print(f'Display {args.display}: {values}')
        elif args.set!=None:
            SBC.set_brightness(args.set, **kw)
        elif args.fade!=None:
            SBC.fade_brightness(args.fade, **kw)
        elif args.version:
            print(SBC.__version__)
        elif args.list:
            monitors = SBC.list_monitors(**kw)
            if len(monitors) == 0:
                print('No monitors detected')
            else:
                for i in range(len(monitors)):
                    print(f'Display {i}: {monitors[i]}')
        else:
            print("No valid arguments")
Exemplo n.º 9
0
    RATE = 44100

    stream = p.open(format=FORMAT,
                    channels=CHANNELS,
                    rate=RATE,
                    input=True,
                    output=True,
                    frames_per_buffer=CHUNK)
    stream.start_stream()
    while stream.is_active():
        frames = []
        for i in range(0, int(RATE / CHUNK)):
            data = stream.read(CHUNK)
            frames.append(data)
            wf = wave.open("audioSample.wav", 'wb')
            wf.setnchannels(CHANNELS)
            wf.setsampwidth(p.get_sample_size(FORMAT))
            wf.setframerate(RATE)
            wf.writeframes(b"".join(frames))
            wf.close()

        sound = AudioSegment.from_file("audioSample.wav", format="wav")
        rms = sound.rms
        print(rms)
        if rms > 1000:
            print('auditory anomaly detected')
            print('current brightness:')
            print(sbc.get_brightness())
            print('brightness set to: 100%')
            sbc.set_brightness(100)
Exemplo n.º 10
0
 def on_value_change(self, instance, value):
     try:
         sbc.set_brightness(value)
     except:
         pass
Exemplo n.º 11
0
        continue  # ignore empty lines

    if (line.find("command: landscape") != -1):
        if not landscape:
            try:
                monitor.set_landscape()
                landscape = True
            except Exception:
                pass

    if (line.find("command: portrait") != -1):
        if landscape:
            try:
                monitor.set_portrait_flipped()
                landscape = False
            except Exception:
                pass

    if (line.find("brightness: ") != -1):
        cbr = -1
        try:
            cbr = sbc.get_brightness(display=0)
        except Exception:
            pass

        nbr = int(line.replace("brightness: ", ""))
        if (nbr != cbr):
            try:
                sbc.set_brightness(nbr, display=0)
            except Exception:
                pass
Exemplo n.º 12
0
 def check_status(self):
     self.statusThread = threading.Timer(0.2, self.check_status)
     self.statusThread.start()
     for key in self.currentDetectors:
         if isinstance(key, extremity_trigger.ExtremityTrigger):
             eventType = self.currentDetectors.get(key)[1]
             eventContent = self.currentDetectors.get(key)[2]
             if key.status == 1:
                 self.records[1][key.triggerName] = (
                     key.pos, self.records[1][key.triggerName][1] + 0.2)
                 if eventType == "keypress":
                     pydirectinput.keyDown(eventContent)
                     key.isPressed = True
                 elif eventType == "mouse":
                     if eventContent == "click":
                         pydirectinput.click()
                     elif eventContent == "move-left":
                         pydirectinput.move(-1, None)
                     elif eventContent == "move-right":
                         pydirectinput.move(1, None)
                     elif eventContent == "move-up":
                         pydirectinput.move(None, -1)
                     elif eventContent == "move-down":
                         pydirectinput.move(None, 1)
                 elif eventType == "brightness":
                     sbc.set_brightness(100)
             elif key.status == 0 and key.isPressed == True:
                 if eventType == "keypress":
                     pydirectinput.keyUp(eventContent)
                     key.isPressed = False
             else:
                 if eventType == "brightness":
                     sbc.set_brightness(-25)
         else:
             eventType = self.currentDetectors.get(key)[0]
             eventContent = self.currentDetectors.get(key)[1]
             if key.status == 1 and self.isMoving:
                 self.records[0][
                     key.motionType] = self.records[0][key.motionType] + 0.2
                 if eventType == "keypress":
                     pydirectinput.keyDown(eventContent)
                     key.isPressed = True
                     # self.t0 = round(time()*1000)
                     # self.testingLog.write("KeyPressed:"+str(self.t0) + "\n")
                 elif eventType == "mouse":
                     if eventContent == "click":
                         pydirectinput.click()
                     elif eventContent == "move-left":
                         pydirectinput.move(-1, None)
                     elif eventContent == "move-right":
                         pydirectinput.move(1, None)
                     elif eventContent == "move-up":
                         pydirectinput.move(None, -1)
                     elif eventContent == "move-down":
                         pydirectinput.move(None, 1)
                 elif eventType == "brightness":
                     sbc.set_brightness(100)
             elif (not self.isMoving
                   or key.status == 0) and key.isPressed == True:
                 # self.t0=round(time()*1000)
                 # self.testingLog.write("KeyReleased:" + str(self.t0) + "\n")
                 if eventType == "keypress":
                     pydirectinput.keyUp(eventContent)
                     key.isPressed = False
             else:
                 if eventType == "brightness":
                     sbc.set_brightness(-25)
Exemplo n.º 13
0
    def runCasey(self):
        wishMe()
        while True:
            self.query = self.takeCommand()

            if 'wikipedia' in self.query:
                speak('Searching in Wikipedia...')
                print('Searching in Wikipedia...')
                self.query = self.query.replace("wikipedia", "")
                results = wikipedia.summary(self.query, sentences=2)
                speak("According to Wikipedia")
                print("According to Wikipedia")
                speak(results)
                print(results)

            elif 'play song' in self.query or 'song' in self.query:
                speak("Which song I should play")
                song = self.takeCommand()
                song_result = "playing ", song
                speak(song_result)
                print(song_result)
                pywhatkit.playonyt(song)

            elif 'screenshot' in self.query:
                image = pyautogui.screenshot()
                digits = [i for i in range(0, 10)]
                imageName = ""
                for i in range(6):
                    index = math.floor(random.random() * 10)
                    imageName += str(digits[index])
                image.save("C:\\Users\\vijin\\Pictures\\Screenshots\\" +
                           imageName + ".png")
                os.startfile("C:\\Users\\vijin\\Pictures\\Screenshots\\" +
                             imageName + ".png")

            elif 'open youtube' in self.query:
                webbrowser.open("youtube.com")

            elif 'open google' in self.query:
                webbrowser.open("google.com")

            elif 'open stackoverflow' in self.query:
                webbrowser.open("stackoverflow.com")

            elif 'open facebook' in self.query:
                webbrowser.open("facebook.com")

            elif 'open instagram' in self.query:
                webbrowser.open("instagram.com")

            elif 'open wikipedia' in self.query:
                webbrowser.open("wikipedia.com")

            elif 'increase volume' in self.query:
                pyautogui.press("volumeup")
                speak("Volume increased")
                print("Volume increased")

            elif 'decrease volume' in self.query:
                pyautogui.press("volumedown")
                speak("Volume decreased")
                print("Volume decreased")

            elif 'close chrome' in self.query:
                os.system("taskkill /f /im " + "chrome.exe")
                speak("Closed Chrome Browser")
                print("Closed Chrome")

            elif 'take photo' in self.query or 'photo' in self.query:
                cam = cv2.VideoCapture(0)

                cv2.namedWindow("test")
                speak(
                    "Press Space Bar to click photo and Escape button for closing the window"
                )

                img_counter = 0

                while True:
                    ret, frame = cam.read()
                    if not ret:
                        print("failed to grab frame")
                        break
                    cv2.imshow("test", frame)

                    k = cv2.waitKey(1)
                    if k % 256 == 27:
                        speak("Closing Camera")
                        print("Escape hit, closing...")
                        break
                    elif k % 256 == 32:
                        img_name = "opencv_frame_{}.png".format(img_counter)
                        cv2.imwrite(img_name, frame)
                        speak("Taking Photo")
                        print("Taking photo")
                        print("{} written!".format(img_name))
                        speak("Took Photo")
                        print("Took Photo")
                        img_counter += 1

                cam.release()

                cv2.destroyAllWindows()

            elif 'record video' in self.query or 'video' in self.query:
                speak(
                    "The video will be recorded automatically, press the q button in keyboard to stop recording"
                )
                cap = cv2.VideoCapture(0)
                out = cv2.VideoWriter('output.avi',
                                      cv2.VideoWriter_fourcc(*"MJPG"), 30,
                                      (640, 480))
                while (cap.isOpened()):
                    ret, frame = cap.read()
                    if ret:

                        out.write(frame)

                        cv2.imshow('frame', frame)
                        if cv2.waitKey(1) & 0xFF == ord('q'):
                            break
                    else:
                        break
                cap.release()
                out.release()
                cv2.destroyAllWindows()

            elif 'mute' in self.query:
                pyautogui.press("volumemute")

            elif 'time' in self.query:
                strTime = datetime.datetime.now().strftime("%H:%M:%S")
                speak(f"Sir, the time is {strTime}")
                print(strTime)

            elif 'date' in self.query:
                strDate = str(datetime.date.today())
                todayDate = "Today's date is ", strDate
                speak(todayDate)
                print(todayDate)

            elif 'open visual studio' in self.query:
                speak("Opening VS Code")
                print("Opening VS code")
                codePath = "C:\\Users\\vijin\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe"
                os.startfile(codePath)

            elif 'open word' in self.query:
                speak("Opening Microsoft Word")
                print("Opening Microsoft Word")
                wordPath = "C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Microsoft Office\\Microsoft Office Word 2007"
                os.startfile(wordPath)

            elif 'open excel' in self.query:
                speak("Opening Microsoft Excel")
                print("Opening Microsoft Excel")
                excelPath = "C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Microsoft Office\\Microsoft Office Excel 2007"
                os.startfile(excelPath)

            elif 'open media player' in self.query:
                speak("Opening VLC Media Player")
                print("Opening VLC Media Player")
                vlcPath = "C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\VideoLAN\\VLC media player"
                os.startfile(vlcPath)

            elif 'email' in self.query:
                contacts = {
                    "vijin": "*****@*****.**",
                    "joker": "*****@*****.**"
                }
                print("To whom should I send the email")
                speak("To whom should I send the email")
                to = self.takeCommand()
                to = to.replace(" ", "")
                print(to)
                x = 0
                for key, value in contacts.items():
                    if key == to:
                        to = value
                        print("What Message should I send")
                        speak("What message should I send")
                        message = self.takeCommand()
                        sendEmail(to, message)
                        x = x + 1

                if x > 0:
                    print("Email send successfully")
                else:
                    print("Couldn't find the contact")

            elif 'increase brightness' in self.query:
                current_brightness = sbc.get_brightness()
                if current_brightness > 90:
                    speak(
                        "Brightness is at it's highest level. Can't increase brightness"
                    )
                    print(
                        "Brightness is at it's highest level. Can't increase brightness"
                    )
                else:
                    new_brightness = current_brightness + 10
                    print(new_brightness)
                    sbc.set_brightness(new_brightness)
                    updated_brightness = "Brightness increased to ", new_brightness
                    print(updated_brightness)
                    speak(updated_brightness)

            elif 'decrease brightness' in self.query:
                current_brightness = sbc.get_brightness()
                if current_brightness < 10:
                    speak(
                        "Brightness is at its lowest level. Can't decrease brightness"
                    )
                    print(
                        "Brightness is at its lowest level. Can't decrease brightness"
                    )
                else:
                    new_brightness = current_brightness - 10
                    print(new_brightness)
                    sbc.set_brightness(new_brightness)
                    updated_brightness = "Brightness decreased to ", new_brightness
                    print(updated_brightness)
                    speak(updated_brightness)

            elif 'shut down' in self.query:
                speak("shutting down")
                print("Shutting down")
                os.system('shutdown -s -t 0')

            elif 'sleep' in self.query:
                speak("Hibernating system")
                print("Hibernating system")
                os.system("rundll32.exe powrprof.dll,SetSuspendState 0,1,0")

            elif 'weather' in self.query or 'temperature' in self.query:
                speak("which city's temperature do you want to look")
                city = self.takeCommand()
                q = "Temperature of ", city
                res = wfapp.query(q)
                print(next(res.results).text)
                speak(next(res.results).text)

            elif 'mathematics' in self.query or 'calculation' in self.query:
                speak("Tell me the problem")
                question = self.takeCommand()
                res = wfapp.query(question)
                print(next(res.results).text)
                speak(next(res.results).text)

            elif 'translate' in self.query:
                languages = {
                    "hindi": "hi",
                    "english": "en",
                    "malayalam": "ml",
                    "tamil": "ta"
                }
                dest_lang = ""
                x = 0
                try:
                    speak("In which language do you want me to translate")
                    lang = self.takeCommand()
                    for key, value in languages.items():
                        if key == lang:
                            x = x + 1
                            dest_lang = value
                            break
                    if x > 0:
                        speak("What do you want me to translate")
                        text = self.takeCommand()
                        translator = googletrans.Translator()
                        result = translator.translate(text, dest_lang)
                        print(result.text)
                        translated_audio = gtts.gTTS(result.text,
                                                     lang=dest_lang)
                        translated_audio.save('audio.mp3')
                        playsound.playsound('audio.mp3')
                    else:
                        speak("Couldn't find language")
                except Exception:
                    speak("Couldn't translate")

            elif 'internet speed' in self.query:
                import speedtest
                st = speedtest.Speedtest()
                dl = st.download()
                up = st.upload()
                dl_speed = "download speed=", dl, " bits per second"
                up_speed = "upload speed=", up, " bits per second"
                print(dl_speed)
                print(up_speed)
                speak(dl_speed)
                speak(up_speed)

            elif 'joke' in self.query:
                import pyjokes
                jokes = pyjokes.get_jokes(language="en", category="all")
                r1 = random.randint(0, 100)
                joke = jokes[r1]
                speak(joke)
                print(joke, sep="\n")

            elif 'send message' in self.query:
                account_sid = 'your sid'
                auth_token = 'your auth_token'
                client = Client(account_sid, auth_token)
                speak("What do you want me to send?")
                print("What do you want me to send?")
                body = self.takeCommand()

                message = client.messages \
                    .create(
                    body = body,
                    from_='from number',
                    to ='to number'
                )
                print(message.sid)
                speak("Message sent")
                print("Message sent")

            elif 'news' in self.query or 'headlines' in self.query:
                news_url = "https://news.google.com/news/rss"
                Client = urlopen(news_url)
                xml_page = Client.read()
                Client.close()
                soup_page = soup(xml_page, "xml")
                news_list = soup_page.findAll("item")
                for i in range(1, 10):
                    print(news_list[i].title.text)
                    speak(news_list[i].title.text)
                    print(news_list[i].pubDate.text)
Exemplo n.º 14
0
				file.write(note)
			else:
				file.write(note)		
		elif "show the note" in query:
			speak("Showing Notes")
			print("J: Showing Notes")
			file = open("jarvis.txt", "r") 
			print(file.read())
			speak(file.read(6))

# BRIGHTNESS
		elif "brightness" in query:
			print('J: How much brightness do you want to set it at')
			speak('How much brightness do you want to set it at')
			number = takeCommand()
			sbc.set_brightness(number)
			speak('Brightness has been set')
			print('* J:Brightness has been set')
# BATTERY
		elif "battery" in query:
			battery = psutil.sensors_battery() 
			percent = battery.percent
			batterypercent=str(percent)+"% Battery remaining"
			speak(batterypercent)
			print('J:'+ batterypercent)
			if percent <=10:
				speak('Please plug in the laptop')
# EXIT		
		elif 'exit' in query or 'quit' in query or 'bye' in query:
			speak('Exiting sir ! Have a nice day !')
			print("Exiting sir! Have a nice day !")
Exemplo n.º 15
0
# importing the module
import screen_brightness_control as sbc

# get current brightnessvalue
print(sbc.get_brightness())

#set brightness to 50%
sbc.set_brightness(90)

print(sbc.get_brightness())
Exemplo n.º 16
0
    img = dec.findhands(img)
    lmlist = dec.getposition(img)
    if len(lmlist) != 0:

        x1, y1 = lmlist[4][1], lmlist[4][2]
        x2, y2 = lmlist[8][1], lmlist[8][2]
        cx, cy = (x1 + x2) // 2, (y1 + y2) // 2
        cv2.circle(img, (x1, y1), 8, (255, 10, 25), cv2.FILLED)
        cv2.circle(img, (x2, y2), 8, (255, 10, 25), cv2.FILLED)
        cv2.line(img, (x1, y1), (x2, y2), (255, 0, 255), 2)
        cv2.circle(img, (cx, cy), 5, (255, 0, 255), cv2.FILLED)

        leng = math.hypot(x2 - x1, y2 - y1)
        # vol = np.interp(leng, [20, 185], [minvol, maxvol])
        volbar = np.interp(leng, [20, 185], [400, 150])
        volpar = np.interp(leng, [20, 185], [0, 100])
        sbc.set_brightness(int(volpar))
        # volume.SetMasterVolumeLevel(vol, None)
        # print(vol)
        # print(leng)
        if leng < 20:
            cv2.circle(img, (cx, cy), 5, (0, 255, 0), cv2.FILLED)
    cv2.rectangle(img, (70, 150), (85, 400), (0, 0, 255), 2)
    cv2.rectangle(img, (70, int(volbar)), (85, 400), (0, 0, 255), cv2.FILLED)
    cv2.putText(img, f"{int(volpar)}%", (60, 50),
                cv2.FONT_HERSHEY_SCRIPT_SIMPLEX, 1, (0, 0, 255), 3)

    # print(lmlist)
    cv2.imshow("video", img)
    cv2.waitKey(1)
Exemplo n.º 17
0
import argparse
import screen_brightness_control as SBC

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-s',
                        '--set',
                        type=int,
                        help='set the brightness to this value')
    parser.add_argument('-g',
                        '--get',
                        action='store_true',
                        help='get the current screen brightness')
    parser.add_argument('-f',
                        '--fade',
                        type=int,
                        help='fade the brightness to this value')

    args = parser.parse_args()

    if args.get:
        print(SBC.get_brightness())
    elif args.set != None:
        SBC.set_brightness(args.set)
    elif args.fade != None:
        SBC.fade_brightness(args.fade)
    else:
        print("No valid arguments")
    lmList = []
    if results.multi_hand_landmarks:
        for handlandmark in results.multi_hand_landmarks:
            for id,lm in enumerate(handlandmark.landmark):
                h,w,_ = img.shape
                cx,cy = int(lm.x*w),int(lm.y*h)
                lmList.append([id,cx,cy]) 
            mpDraw.draw_landmarks(img,handlandmark,mpHands.HAND_CONNECTIONS)
    
    if lmList != []:
        x1,y1 = lmList[4][1],lmList[4][2]
        x2,y2 = lmList[8][1],lmList[8][2]

        cv2.circle(img,(x1,y1),4,(255,0,0),cv2.FILLED)
        cv2.circle(img,(x2,y2),4,(255,0,0),cv2.FILLED)
        cv2.line(img,(x1,y1),(x2,y2),(255,0,0),3)

        length = hypot(x2-x1,y2-y1)

        bright = np.interp(length,[15,220],[0,100])
        print(bright,length)
        sbc.set_brightness(int(bright))
        
        # Hand range 15 - 220
        # Brightness range 0 - 100

    cv2.imshow('Image',img)
    if cv2.waitKey(1) & 0xff==ord('q'):
        break
Exemplo n.º 19
0
def set_brightness(brightness):
    try:
        sbc.set_brightness(brightness)
    except sbc.ScreenBrightnessError as error:
        print(error)
import serial
from serial.tools import list_ports

slider_trinkey_port = None
ports = list_ports.comports(include_links=False)
for p in ports:
    if p.pid is not None:
        print("Port:", p.device, "-", hex(p.pid), end="\t")
        if p.pid == 0x8102:
            slider_trinkey_port = p
            print("Found Slider Trinkey!")
            trinkey = serial.Serial(p.device)
            break
else:
    print("Did not find Slider Trinkey port :(")
    sys.exit()

curr_brightness = sbc.get_brightness()

while True:
    x = trinkey.readline().decode('utf-8')
    if not x.startswith("Slider: "):
        continue

    val = int(float(x.split(": ")[1]))

    if val != curr_brightness:
        print("Setting brightness to:", val)
        sbc.set_brightness(val)
        curr_brightness = sbc.get_brightness()
Exemplo n.º 21
0
            while True:  # infinite loop starts to make the program running until time matches alarm time

                # ringing alarm + execution condition for alarm
                if alarm_hour == datetime.datetime.now(
                ).hour and alarm_minutes == datetime.datetime.now().minute:

                    print("\nIt's the time!")
                    winsound.PlaySound("SystemQuestion", winsound.SND_ALIAS)
                    winsound.PlaySound("SystemQuestion", winsound.SND_ALIAS)
                    winsound.PlaySound("SystemQuestion", winsound.SND_ALIAS)
                    break

        elif "brightness" in query:
            ans = "no"
            curr_brightness = sbc.get_brightness()
            while (ans != "yes"):
                speak("How much brightness do you want?")
                try:
                    br = takeCommand()
                    sbc.set_brightness(br)
                    speak("Do you want this much ??")
                    ans = takeCommand().lower()
                    if (ans == "no"):
                        sbc.set_brightness(curr_brightness)
                    elif (ans == "yes"):
                        speak(f"brightness has been set to {br}")
                except:
                    speak("Please speak clearly")
                    ans = "no"
            print(curr_brightness)