forked from suryan-s/Precio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
endpoints.py
306 lines (285 loc) · 9.92 KB
/
endpoints.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
import datetime
import json
import os
import sqlite3
# import numpy as np
# import pandas as pd
# from keras.callbacks import EarlyStopping, ModelCheckpoint
# from sklearn.model_selection import train_test_split
# from sklearn.preprocessing import LabelEncoder, StandardScaler
# from keras.models import load_model
# from tensorflow.keras.layers import Dense
# from tensorflow.keras.models import Sequential
# {
# "id":"string","
# "name":"Agro",
# "type":"Arable",
# "available":"PMS",
# "stationParameters":["Temperature","Humidity","Pressure","Wind","UV","Light","Rain","Battery Status"],
# "pmsParameters":["Soil Moisture","Soil Temperature/Humidity"]
# }
# model = load_model(os.path.join('model','best_pretemp.h5'))
def get_client(input):
incoming_json = json.dumps(input)
incoming_json = json.loads(incoming_json)
print(incoming_json)
def create_project(config):
status =500
token = config['id']
print(token)
pro_name = config['name']
pro_name = pro_name.replace(' ','')
table_name = str(pro_name) + '_' + str(token)
table_name = table_name.replace(' ','')
print(table_name)
create_table_sql = ''''''
if config['available'] == 'Weather Station':
# Define the SQL statement to create a new table
create_table_sql = '''CREATE TABLE {} (
date_time TIMESTAMP,
maxtempC INTEGER,
mintempC INTEGER,
uvIndex INTEGER,
DewPointC INTEGER,
FeelsLikeC INTEGER,
HeatIndexC INTEGER,
WindChillC INTEGER,
WindGustKmph INTEGER,
humidity INTEGER,
precipMM INTEGER,
pressure INTEGER,
tempC INTEGER,
visibility INTEGER,
winddirDegree INTEGER,
windspeedKmph INTEGER,
location TEXT
);'''.format(table_name)
elif config['available'] == 'PMS':
create_table_sql = '''CREATE TABLE {} (
tempC INTEGER,
moisture INTEGER,
location TEXT
);'''.format(table_name)
# print(create_table_sql)
# db_files = glob.glob(os.path.join('database', '*.db'))
db_name = os.path.join('database','sql3.db')
conn = sqlite3.connect(db_name)
c = conn.cursor()
try:
c.execute(create_table_sql)
except sqlite3.Error as e:
print(e)
# Check if the table was created successfully
# print(c.execute("SELECT name FROM sqlite_master WHERE type='table';"))
if '{}'.format(table_name) in [table[0] for table in c.execute("SELECT name FROM sqlite_master WHERE type='table';")]:
print("Table created successfully.")
settings = {}
with open('settings.json', 'r') as f:
settings = json.load(f)
print(settings)
new_table_list = []
new_table_list = settings['table_names']
new_table_list.append(table_name)
settings['table_names'] = new_table_list
with open('settings.json', 'w') as f:
f.write(json.dumps(settings))
status = 200
else:
print("Error creating table.")
conn.commit()
conn.close()
return status
def delete_project(token):
delete_sql = '''DROP TABLE {};'''.format(token)
conn = sqlite3.connect(os.path.join('database','sql3.db'))
status = 0
c = conn.cursor()
try:
c.execute(delete_sql)
conn.commit()
status =200
except sqlite3.Error as e:
print(f"The SQL statement failed with error: {e}")
status = 500
finally:
if conn:
conn.close()
# print(status)
return status
# create_project("24k3423","weather")
#garden_ZBFZCz9Ugn
def insert_into_table_WMS(datapoints,token):
db_name = ""
tb_name = ""
with open('settings.json', 'r') as f:
data = json.load(f)
# db_name = data['database']
tb_name = token
date_time = datetime.datetime.now()
maxtempC = datapoints['maxtempC']
mintempC = datapoints['mintempC']
uvIndex = datapoints['uvIndex']
DewPointC = datapoints['DewPointC']
FeelsLikeC = datapoints['FeelsLikeC']
HeatIndexC = datapoints['HeatIndexC']
WindChillC = datapoints['WindChillC']
WindGustKmph = datapoints['WindGustKmph']
humidity = datapoints['humidity']
precipMM = datapoints['precipMM']
pressure = datapoints['pressure']
tempC = datapoints['tempC']
visibility = datapoints['visibility']
winddirDegree = datapoints['winddirDegree']
windspeedKmphL = datapoints['windspeedKmph']
location = datapoints['location']
insert_data_sql = '''INSERT INTO {} (
date_time,
maxtempC,
mintempC,
uvIndex,
DewPointC,
FeelsLikeC,
HeatIndexC,
WindChillC,
WindGustKmph,
humidity,
precipMM,
pressure,
tempC,
visibility,
winddirDegree,
windspeedKmph,
location
) VALUES ('{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}');'''.format(tb_name, date_time, maxtempC, mintempC, uvIndex, DewPointC, FeelsLikeC, HeatIndexC, WindChillC, WindGustKmph, humidity, precipMM, pressure, tempC, visibility, winddirDegree, windspeedKmphL, location)
conn = sqlite3.connect(os.path.join('database','sql3.db'))
status = 0
c = conn.cursor()
try:
c.execute(insert_data_sql)
conn.commit()
status =200
except sqlite3.Error as e:
print(f"The SQL statement failed with error: {e}")
status = 500
finally:
if conn:
conn.close()
return status
def get_gauge_data(token):
get_data_sql = '''SELECT date_time,
uvIndex,
HeatIndexC,
humidity,
precipMM,
pressure,
tempC,
windspeedKmph FROM {} ORDER BY date_time DESC LIMIT 1;'''.format(token)
conn = sqlite3.connect(os.path.join('database','sql3.db'))
status = 0
c = conn.cursor()
data = {}
result = None
try:
c.execute(get_data_sql)
rows = c.fetchall()
# print(rows[0])
parameters = [
'date_time','uvIndex',
'HeatIndexC',
'humidity','precipMM','pressure',
'tempC','windspeedKmph'
]
for row,parameter in zip(list(rows[0]),parameters):
data[parameter] = row
# print(row,parameter)
conn.commit()
status =200
result = json.dumps(data)
except sqlite3.Error as e:
print(f"The SQL statement failed with error: {e}")
status = 500
finally:
if conn:
conn.close()
return result,status
def get_line_data(token, parameter):
get_data_sql = ''''''
if parameter ==0:
get_data_sql = '''SELECT date_time,
maxtempC,
mintempC,
tempC
FROM {} ORDER BY date_time DESC LIMIT 50;'''.format(token)
elif parameter ==1:
get_data_sql = '''SELECT date_time,
humidity FROM {} ORDER BY date_time DESC LIMIT 50;'''.format(token)
elif parameter ==2:
get_data_sql = '''SELECT date_time,
precipMM FROM {} ORDER BY date_time DESC LIMIT 50;'''.format(token)
elif parameter ==3:
get_data_sql = '''SELECT date_time,
pressure FROM {} ORDER BY date_time DESC LIMIT 50;'''.format(token)
conn = sqlite3.connect(os.path.join('database','sql3.db'))
status = 0
result = None
c = conn.cursor()
try:
c.execute(get_data_sql)
rows = c.fetchall()
result = json.dumps(rows)
conn.commit()
status =200
except sqlite3.Error as e:
print(f"The SQL statement failed with error: {e}")
status = 500
finally:
if conn:
conn.close()
return result,status
def get_table_names():
table_names = '''SELECT name FROM sqlite_master WHERE type='table';'''
conn = sqlite3.connect(os.path.join('database','sql3.db'))
status = 0
result = None
c = conn.cursor()
try:
c.execute(table_names)
rows = c.fetchall()
result = json.dumps(rows)
conn.commit()
status =200
except sqlite3.Error as e:
print(f"The SQL statement failed with error: {e}")
status = 500
finally:
if conn:
conn.close()
return result,status
def insert_into_table_PMS(token, datapoints):
tempC = datapoints['tempC']
moisture = datapoints['moisture']
location = datapoints['location']
pms_insert = '''INSERT into {} (tempC, moisture, location) VALUES ('{}','{}','{}')';'''.format(token,tempC,moisture,location)
conn = sqlite3.connect(os.path.join('database','sql3.db'))
status = 0
result = None
c = conn.cursor()
try:
c.execute(pms_insert)
rows = c.fetchall()
result = json.dumps(rows)
conn.commit()
status =200
except sqlite3.Error as e:
print(f"The SQL statement failed with error: {e}")
status = 500
finally:
if conn:
conn.close()
return result,status
def predictBasic():
pass
# print(get_line_data('Garden_B5gWZiq83M'))
# print(get_table_names())
# print(delete_project('Farmland_OBVL0EJnB0'))
# print(get_gauge_data('Garden_B5gWZiq83M'))