-
Notifications
You must be signed in to change notification settings - Fork 1
/
DatabaseRetriever_ver06.py
186 lines (159 loc) · 7.09 KB
/
DatabaseRetriever_ver06.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
##Hamtar all data sedan senaste hamtningen
##behover python 2.7 och MySQL-python installerat
import MySQLdb as mdb
from Tkinter import *
import pickle
from datetime import datetime
from time import strptime
import os
idDict = dict()
idDict["Plugwise.000D6F00003FE5A5"] = "Livningroom"
idDict["Plugwise.000D6F000046957C"] = "Dishwasher"
idDict["Plugwise.000D6F0000469D83"] = "Office"
idDict["Plugwise.000D6F000055138F"] = "Bedroom"
idDict["Plugwise.000D6F0000599D9B"] = "Kettle"
idDict["Plugwise.000D6F000072A183"] = "WashingMachine"
idDict["Plugwise.000D6F000397AA8A"] = "MicrowaveOven"
idDict["Plugwise.000D6F00039745B7"] = "KitchenFan"
idDict["Plugwise.000D6F000397AAFA"] = "Dehumidifier"
idDict["Plugwise.000D6F00039745EF"] = "Refridgerator"
idDict["Plugwise.000D6F00039747EC"] = "Toaster"
idDict["Plugwise.000D6F0001A40370"] = "Mains1"
idDict["Plugwise.000D6F0001A40664"] = "Mains2"
idDict["Plugwise.000D6F0000D31BBE"] = "Mains3"
idDict["Plugwise.Total"] = "TotalEnergy"
invIdDict = {v: k for k, v in idDict.items()}
class Db:
def __init__(self):
pass
def create_gui(self):
self.root = Tk()
self.frame = Frame(self.root)
self.frame.master.title("Database Retreiver")
ws = self.root.winfo_screenwidth()
hs = self.root.winfo_screenheight()
self.frame.master.geometry('%dx%d+%d+%d' % (220, 210, (ws / 2) - (220 / 2), (hs / 2) - (210 / 2)))
self.frame.pack(padx=5, pady=5)
hostLabel = Label(self.frame)
hostLabel.grid(row=1, column=0, pady=3, sticky=W)
hostLabel["text"] = "Host:"
hostEntry = Entry(self.frame)
hostEntry.grid(row=1, column=1, pady=3)
hostEntry["width"] = 20
userLabel = Label(self.frame)
userLabel.grid(row=2, column=0, sticky=W, pady=3)
userLabel["text"] = "User:"
userEntry = Entry(self.frame)
userEntry.grid(row=2, column=1, pady=3)
userEntry["width"] = 20
passLabel = Label(self.frame)
passLabel["text"] = "Password:"
passLabel.grid(row=3, column=0, sticky=W, pady=3)
passEntry = Entry(self.frame)
passEntry["width"] = 20
passEntry.grid(row=3, column=1)
dbLabel = Label(self.frame)
dbLabel["text"] = "Database:"
dbLabel.grid(row=4, column=0, sticky=W, pady=3)
dbEntry = Entry(self.frame)
dbEntry["width"] = 20
dbEntry.grid(row=4, column=1)
tableLabel = Label(self.frame)
tableLabel["text"] = "Table:"
tableLabel.grid(row=5, column=0, sticky=W, pady=3)
tableEntry = Entry(self.frame)
tableEntry["width"] = 20
tableEntry.grid(row=5, column=1)
deviceLabel = Label(self.frame)
deviceLabel["text"] = "Device:"
deviceLabel.grid(row=6, column=0, sticky=W, pady=3)
var = StringVar()
var.set(invIdDict.keys()[0])
#OptionMenu(self.frame, var, tuple(invIdDict.keys())).grid(row=6,column=1)
apply(OptionMenu, (self.frame, var) + tuple(invIdDict.keys())).grid(row=6, column=1)
Button(self.frame, text='Get database',
command=(lambda: self.collect(hostEntry.get(),
userEntry.get(), passEntry.get(), dbEntry.get(),
tableEntry.get(),
var.get(), None))).grid(row=7, column=0, padx=1, columnspan=2)
self.enter=lambda event: self.collect(hostEntry.get(),
userEntry.get(),
passEntry.get(), dbEntry.get(), tableEntry.get(), var.get(), None)
tableEntry.bind('<Return>', self.enter)
self.root.mainloop()
def collect(self, host, user, password, db, table, device, return_list=None):
if return_list is True:
self.data_list = list()
try:
self.root.destroy()
except AttributeError, TclError:
pass
self.lastTimeTag = "0000-00-00 00:00:00"
dataCollection = list()
file_not_found = 0
try:
old = open(str(device) + ".csv", "rb")
print "Previous data found, will merge with new"
lines = old.readlines()
if return_list is True:
for line in lines:
#lastTimeTag = datetime.strptime(tempList[0], "%Y-%m-%d %H:%M:%S")
self.data_list.append(line)
old.close()
newfile = open(str(device) + ".csv", "a")
#for line in lines:
# newfile.write(line)
#ast.litheral.eval()
try:
tempList = lines[-1][:lines[-1].find(";")]
print "temP: ", tempList
#lastTimeTag = datetime.strptime(tempList[0], "%Y-%m-%d %H:%M:%S")
self.lastTimeTag = tempList
print "timetag: ", self.lastTimeTag
except IndexError:
newfile.close()
os.remove(str(device) + ".csv")
file_not_found = 1
except IOError:
file_not_found = 1
print "No previous data, complete database will be retrieved.."
if file_not_found:
newfile = open(str(device) + ".csv", "wb")
print "Connecting to database with Host:" + str(host) + " User:" + str(user) + " Password:" + str(password)+ \
" DB:" + str(db) + " Table:" + str(table) + " Device:" + str(device)
try:
conn = mdb.connect(host=str(host), user=str(user), passwd=str(password), db=str(db))
except Exception as e:
print e
return
print "Connected.."
with conn:
cur = conn.cursor()
sql = "SELECT * FROM {0} WHERE (id='{1}' OR id='{2}') AND time>'{3} ORDER BY time'".format(table, str(invIdDict[device]),
str(idDict[invIdDict[device]]),
self.lastTimeTag)
#sql="SELECT * FROM {0} WHERE time>'{1}'".format(table,lastTimeTag)
print "Using: " + sql
cur.execute(sql)
rows = cur.fetchall()
if return_list is None:
for row in rows:
#print row[0]
newfile.write(str(row[0].__str__()) + ";" + str(row[3]) + "\n")
#print row
newfile.close()
else:
for row in rows:
self.data_list.append(str(row[0].__str__()) + ";" + str(row[3]))
newfile.write(str(row[0].__str__()) + ";" + str(row[3]) + "\n")
newfile.close()
return self.data_list
#newfile.close()
#os.remove(str(device) + ".csv")
#return
if __name__ == '__main__':
d = Db()
#d.create_gui()
lista = d.collect("mysql315.loopia.se", "kthstud@a68445", "2013IIstud!#", "aktivahuset_com", "meterevents", "Office", True)
#print lista
print "Done"