-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathDatabase.py
More file actions
235 lines (203 loc) · 7.64 KB
/
Database.py
File metadata and controls
235 lines (203 loc) · 7.64 KB
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
import psycopg2
import datetime
from datetime import datetime
from psycopg2.extensions import AsIs
from socketForRTK.Server import Server
class Database:
"""
Class managing the insertion of data in the postgresql database.
"""
def __init__(self, host, dbname, user, password, port, robotSerialNumber, serveurPort):
"""
Inits Database with the host of the database, its name, the database-user name, its password and its port of connexion.\n
The roboSerialNumber is optionnal and serveurPort is the connection port of RTK server.\n
Create an instance of Server and APIWeather.
:param host: Path of the database host
:param dbname: Name of the database
:param user: Name of the user used for the connection to database
:param password: Password of the database user
:param port: Connection port for the database
:param robotSerialNumber: optional, used for init the global variable of the robot serial number
:param serveurPort: Connection port of the server that send gps coordinates
**Authors of this class :** SOULLARD Thomas and TOURNEUR Hugo and CHENNUAUD Emmanuel and LAMBERT Vincent. \n
"""
self.host = host
self.dbName = dbname
self.user = user
self.password = password
self.port = port
self.robotSerialNumber = robotSerialNumber
self.sessionID = None
self.server = Server(int(serveurPort))
self.lastCoordinate = None
def insertRobot(self, serialNumber):
"""
Insert a robot's informations in the database. \n
This method :
* obtain the serial number of the robot,
* send it in the Database by a POSTGRESQL Request.
:param serialNumber: the serial number of a robot.
"""
# INSERT INTO robot(serial_number) SELECT N189563 WHERE NOT EXISTS (SELECT serial_number FROM robot WHERE serial_number = N189563);
sql = 'INSERT INTO robot(serial_number) SELECT \'{}\' WHERE NOT EXISTS (SELECT serial_number FROM robot WHERE serial_number = \'{}\');'.format(
self.robotSerialNumber, self.robotSerialNumber)
conn = None
try:
# connect to the PostgreSQL database
conn = psycopg2.connect(dbname=self.dbName, user=self.user, host=self.host, password=self.password)
# create a new cursor
cur = conn.cursor()
# execute the INSERT statement
cur.execute(sql)
# commit the changes to the database
conn.commit()
# close communication with the database
cur.close()
except(Exception, psycopg2.DatabaseError) as error:
print("[Database]")
print(error)
finally:
if conn is not None:
conn.close()
def startSession(self):
"""
Send to the database the start informations of the robot's session. \n
This method :
* format the start date, hour and coordinates,
* put them in a POSTGRESQL request,
* send them in the database.
"""
now = datetime.now().time()
DateSession = str(datetime.now())
Begin_Hour = str(now.hour) + ":" + str(now.minute) + ":" + str(now.second)
coordinate = self.server.getLocation()
coordinateLong = coordinate['latitude']
coordinateLat = coordinate['longitude']
Start_Position = AsIs("'(%s,%s)'" % (coordinateLat, coordinateLong))
sql = """INSERT INTO "session"(date,Start_Position,Begin_Hour,robot)
VALUES(%s,%s,%s,%s) RETURNING id"""
conn = None
try:
# connect to the PostgreSQL database
conn = psycopg2.connect(dbname=self.dbName, user=self.user, host=self.host, password=self.password)
# create a new cursor
cur = conn.cursor()
# execute the INSERT statement
cur.execute(sql, (DateSession, Start_Position, Begin_Hour, self.robotSerialNumber))
# get the generated id back
self.sessionID = cur.fetchone()[0]
# commit the changes to the database
conn.commit()
# close communication with the database
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print("[Database]")
print(error)
finally:
if conn is not None:
conn.close()
def endSession(self):
"""
Complete information of a session with the end hour. \n
This method :
* recover the end hour of a robot session,
* format the hour,
* put it in a POSTGRESQL request,
* send it in the database.
"""
now = datetime.now().time()
End_Hour = str(now.hour) + ":" + str(now.minute) + ":" + str(now.second)
sql = """UPDATE session
SET End_Hour = %s
WHERE id = %s"""
conn = None
try:
# connect to the PostgreSQL database
conn = psycopg2.connect(dbname=self.dbName, user=self.user, host=self.host, password=self.password)
# create a new cursor
cur = conn.cursor()
# execute the INSERT statement
cur.execute(sql, (End_Hour, self.sessionID))
# commit the changes to the database
conn.commit()
# close communication with the database
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print("[Database]")
print(error)
finally:
if conn is not None:
conn.close()
def insertResults(self, angle):
"""
Insert the results of an angle measure on the robot in the database with the actual weather. \n
This method :
* recover and format the hour of measure,
* recover the coordinates where the robot was,
* call the APIWeather class to get the weather,
* recover the angle measured,
* send them in the Database with a POSTGRESQL request.
* calculate the robot orientation vector and send it to database (qgis)
:param angle: the angle measured by the angular captor
"""
weather = "Wether not specified"
temperature = 0.0
humidity = 0
coordinate = self.server.getLocation()
coordinateLat = coordinate['latitude']
coordinateLong = coordinate['longitude']
# if coordinateLat == 0 and coordinateLong == 0: # TODO: possible fix (request was denied because of broken commits)
# return
idResultat = None
vector_robot_direction = None
sql2 = None
if self.lastCoordinate is not None:
latCompass = coordinateLat - self.lastCoordinate['latitude']
longCompass = coordinateLong - self.lastCoordinate['longitude']
vector_robot_direction = AsIs("'(%s,%s)'" % (longCompass, latCompass))
# A supprimer quand il y aura rtk et weather
now = datetime.now().time()
coordinateStr = AsIs("'(%s,%s)'" % (coordinateLong, coordinateLat))
time_hour = str(now.hour) + ":" + str(now.minute) + ":" + str(now.second)
sql = """INSERT INTO resultat(angle,coordinates,timer_hour,weather,humidity,temperature,session)
VALUES(%s,%s,%s,%s,%s,%s,%s) RETURNING id;"""
if vector_robot_direction is not None:
sql2 = """INSERT INTO qgis(id_resultat,coordinates,angle,session,vector_robot_direction)
VALUES(%s,%s,%s,%s,%s);"""
else:
sql2 = """INSERT INTO qgis(id_resultat,coordinates,angle,session)
VALUES(%s,%s,%s,%s);"""
try:
# connect to the PostgreSQL database
conn = psycopg2.connect(dbname=self.dbName, user=self.user, host=self.host, password=self.password)
# create a new cursor
cur = conn.cursor()
# execute the INSERT statement
cur.execute(sql, (angle, coordinateStr, time_hour, weather, humidity, temperature, self.sessionID,))
idResultat = cur.fetchone()[0]
conn.commit()
if vector_robot_direction is not None:
cur.execute(sql2, (idResultat, coordinateStr, angle, self.sessionID, vector_robot_direction,))
else:
cur.execute(sql2, (idResultat, coordinateStr, angle, self.sessionID,))
# commit the changes to the database
conn.commit()
# close communication with the database
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print("[Database]")
print(error)
finally:
if conn is not None:
conn.close()
self.lastCoordinate = dict(coordinate)
def startServer(self):
"""
This method start the server for reiceve the location.
"""
self.server.start()
def stopServer(self):
"""
This method stop the server.
"""
self.server.exit()