Hi J.M.
Firstly, thanks for this. This is a great approach to the issue.
Secondly, I now have to blame you for a sleepless night last night
. I spent most of last night using your method to try a slightly different approach. To be fair, most of my time was spent getting the task scheduler to work (finicky thing that is).
I have made some mods to your script - I have never programmed with Powershell before so if you see any potential enhancements (eg. not sure how to define constants) please let me know. What I have done is more complex than what you did, but it removes the requirement for steps 1 and 2 in your post. It also removes the (very slim) risk of your PC being left in the wrong power scheme state (eg. if someone turns the PC off before the scheme is reset).
My code for step 3 above uses a bit of C programming embedded in a powershell script:
- Code:
$code=@'
[DllImport("kernel32.dll", CharSet = CharSet.Auto,SetLastError = true)]
static extern void SetThreadExecutionState(uint esFlags);
public static void KeepSystemAwake(uint esFlag)
{
SetThreadExecutionState(esFlag);
}
'@
$keepAwake=Add-Type -memberDefinition $code -name "SystemSleep" -namespace SleepFunctions -passThru
$ES_CONTINUOUS = [uint32]"0x80000000"
$ES_AWAYMODE_REQUIRED = [uint32]"0x00000040"
$ES_DISPLAY_REQUIRED = [uint32]"0x00000002"
$ES_SYSTEM_REQUIRED = [uint32]"0x00000001"
$str = netstat -a -n | select-string -pattern "ESTABLISHED" | select-string -pattern "192.168.0.9\d{1}"
if ($str) {
"$str"
"String is not empty"
$keepAwake::KeepSystemAwake($ES_CONTINUOUS -and $ES_AWAYMODE_REQUIRED)
} else {
"String is null or empty"
$keepAwake::KeepSystemAwake($ES_CONTINUOUS)
}
Instead of setting different power schemes as you have done, I have used the WIN API function
SetThreadExecutionState (see
MSDN page here for details) to tell your PC to enter an
Away Mode state while a connection exists. The
Away Mode state is a special state recommended for media streaming - your PC goes into a partial sleep mode (eg. screen is shut off) but full processor etc is available.
I have tested this and all works well so far. Any feedback most welcome.
Windows XP and Windows Server 2003 users: the above won't work as-is, as these OS's do not support
Away Mode. You need to change the line
$keepAwake::KeepSystemAwake($ES_CONTINUOUS -and $ES_AWAYMODE_REQUIRED) to
$keepAwake::KeepSystemAwake($ES_SYSTEM_REQUIRED) in the above. This will simply stop the PC entering sleep (rather than entering
Away Mode).
ps. @blopa: my code uses "192.168.0.9\d{1}". To illustrate J.M.'s answer to your post, my code matches any IP's in the range 192.168.0.90 to 192.168.0.99. This is where I have statically assigned all of my renderers (eg. my PS3 is on .90 and my Panasonic is on .95)