-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathobsschedulermySQL.py
325 lines (303 loc) · 13.2 KB
/
obsschedulermySQL.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
#!/usr/bin/env python
import sys
import time
import logging
from datetime import datetime
from datetime import timedelta
import socket
import websocket #pip install websocket-client
import hashlib
import base64
import json
import mysql.connector #pip install mysql-connector-python
from mysql.connector import Error
try:
import thread
except ImportError:
import _thread as thread
#MariaDB settings. Port = 3306 or 3307
mysqlconfig = {
'user': 'user',
'password': 'pass',
'host': 'localhost',
'port': '3306',
'database': 'OBSdb',
'raise_on_warnings': True
}
writelog = 0
args = sys.argv[1:]
if len(args):
CW = args[0]
if CW == '-l':
writelog = 1
print ("Logfile will be made.")
if writelog:
logging.basicConfig(filename=time.strftime("%Y%m%d%H%M%S") + '.log', level=logging.INFO)
logging.info('Started')
try:
connection = mysql.connector.connect(**mysqlconfig)
if connection.is_connected():
db_Info = connection.get_server_info()
print("Connected to MySQL Server version ", db_Info)
if writelog:
logging.info(time.strftime("%Y%m%d%H%M%S") + ": Connected to MySQL Server version " + db_Info)
mycursor = connection.cursor(dictionary=True)
mycursor.execute("SELECT * FROM host")
records = mycursor.fetchall()
for row in records:
host = row["hostname"]
port = row["port"]
password = row["pass"]
except Error as e:
print("Error while connecting to MySQL", e)
if writelog:
logging.warning(time.strftime("%Y%m%d%H%M%S") + ": Error while connecting to MySQL" + e)
try:
connectionthread = mysql.connector.connect(**mysqlconfig)
if connectionthread.is_connected():
db_Info = connectionthread.get_server_info()
print("Thread connected to MySQL Server version ", db_Info)
if writelog:
logging.info(time.strftime("%Y%m%d%H%M%S") + ": Thread connected to MySQL Server version " + db_Info)
except Error as e:
print("Error while connecting to MySQL", e)
if writelog:
logging.warning(time.strftime("%Y%m%d%H%M%S") + ": Error while connecting thread to MySQL" + e)
StudioMode = False
obsconnected = False
exporttime = [0,500,1000,1500,2000,2500,3000,3500,4000,4500,5000,5500]
#exporttime = [0,1000,2000,3000,4000,5000] # every hour at mmss. 100 = 1 minute after each hour, 1500 = 15 minutes after each hour.
#[0,1000,2000,3000,4000,5000] = export every 10 minutes
GetAuthRequired = {"request-type" : "GetAuthRequired" ,"message-id" : "1"};
GetStudioModeStatus = {"request-type" : "GetStudioModeStatus" , "message-id" : "GetStudioModeStatus"}
GetSceneList = {"request-type" : "GetSceneList" , "message-id" : "getSceneList"}
GetSourcesList = {"request-type" : "GetSourcesList" , "message-id" : "GetSourcesList"}
GetTransitionList = {"request-type": "GetTransitionList","message-id" : "GetTransitionList"}
while True:
try:
def on_message(ws, message):
data = json.loads(message)
#print (data["message-id"])
#print (data)
global obsconnected
if "error" in data:
if (data["error"] == "Authentication Failed."):
print("Authentication Failed.")
if writelog:
logging.info(time.strftime("%Y%m%d%H%M%S") + ": Authentication Failed.")
ws.keep_running = False
else:
print (data)
message = str(data)
if writelog:
logging.warning(time.strftime("%Y%m%d%H%M%S") + ": " + message)
elif "message-id" in data:
if (data["message-id"] == "GetStudioModeStatus"):
global StudioMode
StudioMode = data["studio-mode"]
elif (data["message-id"] == "getSceneList"):
if not connection.is_connected():
connection.reconnect(attempts=5, delay=0)
mycursor = connection.cursor()
mycursor.execute("TRUNCATE TABLE scenenames")
connection.commit()
mycursor = connection.cursor()
mycursor.execute("TRUNCATE TABLE sourcenames")
connection.commit()
for name in data['scenes']:
scene = name['name']
if not connection.is_connected():
connection.reconnect(attempts=5, delay=0)
mycursor = connection.cursor()
qry = "INSERT INTO scenenames(scene) VALUES('" + scene + "')"
mycursor.execute(qry)
connection.commit()
for name in name['sources']:
sourcename = name['name']
mycursor = connection.cursor()
qry = "INSERT INTO sourcenames(scene,source) VALUES('" + scene + "' , '" + sourcename + "')"
if not connection.is_connected():
connection.reconnect(attempts=5, delay=0)
mycursor.execute(qry)
connection.commit()
elif (data["message-id"] == "GetTransitionList"):
if not connection.is_connected():
connection.reconnect(attempts=5, delay=0)
mycursor = connection.cursor()
mycursor.execute("TRUNCATE TABLE transitionnames")
connection.commit()
for i in data['transitions']:
trans_type = i['name']
if not connection.is_connected():
connection.reconnect(attempts=5, delay=0)
mycursor = connection.cursor()
qry = "INSERT INTO transitionnames(transition) VALUES('" + trans_type + "')"
mycursor.execute(qry)
connection.commit()
elif (data["message-id"] == "SetCurrentTransition"):
print("SetCurrentTransition")
#elif (data["authRequired"]):
elif (data["message-id"] == "1"):
print("Authentication required")
secret = base64.b64encode(hashlib.sha256((password + data['salt']).encode('utf-8')).digest())
auth = base64.b64encode(hashlib.sha256(secret + data['challenge'].encode('utf-8')).digest()).decode('utf-8')
auth_payload = {"request-type": "Authenticate", "message-id": "2", "auth": auth}
ws.send(json.dumps(auth_payload))
obsconnected = True
elif (data["message-id"] == "2"):
print("Login pass")
elif (data["message-id"] == "SetCurrentScene") or (data["message-id"] == "SetSceneItemProperties") or (data["message-id"] == "SetPreviewScene") :
True
else:
print(data)
message = str(data)
if writelog:
logging.warning(time.strftime("%Y%m%d%H%M%S") + ": " + message)
obsconnected = True
elif "update-type" in message:
if (data["update-type"] == "StudioModeSwitched"):
StudioMode = data["new-state"]
def on_error(ws, error):
print(error)
if writelog:
logging.warning(time.strftime("%Y%m%d%H%M%S") + ": " + str(error))
ws.close()
def on_close(ws):
print("On Close Connection error.")
if writelog:
logging.warning(time.strftime("%Y%m%d%H%M%S") + ": On Close Connection error.")
#stop on_open while loop
global obsconnected
obsconnected = False
ws.keep_running = False
time.sleep(30)
def on_open(ws):
def run(*args):
ws.send(json.dumps(GetAuthRequired))
time.sleep(2)
if ws.sock:
ws.send(json.dumps(GetStudioModeStatus))
global obsconnected
weekdays = ("ma","di","wo","do","vr","za","zo") #Dutch
while obsconnected == True:
try:
dayrun = False
currentdtime = time.strftime("%Y%m%d%H%M%S",time.localtime())
timenow = time.strftime("%H:%M:%S",time.localtime())
if not connectionthread.is_connected():
connectionthread.reconnect(attempts=5, delay=0)
mycursor = connectionthread.cursor(dictionary=True)
getqry = "SELECT * FROM schedules WHERE processed = 0"
mycursor.execute(getqry)
records = mycursor.fetchall()
print(time.strftime("%H:%M:%S",time.localtime()))
for row in records:
logrow = str(row)
id = row["id"]
swtime = row["swtime"]
swdate = row["swdate"]
time_object = datetime.strptime(str(swtime), '%H:%M:%S').time()
date_object = datetime.strptime(str(swdate), '%Y-%m-%d').date()
datetime_str = datetime.combine(date_object , time_object)
dtime = datetime_str.strftime("%Y%m%d%H%M%S")
scene = row["scene"]
trans_type = row["transition"]
sourceoff = row["sourceoff"] #source in this scene to switch off
sourceon = row["sourceon"] #source in this scene to switch on
repeattime = row["repeattime"]
scenesourceoff = row["scenesourceoff"]
scenesourceon = row["scenesourceon"]
if timenow == datetime_str.strftime("%H:%M:%S"):
if weekdays[datetime.today().weekday()] in repeattime:
dayrun = True
if currentdtime == dtime or dayrun:
logging.info(time.strftime("%Y%m%d%H%M%S") + ": " + logrow)
if len(sourceon) > 0:
#first set correct scene in preview
message = {"request-type" : "SetPreviewScene" , "message-id" : "SetPreviewScene" , "scene-name" : scenesourceon};
logmessage = str(message)
logging.info(time.strftime("%Y%m%d%H%M%S") + ": " + logmessage)
ws.send(json.dumps(message))
#set source properties
message={"request-type" : "SetSceneItemProperties" , "message-id" : "SetSceneItemProperties" , "scene-name" : scenesourceon , "item" : sourceon , "visible": True };
logmessage = str(message)
logging.info(time.strftime("%Y%m%d%H%M%S") + ": " + logmessage)
ws.send(json.dumps(message))
if len(sourceoff) > 0:
#delay,else to fast for OBS
time.sleep(2)
message = {"request-type" : "SetPreviewScene" , "message-id" : "SetPreviewScene" , "scene-name" : scenesourceoff};
logmessage = str(message)
logging.info(time.strftime("%Y%m%d%H%M%S") + ": " + logmessage)
ws.send(json.dumps(message))
message={"request-type" : "SetSceneItemProperties" , "message-id" : "SetSceneItemProperties" , "scene-name" : scenesourceoff , "item" : sourceoff , "visible": False };
logmessage = str(message)
logging.info(time.strftime("%Y%m%d%H%M%S") + ": " + logmessage)
ws.send(json.dumps(message))
message={"request-type" : "SetCurrentTransition" , "message-id" : "SetCurrentTransition" ,"transition-name":trans_type};
ws.send(json.dumps(message))
message = {"request-type" : "SetCurrentScene" , "message-id" : "SetCurrentScene" , "scene-name" : scene};
ws.send(json.dumps(message))
if not connectionthread.is_connected():
connectionthread.reconnect(attempts=5, delay=0)
mycursor = connectionthread.cursor()
if len(repeattime) > 0 and not dayrun:
if "," in repeattime:
repeattimenew = repeattime.split(',')[0]
repeattimenumber = repeattime.split(',')[1]
if repeattimenumber == "0": #continuous
newdtime = datetime_str + timedelta(minutes=int(repeattimenew))
new_time_object = datetime.time(newdtime)
new_date_object = datetime.date(newdtime)
qry = "UPDATE schedules SET swtime = '" + new_time_object.strftime("%H:%M:%S") + "', swdate ='" + new_date_object.strftime("%Y-%m-%d") + "' WHERE id = " + str(id) + ";"
elif repeattimenumber == "1": #last run was done
qry = "UPDATE schedules SET processed = 1 WHERE id = " + str(id) + ";"
else:
newdtime = datetime_str + timedelta(minutes=int(repeattimenew))
repeattime = repeattimenew + "," + str(int(repeattimenumber) - 1)
new_time_object = datetime.time(newdtime)
new_date_object = datetime.date(newdtime)
qry = "UPDATE schedules SET swtime = '" + new_time_object.strftime("%H:%M:%S") + "', swdate = '" + new_date_object.strftime("%Y-%m-%d") + "', repeattime = '" + repeattime + "' WHERE id = " + str(id) + ";"
else:
newdtime = datetime_str + timedelta(minutes=int(repeattime))
new_time_object = datetime.time(newdtime)
new_date_object = datetime.date(newdtime)
qry = "UPDATE schedules SET swtime = '" + new_time_object.strftime("%H:%M:%S") + "', swdate ='" + new_date_object.strftime("%Y-%m-%d") + "' WHERE id = " + str(id) + ";"
else:
qry = "UPDATE schedules SET processed = 1 WHERE id = " + str(id) + ";"
if not dayrun:
mycursor.execute(qry)
connectionthread.commit()
print("Transition to: " + scene + " at " + time.strftime("%H:%M:%S",time.localtime()))
if writelog:
logging.info(time.strftime("%Y%m%d%H%M%S") + ": Transition to: " + scene + " at " + time.strftime("%H:%M:%S",time.localtime()))
time.sleep(1) #wait for next second.
connectionthread.close()
time.sleep(0.25) #no need 100's loops a second
except Exception:
print("connectionthread error")
connectionthread.close()
if writelog:
logging.warning(time.strftime("%Y%m%d%H%M%S") + ": connectionthread error")
time.sleep(10)
timenow = int(time.strftime("%M%S",time.localtime()))
if timenow in exporttime:
print("export scenes")
ws.send(json.dumps(GetSceneList))
Updatescenes = False
time.sleep(0.25)
if timenow - 10 in exporttime:
print("export transitions")
ws.send(json.dumps(GetTransitionList))
time.sleep(0.25)
thread.start_new_thread(run, ())
if __name__ == "__main__":
#websocket.enableTrace(True)
ws = websocket.WebSocketApp("ws://{}:{}".format(host, port),on_message = on_message,on_error = on_error,on_close = on_close)
ws.on_open = on_open
ws.run_forever()
except Exception:
print("Exception Connection error")
if writelog:
logging.warning(time.strftime("%Y%m%d%H%M%S") + ": Exception Connection error")
time.sleep(10)