How to know the status of monitor is on or off in python?
I would like to receive a beep notification every 50 minutes of every hour like this:
import datetime
import time
import winsound
frequency = 2500 # Set Frequency To 2500 Hertz
duration = 200 # Set Duration To 1000 ms == 1 second
while True:
# If the monitor is Black by sleep mode
if ???:
time.sleep(60)
continue
now = datetime.datetime.now()
if now.minute == 50:
print(now)
winsound.Beep(frequency, duration)
time.sleep(60)
However, I don't want to receive a beep notification when the monitor is off because the monitor is on when I'm working, and the monitor is off because it's in power saving mode when I'm not.
But I don't know how to tell if the monitor is on or off.
How can I know the status of my monitor?
best regards!
CodePudding user response:
This question captivated me, in the same vein as the timeless classic "is the fridge light really on if the door is closed"?
In trying to solve this problem, I wondered what a screenshot would appear as if the display was off. So, I tested it out. The idea is that if the screen is black, you can sum the pixels and detect if the value is 0 to determine whether the monitor is on or off.
Unfortunately, it seems like through testing that the screenshot while the monitor is off is not a black screen, at least on my device. You are welcome to test on yours, and I'll post the "solution" anyways if curious.
The solution will probably need to understand the devices connected and the status of them as known by windows, which I would guess could be tricky in python.
import datetime
import time
import winsound
from mss import mss
from PIL import Image
import numpy
def screen_accumulator():
#take screenshot
mss().shot()
#retrieve png
im = Image.open("monitor-1.png")
pix = numpy.array(im)
return(numpy.sum(pix))
frequency = 2500 # Set Frequency To 2500 Hertz
duration = 200 # Set Duration To 1000 ms == 1 second
while True:
# If the monitor is Black by sleep mode
if screen_accumulator()==0:
time.sleep(60)
continue
now = datetime.datetime.now()
if now.minute == 50:
print(now)
winsound.Beep(frequency, duration)
time.sleep(60)