-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhitzSaveMonitor.py
176 lines (144 loc) · 6.62 KB
/
hitzSaveMonitor.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
#
# hitzSaveMonitor.py
#
# Monitors the hitz save file and reads in the data, detecting changes.
#
# 1.) Perform an initial read to establish a baseline
# 2.) Set up an observer on the directory containing the save
# 3.) Set up an eventHandler to get a new read to compare to the baseline values
# 4.) Compare to find who played in a game. Should be able to tell from "wins"
# increasing or "consecutivelosses" changing any direction.
# 5.) Log the result
#
import sys, threading
import time
import logging
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from hitzSaveRead import hitzSaveRead
import os, pprint
#FILENAME = 'SLUS_201.40_0.bin'
FILENAME = 'hitzsave'
DIRNAME = '/media/pool/playstation2/VMC/'
OFFSET=46088
# OFFSET = 8 # for a save file directly use 8, for a VMC file use 46088
#FILENAME = 'hitzsave'
#DIRNAME = 'C:\saves'
SECONDS_TO_WAIT_FOR_FILE_COMPLETE=30
players = hitzSaveRead(os.path.join(DIRNAME,FILENAME), OFFSET)
#print players
'''def didPlay(newrecord,oldrecord):
# Get the dictionary of the value differences from the old record to the new record
stats = { key: value-oldrecord[key] for (key, value) in newrecord.iteritems() if key !='name'}
stats['name']=oldrecord['name']
return stats'''
class DictDiffer(object):
"""
Calculate the difference between two dictionaries as:
(1) items added
(2) items removed
(3) keys same in both but changed values
(4) keys same in both and unchanged values
"""
def __init__(self, current_dict, past_dict):
self.current_dict, self.past_dict = current_dict, past_dict
self.set_current, self.set_past = set(current_dict.keys()), set(past_dict.keys())
self.intersect = self.set_current.intersection(self.set_past)
def added(self):
return self.set_current - self.intersect
def removed(self):
return self.set_past - self.intersect
def changed(self):
return set(o for o in self.intersect if self.past_dict[o] != self.current_dict[o])
def unchanged(self):
return set(o for o in self.intersect if self.past_dict[o] == self.current_dict[o])
class SaveChangeEventHandler(FileSystemEventHandler):
def __init__(self):
self.events={}
self.running = True
t = threading.Thread(target=self.checkExpiration)
t.start()
def checkExpiration(self):
#executing on thread
while self.running:
time.sleep(1)
#print "Testing"
for e in self.events.keys():
# test elapsed time since last modification in seconds
#print str(time.time() - self.events[e])
if time.time() - self.events[e] > SECONDS_TO_WAIT_FOR_FILE_COMPLETE:
# file is "complete"
self.events.pop(e, None)
global FILENAME
global DIRNAME
global players
readytoread=1
#test if the file is done being written to, if its not we should get an exception
if readytoread:
playednames = set()
updatedplayers=[]
winteam={'players':[],'score':0}
loseteam={'players':[],'score':0}
#pprint.pprint(players)
#print "*** NEW GAME ***"
newplayers = hitzSaveRead(os.path.join(DIRNAME,FILENAME))
#print newplayers
#
# compare new records to old records
#
#pprint.pprint(newplayers)
d=DictDiffer(newplayers, players)
deleteName=0
if len(d.added())>0:
print "New players: " + ' '.join(i for i in d.added())
for player in d.added():
if player != '':
players[player]={'name':player,'assists':0, 'goals':0, 'hits':0, 'shots':0,
'gamesPlayed':0,'consecutiveLosses':0,'wins':0}
else:
deleteName = 1
playednames = set(d.added().union(d.changed()))
if (len(d.added())+len(d.changed()))!= 6:
print "*** somethings fucky, there weren't 6 players"
pprint.pprint(playednames)
elif deleteName !=1:
print "***NEW GAME***"
print "["
for player in playednames:
oldrecord = players[player]
newrecord = newplayers[player]
currentgamestatschanged = DictDiffer(newrecord, oldrecord).changed()
playeroutput={'name':player,'assists':0, 'goals':0, 'hits':0, 'shots':0,
'gamesPlayed':0,'consecutiveLosses':0,'wins':0}
for key in currentgamestatschanged:
playeroutput[key]+=newrecord[key]-oldrecord[key]
pprint.pprint(playeroutput)
print ","
if newrecord['wins']>oldrecord['wins']:
winteam['players'].append(player)
winteam['score']+=(newrecord['goals']-oldrecord['goals'])
else:
loseteam['players'].append(player)
loseteam['score']+=(newrecord['goals']-oldrecord['goals'])
print "]"
print str(winteam['players'])+' beat '+str(loseteam['players'])+' : '+str(winteam['score'])+' - '+str(loseteam['score'])
players = newplayers
def on_modified(self, event):
self.events[event.src_path] = time.time()
def stop(self):
self.running = False
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO,
format= '%(asctime)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
path = DIRNAME
event_handler = SaveChangeEventHandler()
observer = Observer()
observer.schedule(event_handler, path)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()