Powershell script to keep computer from going to idle - python

I'm trying to keep my computer from going into idle mode. So I'm trying to write a script that will wiggle my mouse. This is a slightly customized version of a powershell script I found.
param($cycles = 60)
Add-Type -AssemblyName System.Windows.Forms
$screen = [System.Windows.Forms.SystemInformation]::VirtualScreen
for ($i = 0; $i -lt $cycles; $i++) {
Start-Sleep -Seconds 3
[Windows.Forms.Cursor]::Position = "$($screen.Width),$($screen.Height)"
Start-Sleep -Seconds 3
[Windows.Forms.Cursor]::Position = "$($screen.Left),$($screen.Top)"
}
While this does wiggle the mouse it doesn't keep the screen from turning off. So I wrote this: (in python)
import ctypes, time, datetime
mouse_event = ctypes.windll.user32.mouse_event
MOUSEEVENTF_MOVE = 0x0001
print("press ctrl-c to end mouse shaker")
try:
while True:
mouse_event(MOUSEEVENTF_MOVE,25,0,0,0)
time.sleep(1)
mouse_event(MOUSEEVENTF_MOVE,0,25,0,0)
time.sleep(1)
mouse_event(MOUSEEVENTF_MOVE,-25,0,0,0)
time.sleep(1)
mouse_event(MOUSEEVENTF_MOVE,0,-25,0,0)
time.sleep(1)
except KeyboardInterrupt:
pass
This python code will keep my screen from going to sleep and prevents the machine from becoming idle. I believe the issue is because in the powershell scrip I never send the os the "MOUSEEVENTF_MOVE = 0x0001" string. According to the Microsoft website the variable MOUSEEVENTF_MOVE is a flag to signify that the mouse has moved.
Additionally I found this SO question (How i can send mouse click in powershell) that seems to be doing this exact thing but is also clicking, which I don't want. I've tried just commenting out those lines but the "SendImput" I think is expecting some input causing it to fail.
So here is my question. How do I pass the MOUSEEVENTF_MOVE variable in the powershell code? I'm thinking it should have the same effect as my python code.
P.S. This is my first time working with powershell.

Related

how to prevent python from stopping the code after one integer value is read?

I am making a project where an arduino sends a "1" (49) or "2" (50) based on wether the door of a room is open or closed. There is then a python program that then switches the windows open on the computer. The arduino is running fine but the python project doesent work properly. Here is the code:
import pyautogui as pa
import serial
#import time
ser = serial.Serial("COM4", 9600)
data_raw = ser.read()
int_val = int.from_bytes(data_raw, "big")
print(int_val)
if (int_val == 49):
pa.hotkey('win','d') #will switch one desktop to the left
if (int_val == 50):
pa.hotkey('alt','tab') #will switch one desktop to the left
The code can print the correct number sent by the arduino but doesent perform the correct hotkey press. Only the first number sent is read and applied. The code then stops immediatly with the following message:
Process finished with exit code 0
Any help is appreciated.

Sleep function OBSpython and OBSlua

Lua:
obs = obslua
local clock = os.clock
function sleep(n)-- seconds
local t0 = clock()
while clock() - t0 <= n do end
end
function script_description()
return "auto restart replay buffer"
end
function refresh_button()
print('hello')
print('world')
sleep(3)
return nil
end
function script_properties()
local props = obs.obs_properties_create()
local button = obs.obs_properties_add_button(props, "button", "Refresh", refresh_button)
return props
end
Python:
import obspython as obs
import time
import sys
test_hotkey = obs.OBS_INVALID_HOTKEY_ID
def refresh_pressed(props, prop):
print("hello")
time.sleep(4)
print("world")
obs.obs_frontend_replay_buffer_start()
def script_properties():
props = obs.obs_properties_create()
obs.obs_properties_add_button(props, "button", "Refresh", refresh_pressed)
return props
def script_description():
return "stop replay buffer on save and restart it after some time."
The sleep function doesnt work as intended in either of the language. It does work normally if i run it in vscode but not when i run it inside OBS. So, I assume it's OBS's fault. Either way im gonna need someone who has experience with OBS Scripting to help me out with making a script that automatically stops Replay Buffer and starts it after few sec ( 2sec ). Basically clearing the replay buffer making it work exactly like Nvidia's Instant Replay.
Okay, so I am trying to make a script where upon pressing the SAVE REPLAY hotkey the script waits for a few seconds then stops the replay and starts it again after a few seconds. To achieve that I am first trying to make the sleep command work but for some reason, it is giving priority to the sleep command regardless of the order it is in ( in python and Lua). I am new to scripting so I'm just making use of docs and everything I can find. If the script to this already exists or if any one of you is kind enough to script it for me that would be really nice of you. Also, do explain to me why the sleep command is doing that. I figured it's only when I'm using it in obs, otherwise, the sleep command works as intended. The drawback to this is that obs.obs_frontend_replay_buffer_start() obs.obs_frontend_replay_buffer_stop() both commands are run at the same time by OBS so only one command really works ( if replay buffer is active then it stops and vice versa ) it doesn't really restart which it should do

Tkinter Window won't open when launched from CMD/Terminal or Python Shell?

I've seen other questions posted along this line but I have a mainloop() function in my program which for most people seems to be the usual fix.
When attempting to launch the program from a command line prompt or terminal or just by double pressing to open it as a python shell on windows it briefly shows the command window and closes instantly. This happens on Windows 11 and Ubuntu. Unsure what is causing it see attached a photo of what is happening.
The CMD Prompt just flashes up and instantly closes with a similar occurrence on Ubuntu. There are print() functions in the script of which I see none running. I'd also like to mention that the program launches absolutely fine from Python IDLE - My personal choice of Python IDE.
I do have to add I have got a infinite loop of sorts running in my program code for which I will attach below. I've played around adding "root.update_idletasks()" and "root.update()" to the loop to no avail. I'm unsure of what other actions to take?
The Infinite Loop I have mentioned above is a defined function, being called with the "after" method "root.after(0,main_program_exec)" and then continuously run with another after method " root.after(500,main_program_exec)".
NOTE: Most of the code has been left out as this is an application I'll be using for work. - Sorry about messy code normally others don't have to read it! I also have included all modules imported in the case that one of those could be causing a issue!
CODE SNIPPIT:
from pymodbus.client import ModbusTcpClient
from pymodbus.constants import Endian
from pymodbus.payload import BinaryPayloadDecoder
from tkinter import *
import time
from PIL import ImageTk, Image
from tksheet import Sheet
def main_program_exec():
global client, datatype
root.update_idletasks()
root.update()
if program_mode.get():
pass
else:
a = RegType.returnSelection()
b = StartAdd_Entry_Widget.returnValue()
if b <=0:
b = 1
if b > 9999:
b = 9999
c = Length_Entry_Widget.returnValue()
if c >100:
c = 100
elif c < 1:
c = 1
try:
main_data = client.compile_data(a,c,b,datatype) #Mode, length, starting add, mode
update_table(main_data)
except Exception as e:
print(e)
pass
root.after(500, main_program_exec)
....
root.after(0, main_program_exec)
main loop()

Why would QtSerialPort not read after running more than once or twice?

I am just trying to read values from a QtSerialPort connection to an arduino after a value was went to signify the start. I could have a maximum count in the python code, but that doesn't change the outcome of it getting not reading the println from arduino after running the python script more than once. At first it'll print out 'start', 'to read', and 'V', and maybe again if I run it again soon. But after that, it stops reading after printing out 'start'. Here is the python code.
from PyQt5 import QtCore, QtSerialPort
import sys
app = QtCore.QCoreApplication([])
serial_port = QtSerialPort.QSerialPort('COM3')
serial_port.open(QtCore.QIODevice.ReadWrite)
def handle_ready_read():
print('to read')
while serial_port.canReadLine():
serialrd = serial_port.readLine().data().decode().strip()
print(serialrd)
serial_port.close()
app.quit()
serial_port.readyRead.connect(handle_ready_read)
serial_port.write(bytes([100]))
print('start')
sys.exit(app.exec_())
And here is the arduino code.
int measured;
int counter = 0;
int maxnum = 10;
void setup()
{
Serial.begin(9600);
}
void loop()
{
if(Serial.available() > 0)
{
while(counter < maxnum)
{
Serial.println("V");
counter++;
delay(100);
}
}
}
Any ideas that would explain why it won't read again would be useful. I have to unplug and replug in the arduino each time to get it to read, but avoiding having to do that is preferable. I also notice I can't run a PyQt5 serial port connection after a pyserial connection, with disconnecting the arduino first, but I can run pyserial after a PyQt5 serial port connection, though I don't know if that issue is related somehow.
Edit: I added in the 'to read' print statement in handle_ready_read, which sometimes would print out twice when running the first time, so though there is something to be read, it's not always readable by readline, so I added in to handle_ready_read at the end it,
while serial_port.bytesAvailable():
dataByte = serial_port.readLineData(1)
print(dataByte)
serial_port.close()
app.quit()
which will thus sometimes print out b'V' when that is read instead of just V. But it still doesn't read after one or two tries.
Edit 2: I added a timer and function to check if the bytes were written with,
attempts = []
def check_bytes_written():
print('bytes to write' , serial_port.bytesToWrite())
attempts.append(1)
if len(attempts) > 10:
serial_port.close()
timer.stop()
app.quit()
timer = QtCore.QTimer()
timer.setInterval(50)
timer.timeout.connect(check_bytes_written)
timer.start()
This doesn't print out anything with the first or second try, and then says 'bytes to write 0' with later tries, still not printing out any form of 'V', even though the port and app were ended, unless I still disconnect the arduino and plug it back in (at least the kernal doesn't need to be restarted each time now though). I also added code into the arduino to check if the value written can be used to change the voltage of an output pin, it works and the output voltage is changed each time the python script is run, whether a 'V' is read or not. So I changed the question title a bit and previous text, since it's not really crashing or freezing, it's just not reading what the arduino is printing.
Edit 3: I put if(Serial.available() > 0) { int counter = 0; in the arduino code, instead of initializing the counter at the start, the python code will read from the arduino when rerunning the script (though with a bunch of spaces around the V, or just printing b'\x00' from the readlineData part, but that may be another issue, which is cleared by putting serial_port.clear() before the readyRead, but then either V or b'V' is still printed). So it seems like the python script is not restarting the arduino code, maybe it is an issue with how qserialport closes or opens (like with DTR or RTS), unlike how pyserial does? More is discussed here.
Edit 4: If I add (while initializing the counter at the start in the arduino code, as originally shown, undoing the last edit)
serial_port.setDataTerminalReady(1)
serial_port.setDataTerminalReady(0)
serial_port.setDataTerminalReady(1)
after the serial_port.open statement and run it, it still doesn't print from the serial read (without disconnecting the arduino and reconnecting it first), but then if I comment the DTR sets out, then a V is printed out as expected when running again, no disconnect needed, but then it goes back to not printing V. The same effect occurs using just serial_port.setDataTerminalReady(1), commenting it in/out every other time.
Edit 5: I found that (once it has run properly at least once, by unplugging first or using the method in edit 4), if I put
serial_port.setDataTerminalReady(0)
serial_port.setDataTerminalReady(1)
serial_port.setDataTerminalReady(0)
right before serial_port.close() it can be run again multiple times and print out 'V'. I guess it is resetting the DTR to 0. If there is an explanation of why that needs to happen, that would be good to know.
Is your function logic indented correctly?
To me it looks like you read a single line and immediately close the serial port and quit your app.
Perhaps you intended:
def handle_ready_read():
while serial_port.canReadLine():
serialrd = serial_port.readLine().data().decode().strip()
print(serialrd)
# Close serial port and quit app when no more data is available
serial_port.close()
app.quit()

grab() after device.leds() turns off led

I can read the NUML_LED state using evdev. But if I grab() the device after reading the leds when I exit the program the led is off even though the state is still on as far as the system is concerned.
import evdev
device = evdev.InputDevice('/dev/input/event3')
try:
print(device.leds(verbose=True))
print("Using device:\n" + str(device))
device.grab()
except (KeyboardInterrupt, SystemExit):
pass
If I just do one of grab() OR device.leds() without the other they (as expected) don't turn off. But invoking both messes with the leds.
Edit:
I just realised that if LED_NUML and LED_CAPSL are on when I exit the leds are off but when I press either num_lock or caps_lock the state of the other button gets fixed also.
IE:
- LED_NUML and LED_CAPSL are on
- run script
- LED_NUML and LED_CAPSL are off
- press num_lock turns num_lock off (LED_NUML is already off so it stays off)
- LED_CAPSL turns on
At this time it is not possible. There is an issue in the kernel. As ssieb says on the python evdev issues page about this issue.
When a device is released, all handlers attached to the device get restarted. My guess is that there is some handler that is resetting the LEDs.

Categories

Resources