· 5 years ago · Jun 02, 2020, 11:10 AM
1from urllib.request import urlopen
2from tkinter import *
3from random import uniform
4from matplotlib import pyplot
5import json
6import sqlite3
7
8# Create window home Tkinter
9home = Tk()
10home.title("Aplikasi Data Tanaman");home.geometry("600x250")
11
12# Databases
13# create a database or connect to one
14conn = sqlite3.connect("kebun.db")
15
16# Create cursor
17kursor = conn.cursor()
18
19# Create table data_pohon
20kursor.execute("""CREATE TABLE IF NOT EXISTS data_pohon (
21 id_tree INTEGER PRIMARY KEY,
22 sensor_tree INTEGER,
23 loc_lat REAL,
24 loc_lon REAL)""")
25
26# Create tabel sensor_pohon if not exists
27kursor.execute("""CREATE TABLE IF NOT EXISTS data_sensor(
28 id_tree INTEGER PRIMARY KEY,
29 sensor_0 INTEGER,
30 sensor_1 INTEGER,
31 sensor_2 INTEGER,
32 sensor_3 INTEGER,
33 sensor_4 INTEGER,
34 sensor_5 INTEGER,
35 sensor_6 INTEGER,
36 sensor_7 INTEGER,
37 sensor_8 INTEGER,
38 sensor_9 INTEGER
39 )""")
40
41# Create submit function for database
42def get_loc():
43 # Search Random location Latitude & Longitude
44 for i in range(100):
45 loc_lat = uniform(1, 20)
46 for j in range(100):
47 loc_lon = uniform(1, 360)
48
49 # create a database or connect to one
50 conn = sqlite3.connect("kebun.db")
51 # Create cursor
52 kursor = conn.cursor()
53 # Insert Into Table data_pohon
54 kursor.execute("INSERT INTO data_pohon VALUES (:id_tree, :sensor_tree, :loc_lat, :loc_lon)",
55 {
56 'id_tree': id_tree.get(), 'sensor_tree': sensor_tree.get(),
57 'loc_lat': loc_lat,
58 'loc_lon': loc_lon
59 })
60
61 # Commit changes
62 conn.commit()
63 # Close connection
64 conn.close()
65
66 # Clear The Text Boxes
67 id_tree.delete(0, END)
68 sensor_tree.delete(0, END)
69
70# Create Function to Sensor Tree
71def option_sensor():
72 def sensor_result():
73 data_id = []
74 data_sensor = []
75 tree = id_tree.get()
76
77 while True:
78 tree = id_tree.get()
79
80 if tree.lower() == 'selesai':
81 break
82
83 result_sensor = []
84 for sensor_type in range(0,10):
85
86 address = f"https://belajar-python-unsyiah.an.r.appspot.com/sensor/read?npm=1904105010004&id_tree={tree}&sensor_type={sensor_type}"
87
88 url = urlopen(address)
89
90 documents = url.read().decode("utf-8")
91
92 data = json.loads(documents)
93
94 result_sensor.append(data['value'])
95
96 data_sensor.append(result_sensor)
97 data_id.append(tree)
98
99 print(f"Sensor : 0 Suhu Udara : {result_sensor[0]} K")
100 print(f"Sensor : 1 Kelembaban Udara : {result_sensor[1]} %")
101 print(f"Sensor : 2 Curah Hujan : {result_sensor[2]} mm")
102 print(f"Sensor : 3 Sinar UV : {result_sensor[3]} nm")
103 print(f"Sensor : 4 Suhu Tanah : {result_sensor[4]} C")
104 print(f"Sensor : 5 Kelembaban Tanah : {result_sensor[5]} %")
105 print(f"Sensor : 6 pH Tanah : {result_sensor[6]}")
106 print(f"Sensor : 7 pH N : {result_sensor[7]}")
107 print(f"Sensor : 8 pH P : {result_sensor[8]}")
108 print(f"Sensor : 9 pH K : {result_sensor[9]}")
109
110
111 tipe = 0
112 for one in range(0,10):
113 x = []
114 y = []
115 urutan = 0
116 for satu in data_id:
117 x.append(satu)
118 y.append(data_sensor[urutan][tipe])
119 urutan += 1
120 tipe += 1
121 pyplot.plot(x, y, '-o')
122
123 pyplot.title('Grafik')
124 pyplot.xlabel('Id Tanaman')
125 pyplot.ylabel('Sensor')
126 pyplot.legend(['Suhu Udara', 'Kelembaban Udara', 'Curah Hujan', 'Sinar UV', 'SUhu Tanah', 'Kelembaban Tanah', 'pH Tanah', 'pH N', 'pH P','pH K'])
127 pyplot.show()
128
129 global option_sensor
130 option_sensor = Tk()
131 option_sensor.title("Sensor Tanaman")
132 option_sensor.geometry("700x400")
133
134 id_tree = Entry(option_sensor, width=30)
135 id_tree.grid(row=3, column=1, pady=5)
136
137 id_tree_lbl = Label(option_sensor, text="ID Tanaman : ")
138 id_tree_lbl.grid(row=3, column=0, pady=5)
139
140 id_tree_btn = Button(option_sensor, text="Tambahkan Data", command=sensor_result)
141 id_tree_btn.grid(row=5, column=1, columnspan=1, ipadx=7)
142
143
144
145 # Main Loop
146 option_sensor.mainloop()
147
148# Create Function to Delete A Record
149def option_delete():
150 # delete from ID data
151 def delete_1():
152 # create a database or connect to one
153 conn = sqlite3.connect("kebun.db")
154 # Create cursor
155 # Create a Delete Button
156 kursor = conn.cursor()
157 # Delete a record
158 kursor.execute("DELETE FROM data_pohon WHERE oid = " + delete_box.get())
159 kursor.execute("DELETE FROM data_sensor WHERE oid = " + delete_box.get())
160 delete_box.delete(0, END)
161 # Commit changes
162 conn.commit()
163 # Close connection
164 conn.close()
165
166 # Delete a Tabel data_pohon
167 def delete_2():
168 # create a database or connect to one
169 conn = sqlite3.connect("kebun.db")
170 # Create cursor
171 kursor = conn.cursor()
172 # Delete a tabel
173 kursor.execute("DROP TABLE IF EXISTS data_pohon;")
174 # Create table data_pohon
175 kursor.execute("""CREATE TABLE IF NOT EXISTS data_pohon (
176 id_tree INTEGER PRIMARY KEY, sensor_tree INTEGER,
177 loc_lat REAL, loc_lon REAL)""")
178
179 kursor.execute("DROP TABLE IF EXISTS data_sensor;")
180 # Create Tabel sensor_pohon
181 kursor.execute("""CREATE TABLE IF NOT EXISTS data_sensor(
182 id_tree INTEGER PRIMARY KEY,
183 sensor_0 INTEGER,
184 sensor_1 INTEGER,
185 sensor_2 INTEGER,
186 sensor_3 INTEGER,
187 sensor_4 INTEGER,
188 sensor_5 INTEGER,
189 sensor_6 INTEGER,
190 sensor_7 INTEGER,
191 sensor_8 INTEGER,
192 sensor_9 INTEGER
193 )""")
194 # Commit changes
195 conn.commit()
196 # Close connection
197 conn.close()
198
199 global option_delete
200 option_delete = Tk()
201 option_delete.title("Hapus Data")
202 option_delete.geometry('450x200')
203
204 # Create Text Boxes
205 delete_box = Entry(option_delete, width=30)
206 delete_box.grid(row=3, column=1, pady=5)
207 # Create a label delete
208 delete_box_lbl = Label(option_delete, text="Select ID : ")
209 delete_box_lbl.grid(row=3, column=0, pady=5)
210 # Create a Delete Button
211 delete_btn = Button(option_delete, text="Hapus Data ID", command=delete_1)
212 delete_btn.grid(row=4, column=1, columnspan=1, pady=11, padx=11, ipadx=22)
213 # Create a Delete All Button
214 del_all_btn = Button(option_delete, text="Hapus Semua Data", command=delete_2)
215 del_all_btn.grid(row=5, column=1, columnspan=1, ipadx=7)
216
217 # Main loop
218 option_delete.mainloop()
219
220# Create result function
221def result():
222 option_result = Tk()
223 option_result.title("Tampilkan Data")
224 option_result.geometry("600x300")
225
226 def print():
227 # create a database or connect to one
228 conn = sqlite3.connect("kebun.db")
229 # Create cursor
230 kursor = conn.cursor()
231 # Result the database
232 kursor.execute("SELECT *, oid FROM data_pohon")
233 records = kursor.fetchall()
234
235 # loop thur Result
236 print_records = ""
237 for record in records:
238 # Print for looping
239 print_records += f"\n id : {record[0]} sensor : {record[1]} Latitude : - {record[2]:1.7f} Longitude : {record[3]:1.7f}"
240
241 # Result in box
242 box_result.insert(END, print_records)
243 # Commit changes
244 conn.commit()
245 # Close connection
246 conn.close()
247
248 # create a database or connect to one
249 conn = sqlite3.connect("kebun.db")
250 # Create cursor
251 kursor = conn.cursor()
252 # Result the database
253 kursor.execute("SELECT *, oid FROM data_pohon")
254 records = kursor.fetchall()
255
256 # loop thur Result
257 print_records = ""
258 for record in records:
259 # Print for looping
260 print_records += f"\n id : {record[0]} sensor : {record[1]} Latitude : - {record[2]:1.7f} Longitude : {record[3]:1.7f}"
261
262 # Result in box
263 result_lbl = Label(option_result, text=print_records)
264 result_lbl.grid(row=2, column=0, rowspan=40, columnspan=2, padx=10, pady=10)
265 # Commit changes
266 conn.commit()
267 # Close connection
268 conn.close()
269
270
271 #Main loop
272 option_result.mainloop()
273
274# Create Text Boxes
275id_tree = Entry(home, width=20)
276id_tree.grid(row=0, column=1, padx=20, pady=(10,0))
277sensor_tree = Entry(home, width=20)
278sensor_tree.grid(row=1, column=1)
279
280# Create Text Box Labels
281id_tree_lbl = Label(home, text="ID Tanaman\t\t: ")
282id_tree_lbl.grid(row=0, column=0, pady=(10,0))
283sensor_tree_lbl = Label(home, text="No. Sensor (0 s/d 9)\t\t: ")
284sensor_tree_lbl.grid(row=1, column=0)
285
286
287# Create information Button
288#info_btn = Button(root, text="Application\ninformation", command=optioninfo_tree)
289#info_btn.grid(row=0, column=2, columnspan=1, ipadx=2)
290
291# Create get_data Button
292get_data_btn = Button(home, text="Tambahkan Data", command=get_loc)
293get_data_btn.grid(row=6, column=0, columnspan=1, pady=10, padx=10, ipadx=42)
294
295# Create Result Button
296result_btn = Button(home, text="Tampilkan Data", command=result)
297result_btn.grid(row=7, column=0, columnspan=1, ipadx=46)
298
299# Create Delete Button
300delete_btn = Button(home, text="Hapus Data", command=option_delete)
301delete_btn.grid(row=8, column=0, columnspan=1, ipadx=60)
302
303# Create an Sensor Button
304sensor_btn = Button(home, text="Sensor Tanaman", command=option_sensor)
305sensor_btn.grid(row=7, column=1, columnspan=2, pady=11, padx=11, ipadx=42)
306
307
308# Commit changes
309conn.commit()
310# Close connection
311conn.close()
312# Main loop
313home.mainloop()