# (C) 2020 by Florian Stöhr <ich@florian-stoehr.de>
import ctypes
import time

# Program to keep the computer awake and MS-Teams in the "green"
# state. Works by moving the mouse curser 1 pixel to the right
# or left once a minute if no activity took place. Also tells the
# system that no sleep mode should be entered. Will avoid autolock
# as well.

# Alternate between forward- and backward motion of the cursor
forward = False

# Record position and track seconds since last move
loopcount = 0
last_x = -1
last_y = -1

# Some constants needed
ES_CONTINUOUS = 0x80000000
ES_SYSTEM_REQUIRED = 0x00000001
ES_DISPLAY_REQUIRED = 0x00000002

# Type required for cursor pos
class POINT(ctypes.Structure):
    _fields_ = [("x", ctypes.c_long), ("y", ctypes.c_long)]

# Ensure no system sleep/lock
ctypes.windll.kernel32.SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED |  ES_DISPLAY_REQUIRED)

while 1:
    # Get the current cursor position
    pos = POINT()
    ctypes.windll.user32.GetCursorPos(ctypes.byref(pos))

    # If it differs from the last known position, update the
    # last known position and reset the counter - we don't need
    # to do anything as there seems to be user input (or program
    # start)
    if pos.x != last_x or pos.y != last_y:
        last_x = pos.x
        last_y = pos.y
        loopcount = 0
    else:
        loopcount += 1

        # If there was no motion for 60 seconds, fake a motion event
        # and also ensure the system will not go to sleep/lock
        if loopcount == 60:
            loopcount = 0

            # Move back and forth, alternating
            if forward:
                last_x += 1
            else:
                last_x -= 1

            # Reverse direction
            forward = not forward

            # Set new position
            ctypes.windll.user32.SetCursorPos(last_x, last_y)

    # Next check in 1 second
    time.sleep(1)
