Sleep function OBSpython and OBSlua - python

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

Related

How to pause/sleep() function without crashing app?

I have an app I'm trying to add website updates to every minute. That part works just fine at the moment. The problem I'm experiencing with this current excerpt of code is that, when I go to close/exit the app, I have to hit the "X" button a few times and it completely crashes and freezes.
If my understanding is correct, I believe that is happening because time.sleep() is still "running" constantly when I try to exit.
How can I run a regular update like this that wont throw the app into a fit when I want to close it? Can someone please help me with a solution here?
I have added just a 5 second sleep in this working example here instead of my intended 60 seconds to save time when you test it.
import time
from threading import Thread
from kivy.app import App
class Test(App):
def build(self):
self.thread_for_update()
def thread_for_update(self):
p1 = Thread(target=lambda: self.check_for_update())
p1.start()
def check_for_update(self):
time.sleep(5)
print("Update")
# Here I'm checking an online data source for changes
# I will also notify user if theres changes
self.thread_for_update()
Test().run()
You could use threading.Timer, and update it in another function.
threading.Timer takes 2 argument, the delay (in seconds) and the function to call.
def check_for_update(self):
Timer(5, self.update).start()
def update(self):
print("Update")
self.thread_for_update()
I think I may have fixed it. when I add p1.daemon = True it seems to exit the program well when I try to exit.

Python/Tkinter: trying to sample a signal and run a timer simultaneously: program freezes. Why?

As mentioned in the title, I am trying to run a timer, updating every second, while sampling a signal (for Raspberry Pi), currently simulating on PC.
The code for the timer works very well by itself, here it comes:
def update_timer(self, nap = 1):
while (self.sw_seconds > 0):
self.sw_seconds -= nap
m, s = divmod(self.sw_seconds, 60)
self.labels["Timer"]['text'] = '%02d:%02d' % (int(m), int(s))
self.labels["Timer"].after(1000, self.update_timer)
Now, the function I use to run simultaneously is:
def repeat_function(self,period,f,*args):
t = time.time()
while self.bool:
f(*args)
t += period
time.sleep(max(t - time.time(),0))
The overall program is lengthy and has been tested to work before calling the repeat_function, but I can fully copy it here if required. Just trying to be concise.
I have tested this configuration by launching the timer (which works by itself) and repeat_function(1.0,print,"Hi there\n"). My program freezes and I have to kill it every time.
Can anyone tell me what is wrong with the "repeat function"? In real life, it will have to capture a signal sample with a frequency of 10 Hz at least, so I cannot imagine this how this can work when it freezes already when asked to print a statement every second
Thank you, indeed, sleep (put the whole app to sleep) is the wrong tool for the job, with Threading it works well.

Is there any way to find boot up time of any windows Application?

Suppose I am using VLC Player and I want to calculate the time it takes to boot using python , is there any way?
I have tried winium automation , but elements load too slowly. I want to get boot up time of my application and it boots in 4-5 seconds , whereas winium usually takes more than that to find the location of element.
If anyone can suggest any better way via backend automation, please comment.
If i understood you right, you need to find time from moment you executed the app to the moment the window appears. You can do that with pygetwindow library. Here's the code:
import pygetwindow as pw
import time
# here's code that executing the program, but i just put comment
start = time.time()
while 1: # waiting until window appears
# getWindowsWithTitle method returns empty list if it didn't found any windows with this name
if pw.getWindowsWithTitle('VLC'): #if it founds the window, loop will break
break
stop = time.time()
result = stop - start # result is time in seconds (type float)
EDIT
You also can detect start of application by checking if amount of windows changed.
import pygetwindow as pw
import time
starting_amount = len(pw.getAllWindows()) # amount of windows
# here's code that executing the program, but i just put comment
start = time.time()
while 1: # waiting until window appears
if len(pw.getAllWindows()) > starting_amount: #if amount of windows is bigger than it was before we executed the program
break
stop = time.time()
result = stop - start # result is time in seconds (type float)
This should work with LD Player

Powershell script to keep computer from going to idle

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.

Thread-Switching in PyDbg

I've tried posting this in the reverse-engineering stack-exchange, but I thought I'd cross-post it here for more visibility.
I'm having trouble switching from debugging one thread to another in pydbg. I don't have much experience with multithreading, so I'm hoping that I'm just missing something obvious.
Basically, I want to suspend all threads, then start single stepping in one thread. In my case, there are two threads.
First, I suspend all threads. Then, I set a breakpoint on the location where EIP will be when thread 2 is resumed. (This location is confirmed by using IDA). Then, I enable single-stepping as I would in any other context, and resume Thread 2.
However, pydbg doesn't seem to catch the breakpoint exception! Thread 2 seems to resume and even though it MUST hit that address, there is no indication that pydbg is catching the breakpoint exception. I included a "print "HIT BREAKPOINT" inside pydbg's internal breakpoint handler, and that never seems to be called after resuming Thread 2.
I'm not too sure about where to go next, so any suggestions are appreciated!
dbg.suspend_all_threads()
print dbg.enumerate_threads()[0]
oldcontext = dbg.get_thread_context(thread_id=dbg.enumerate_threads()[0])
if (dbg.disasm(oldcontext.Eip) == "ret"):
print disasm_at(dbg,oldcontext.Eip)
print "Thread EIP at a ret"
addrstr = int("0x"+(dbg.read(oldcontext.Esp + 4,4))[::-1].encode("hex"),16)
print hex(addrstr)
dbg.bp_set(0x7C90D21A,handler=Thread_Start_bp_Handler)
print dbg.read(0x7C90D21A,1).encode("hex")
dbg.bp_set(oldcontext.Eip + dbg.instruction.length,handler=Thread_Start_bp_Handler)
dbg.set_thread_context(oldcontext,thread_id=dbg.enumerate_threads()[0])
dbg.context = oldcontext
dbg.resume_thread(dbg.enumerate_threads()[0])
dbg.single_step(enable=True)
return DBG_CONTINUE
Sorry about the "magic numbers", but they are correct as far as I can tell.
One of your problems is that you try to single step through Thread2 and you only refer to Thread1 in your code:
dbg.enumerate_threads()[0] # <--- Return handle to the first thread.
In addition, the code the you posted is not reflective of the complete structure of your script, which makes it hard to judge wether you have other errors or not. You also try to set breakpoint within the sub-brach that disassembles your instructions, which does not make a lot of sense to me logically. Let me try to explain what I know, and lay it out in an organized manner. That way you might look back at your code, re-think it and correct it.
Let's start with basic framework of debugging an application with pydbg:
Create debugger instance
Attache to the process
Set breakpoints
Run it
Breakpoint gets hit - handle it.
This is how it could look like:
from pydbg import *
from pydbg.defines import *
# This is maximum number of instructions we will log
MAX_INSTRUCTIONS = 20
# Address of the breakpoint
func_address = "0x7C90D21A"
# Create debugger instance
dbg = pydbg()
# PID to attach to
pid = int(raw_input("Enter PID: "))
# Attach to the process with debugger instance created earlier.
# Attaching the debugger will pause the process.
dbg.attach(pid)
# Let's set the breakpoint and handler as thread_step_setter,
# which we will define a little later...
dbg.bp_set(func_address, handler=thread_step_setter)
# Let's set our "personalized" handler for Single Step Exception
# It will get triggered if execution of a thread goes into single step mode.
dbg.set_callback(EXCEPTION_SINGLE_STEP, single_step_handler)
# Setup is done. Let's run it...
dbg.run()
Now having the basic structure, let's define our personalized handlers for breakpoint and single stepping. The code snippet below defines our "custom" handlers. What will happen is when breakpoint hits we will iterate through threads and set them to single step mode. It will in turn trigger single step exception, which we will handle and disassemble MAX_INSTRUCTIONS amount of instructions:
def thread_step_setter(dbg):
dbg.suspend_all_threads()
for thread_id in dbg.enumerate_threads():
print "Single step for thread: 0x%08x" % thread_id
h_thread = dbg.open_thread(thread_id)
dbg.single_step(True, h_thread)
dbg.close_handle(h_thread)
# Resume execution, which will pass control to step handler
dbg.resume_all_threads()
return DBG_CONTINUE
def single_step_handler(dbg):
global total_instructions
if instructions == MAX_INSTRUCTION:
dbg.single_step(False)
return DBG_CONTINUE
else:
# Disassemble the instruction
current_instruction = dbg.disasm(dbg.context,Eip)
print "#%d\t0x%08x : %s" % (total_instructions, dbg.context.Eip, current_instruction)
total_instructions += 1
dbg.single_step(True)
return DBG_CONTINUE
Discloser: I do not guarantee that the code above will work if copied and pasted. I typed it out and haven't tested it. However, if basic understanding is acquired, the small syntactical error could be easily fixed. I apologize in advanced if I have any. I don't currently have means or time to test it.
I really hope it helps you out.

Categories

Resources