-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
80 lines (74 loc) · 2.93 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
"""
Simple TCP Server Script that keeps a TCP Server running in order for NodeRed to connect and put PC into sleep mode
"""
import logging
import os
import socket
import sys
import time
import pidfile
# Desktop Credentials
HOST = "192.168.0.101"
PORT = 60000
PROJECT_PATH = (
"C:/Users/smgib_161/Documents/Projects/Sleep-and-Wake-On-LAN-Node-Red-System/"
)
MAX_ERRORS = 5
# Logger Setup
logger = logging.getLogger("SOL_Logger")
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler(PROJECT_PATH + "SOL.log")
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
fh.setFormatter(formatter)
fh.setLevel(logging.DEBUG)
logger.addHandler(fh)
try:
with pidfile.PIDFile():
logger.info('Starting Sleep on LAN Script')
except pidfile.AlreadyRunningError:
logger.error('Sleep on LAN Script already running, Aborting!')
sys.exit(-1)
ERROR_COUNT = 0
while True:
if ERROR_COUNT > MAX_ERRORS:
logger.error(f'Sleep on LAN Script reached max error count {MAX_ERRORS}')
logger.error("System Exiting")
sys.exit(-2)
try:
while True:
logger.info("Looping Round and creating new socket")
# Create a new Socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
logger.info(f"Attempting to bind on port {PORT}")
sock.bind((HOST, PORT))
logger.info(f"Binded on port {PORT}")
logger.info(f"Attempting to listen on port {PORT}")
ERROR_COUNT = 0
sock.listen()
logger.info("Listening on Port 60000")
conn, addr = sock.accept()
logger.info("Accepted Connection")
sockFile = conn.makefile()
# Decode Message and perform selected operation
with sockFile:
message = sockFile.readline()
logger.debug(message.strip())
message = message.strip()
strings = message.split(":")
if (strings[0]) == "state":
if (strings[1]) == "off":
logger.info("Closing socket")
sock.close()
logger.info("Turning PC off")
os.system("Rundll32.exe Powrprof.dll,SetSuspendState Sleep") # Put PC to Sleep NOT Hibernate
# os.system("shutdown /s /t 0")
else:
logger.info("Closing socket")
sock.close()
except Exception as e:
logger.error(e)
logger.warning("Python code has reached end of script, "
"the code will no longer talk to Node-Red")
logger.info(f"Attempting to restart loop! Error Number: {ERROR_COUNT}")
time.sleep(5) # Sleep for 5 seconds before restarting loop, the ip address might not exist yet
ERROR_COUNT = ERROR_COUNT+1