-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
executable file
·593 lines (494 loc) · 22.2 KB
/
main.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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
import logging
import os
import threading
from logging import Logger
import traceback
from kivy import platform
from kivy.uix.screenmanager import Screen
from kivymd.app import MDApp
from kivymd.toast import toast
from kivymd.uix.filemanager import MDFileManager
from kivymd.uix.floatlayout import MDFloatLayout
from kivymd.uix.menu import MDDropdownMenu
from kivymd.uix.tab import MDTabsBase
import create_vessel
# import file from project
import db_editing
import db_reading
import vol_coorection
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(module)s - - %(lineno)d - %(message)s", filename='mylog.log',
level=logging.WARNING, # %(pathname)s
)
logger: Logger = logging.getLogger(__name__)
## Window resizing. To be deleted or commented before compiling
# from kivy.core.window import Window
# Window.size = (400, 700)
if platform == "android":
from android.permissions import request_permissions, Permission
request_permissions(
[Permission.WRITE_EXTERNAL_STORAGE,
Permission.READ_EXTERNAL_STORAGE])
from android.storage import primary_external_storage_path
SD_CARD = primary_external_storage_path()
# Here we store our dict with total quantity of fuel
tank_total_hfo = []
tank_total_mdo = []
# Default variables
def_temp = int(15) # The conventional Default temperature for calculating fuel
vessel_db = "viking_ocean.db" # deafault vessel for build primary structure of App
prev_label_text = {}
file_location_detect = os.getcwd()
class Tank:
def __init__(self, name, metric_tons, measurement, temp, density, volume):
self.name = name
self.metric_tons = metric_tons
self.measurement = measurement
self.temp = temp
self.density = density
self.volume = volume
@staticmethod
def add_tank_to_list(tank, tank_list):
names = {t.name for t in tank_list}
if tank.name in names:
tank_list[:] = [t for t in tank_list if t.name != tank.name]
tank_list.append(tank)
return True
def add_tank_hfo(self):
return self.add_tank_to_list(self, tank_total_hfo)
def add_tank_mdo(self):
return self.add_tank_to_list(self, tank_total_mdo)
# Screens
class TabScreen(Screen):
pass
class TotalScreen(Screen):
pass
class AdminScreen(Screen):
pass
class NewVesselScreen(Screen):
pass
class AddTankScreen(Screen):
pass
class DelVesselScreen(Screen):
pass
class Tab(MDFloatLayout, MDTabsBase):
'''Class implementing content for a tab.'''
class BunkerCalc(MDApp):
def build(self):
# Theme and colors
self.theme_cls.primary_palette = "Gray"
self.theme_cls.primary_hue = "600"
self.theme_cls.theme_style = "Dark"
def on_start(self):
# Dict for storing all vessel sounding table data
self.the_DB = {}
self.the_DB_admin = {}
# Calculation button state is Disabled
self.button_state = 0
self.name_of_tank(vessel_db)
self.mdo_tank_extract(vessel_db)
self.add_tab(vessel_db)
self.slider_value = {}
self.j = 0
if platform == "android":
from android.permissions import request_permissions, Permission
request_permissions([Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE])
# Label for toggle screens between the total screen and Tabs
screen = self.root.get_screen("tab_screen")
screen.ids.right_action.text = "Sounding Screen"
screen.ids.select_vessel.text = "Select vessel"
def change_vessel(self, vessel):
try:
tabs = self.root.get_screen('tab_screen').ids.tabs.get_tab_list()
for i in tabs:
self.root.get_screen("tab_screen").ids.tabs.remove_widget(i)
try:
self.name_of_tank(vessel)
self.mdo_tank_extract(vessel)
self.add_tab(vessel)
except Exception as error:
logger.debug(traceback.format_exc())
except Exception as error:
logger.debug(traceback.format_exc())
def calculate_total(self):
# Calculate the total m3 in our "total_list"
self.mdo_tons = []
self.hfo_tons = []
# HFO
self.sum_hfo = 0
self.sum_hfo_tons = 0
# MDO
self.sum_mdo = 0
self.sum_mdo_tons = 0
for tank in tank_total_hfo:
self.sum_hfo += float(tank.volume)
self.sum_hfo_tons += float(tank.metric_tons)
for tank in tank_total_mdo:
self.sum_mdo += float(tank.volume)
self.sum_mdo_tons += float(tank.metric_tons)
if len(self.hfo_tons) == 0:
self.hfo_tons.append(float(0))
if len(self.mdo_tons) == 0:
self.mdo_tons.append(float(0))
return self.sum_mdo, self.sum_hfo, self.hfo_tons, self.mdo_tons, self.sum_mdo_tons, self.sum_hfo_tons
def screen2(self):
"""
Go to the total screen where the total figure is shown.
Each time "total_screen" is pressed, the total figure is recalculated.
"""
current_screen = self.root.current
if current_screen != "total_screen":
if current_screen == "tab_screen":
self.root.current = "total_screen"
self.calculate_total()
# Display total results for MDO and HFO
total_screen = self.root.get_screen("total_screen")
total_screen.ids.right_action.text = "Total Screen"
total_screen.ids.total_hfo.text = (
f"{round(self.sum_hfo, 3)} m3 HFO\n"
f"{round(self.sum_hfo_tons, 2)} MT HFO\n___________________"
)
total_screen.ids.total_mdo.text = (
f"{round(self.sum_mdo, 3)} m3 MDO\n"
f"{round(self.sum_mdo_tons, 2)} MT MDO"
)
else:
self.root.current = "tab_screen"
else:
self.root.current = "tab_screen"
def vessel_name(self, vessel_name):
"""
Set the selected vessel as the title of the App.
"""
try:
self.name_of_vessel_db = f"{vessel_name.lower()}.db" # Name of DB if it is non-default
# THREAD FOR selecting and switching vessel DB
self.start_thread(self.name_of_vessel_db)
if len(self.the_DB) != 0:
self.vessel = str(vessel_name)
self.root.get_screen("tab_screen").ids.top_menu.title = str(vessel_name).replace("_", ' ')
self.menu.dismiss()
self.root.get_screen("total_screen").ids.total_menu_total.title = str(vessel_name)
except Exception as error:
logger.warning(f"Vessel name method - {error} : {traceback.format_exc()}")
def choose_vessel(self, x):
"""
Create a dropdown menu for selecting the Vessel's Database.
"""
vessel_name_db = []
self.the_DB = {}
vessels = []
file_location_detect = os.getcwd()
try:
# Scan current working Directory
scan_dir = os.listdir(file_location_detect)
for file in scan_dir:
if not file.endswith('_prev.db') and file.endswith(".db"):
parsed_vessel = os.path.splitext(file)[0].title()
vessel_name_db.append(parsed_vessel)
vessels.append(parsed_vessel)
except Exception as error:
logger.warning(f"Choose vessel files function - {error} : {traceback.format_exc()}")
try:
self.root.get_screen("tab_screen").ids.select_vessel.text = "Vessel"
self.db_tuple = {}
for vessel in iter(vessels):
self.the_DB[vessel] = vessels[0]
menu_items = [
{
"viewclass": "OneLineListItem",
"text": f"{vessels[i]}",
"on_release": lambda x=f"{vessels[i]}": self.vessel_name(x)
} for i in range(len(vessels))
]
self.menu = MDDropdownMenu(
items=menu_items,
width_mult=4
)
self.menu.caller = x
self.menu.open()
except ValueError as error:
logger.warning(f"Create a dropdown menu - {error} : {traceback.format_exc()}")
def start_thread(self, vessel):
self.button_state += 1
self.x_thread = threading.Thread(target=self.change_vessel(vessel), daemon=True)
self.x_thread.start()
if not self.x_thread.is_alive():
try:
self.button_state += 1
except Exception as error:
logger.debug(traceback.format_exc())
def name_of_tank(self, vessel_db):
"""
Extract tank names from the database.
"""
try:
self.names = []
extract_name = db_reading.extract_names(vessel_db)
self.tank_name = extract_name
self.names = [i[0] for i in self.tank_name]
except Exception as error:
self.root.get_screen("tab_screen").ids.top_menu.title = "No DATA in Vessel database"
logger.debug(traceback.format_exc())
def mdo_tank_extract(self, v):
"""
Extract MDO tank names from the database.
"""
self.mdo_names = []
sorted_tank = db_reading.sort_tanks_mdo(v)
self.mdo_tanks = sorted_tank
self.mdo_names = [i[0] for i in self.mdo_tanks]
def add_tab(self, vessel):
try:
names_for_do = list(set(self.mdo_names).intersection(set(self.names)))
# print(names_for_do)
self.tab_iterator = 0
for i in (self.names):
prev_names = db_reading.extract_prev(i, vessel)
if not i in names_for_do:
self.root.get_screen('tab_screen').ids.tabs.add_widget(Tab(tab_label_text=f"{i}"))
for do in names_for_do:
if do == i:
self.root.get_screen('tab_screen').ids.tabs.add_widget(Tab(tab_label_text=f"{do} mdo"))
# afetr add text to label of first tab we delete here the last widget that is non-correct
self.root.get_screen('tab_screen').ids.tabs.remove_widget(
self.root.get_screen('tab_screen').ids.tabs.get_tab_list()[-1]
)
except Exception as error:
logger.warning(f"Exception in add tab - {error} : {traceback.format_exc()}")
def on_tab_switch(
self, instance_tabs, instance_tab, instance_tab_label, tab_text
):
'''Called when switching tabs.
:type instance_tabs: <kivymd.uix.tab.MDTabs object>;
:param instance_tab: <__main__.Tab object>;
:param instance_tab_label: <kivymd.uix.tab.MDTabsLabel object>;
:param tab_text: text or name icon of tab;
'''
self.sound_filed_help = instance_tab.ids.sound_field
instance_tab.ids.sound_field.text_color_normal = 1, 1, 0.8, 1
self.button_calc = instance_tab.ids.calc
self.text_vessel = self.root.get_screen("tab_screen").ids.top_menu.title
self.sound_value = instance_tab.ids.sound_field
self.tank_name = instance_tab_label
self.result = instance_tab.ids.label
self.dens_new = instance_tab.ids.density_field
self.result_mt = instance_tab.ids.label_mt
self.result_mt.font_size = "20dp"
self.hint_text = instance_tab.ids.sound_field
if self.button_state > 0:
self.button_calc.disabled = False
self.root.get_screen("tab_screen").ids.select_vessel.text_color = 1, 1, 0.9, 1
else:
self.button_calc.disabled = True
self.result.font_size = "30dp"
self.result.text = "Select Vessel first"
self.root.get_screen("tab_screen").ids.select_vessel.text_color = "#f43434"
if not self.result.text == "Select Vessel first":
try:
if self.text_vessel:
self.sound_filed_help.hint_text = f"Prev quant:\n{db_reading.prev_label_text[str(self.tank_name.text.removesuffix('mdo')).strip(' ')][0]} m3, at {db_reading.prev_label_text[str(self.tank_name.text.removesuffix('mdo')).strip(' ')][1]} cm"
else:
self.sound_filed_help.hint_text = f"Prev quant:\n{db_reading.prev_label_text[str(self.tank_name.text.removesuffix('mdo')).strip(' ')][0]} m3, at {db_reading.prev_label_text[str(self.tank_name.text.removesuffix('mdo')).strip(' ')][1]} cm"
except Exception as error:
logger.warning(f"On tab switch method - {error} : {traceback.format_exc()}")
def callback_Calc(self, *args):
try:
tank_name_stripped = str(self.tank_name.text.removesuffix('mdo')).strip(' ')
calculations = db_editing.calculation(tank_name_stripped, self.sound_value.text, self.name_of_vessel_db)
type_selected = db_editing.type_sel(tank_name_stripped, self.name_of_vessel_db)
state_selected = db_editing.state_sel(tank_name_stripped, self.name_of_vessel_db)
volume = str(calculations[0]) if calculations else None
self.handle_calculation_results(type_selected[0], state_selected[0], calculations, volume)
except AttributeError as error:
self.handle_attribute_error()
def handle_calculation_results(self, type_selected, state_selected, calculations, volume):
try:
self.result.font_size = "30dp"
if state_selected == 1:
self.handle_mdo_calculation(type_selected, calculations, volume)
else:
self.handle_hfo_calculation(type_selected, calculations, volume)
self.sound_filed_help.hint_text = "Sounding value (cm):"
except IndexError as error:
self.handle_index_error()
def handle_mdo_calculation(self, type_selected, calculations, volume):
try:
if type_selected == 1:
self.result.text = str(self.sound_value.text) + " m3"
else:
self.result.text = str(calculations[0]) + " m3"
self.temp_dens_extraction()
tank_vessel = Tank(self.get_tank_name(), self.real_volume, self.sound_value.text,
self.temperature, self.def_dens, volume)
tank_vessel.add_tank_mdo()
if tank_vessel:
db_reading.add_to_prevdb(tank_vessel.name, tank_vessel.measurement, tank_vessel.volume,
self.name_of_vessel_db)
except IndexError as error:
self.handle_index_error()
def handle_hfo_calculation(self, type_selected, calculations, volume):
try:
self.result.text = str(self.sound_value.text) + " m3" if type_selected == 1 else str(
calculations[0]) + " m3"
self.temp_dens_extraction()
tank_vessel = Tank(self.get_tank_name(), self.real_volume, self.sound_value.text,
self.temperature, self.def_dens, volume)
tank_vessel.add_tank_hfo()
if tank_vessel:
db_reading.add_to_prevdb(tank_vessel.name, tank_vessel.measurement, tank_vessel.volume,
self.name_of_vessel_db)
except IndexError as error:
self.handle_index_error()
def handle_index_error(self):
self.result.text = "Wrong sounding value!"
self.result.font_size = "20dp"
logger.debug(traceback.format_exc())
def handle_attribute_error(self):
self.root.get_screen("tab_screen").ids.select_vessel.text = "Select the vessel first"
logger.debug(traceback.format_exc())
def get_tank_name(self):
return str(self.tank_name.text.removesuffix('mdo')).strip(' ')
def my_value(self, *args):
try:
self.slider_value[self.get_tank_name()] = round(int(args[1]), 0)
except Exception as error:
logger.debug(traceback.format_exc())
return self.slider_value
def temp_dens_extraction(self):
try:
self.temperature = self.get_slider_temperature()
self.def_dens = self.get_density_value()
except (AttributeError, KeyError):
self.temperature = def_temp
self.def_dens = db_editing.select_DefDens(self.get_tank_name(), self.name_of_vessel_db)
self.calculate_converted_density()
def get_slider_temperature(self):
try:
return str(self.slider_value[self.get_tank_name()])
except Exception:
return def_temp
def get_density_value(self):
if len(self.dens_new.text) == 0:
return db_editing.select_DefDens(self.get_tank_name(), self.name_of_vessel_db)
else:
if float(self.dens_new.text) >= 1.1:
self.dens_new.hint_text = "Wrong Density"
self.dens_new.text_color_normal = "#ff2233"
else:
self.dens_new.hint_text = "Density (example: 0.9588)"
self.dens_new.text_color_normal = 1, 1, 0.8, 1
return self.dens_new.text
def calculate_converted_density(self):
try:
self.converted_density = ((float(self.def_dens) / 2) * 1000) * 2
except Exception as error:
logger.debug(traceback.format_exc())
if not str(self.result.text).isdigit():
self.result.text = str(self.result.text).removesuffix(' m3')
vol_ = vol_coorection.vol_correction_factor_calc(self.converted_density, self.result.text,
int(self.temperature))
self.real_volume = vol_
self.result_mt.text = f"{str(self.real_volume)} mt"
def admin_panel(self):
self.vessel_name_db = []
self.vessels_admin = []
self.db_tuple_admin = {}
self.root.current = "admin_screen"
self.root.get_screen("add_tank_screen").ids.drop_vessels.text = "Choose vessel"
self.root.get_screen("del_vessel_screen").ids.drop_vessels.text = "Choose vessel"
def create_vessel(self, name):
# Create new Vessel database
try:
create_vessel.create_vessel(name)
except Exception as error:
logger.debug(traceback.format_exc())
def file_manager_open(self):
# print(self.tk)
if len(self.tk) == 0:
self.manager_open = False
self.file_manager = MDFileManager(
exit_manager=self.exit_manager, select_path=self.select_path,
ext=['.csv', ], selection=[]
)
if platform == "android":
self.file_manager.show(SD_CARD)
else:
self.file_manager.show(os.path.expanduser("~")) # output manager to the screen
self.manager_open = True
else:
self.tk = self.root.get_screen("add_tank_screen").ids.new_tank.text = "Enter name of Tank"
pass
def exit_manager(self, *args):
'''Called when the user reaches the root of the directory tree.'''
self.manager_open = False
self.file_manager.close()
def select_path(self, path: str, ):
'''
It will be called when you click on the file nameF
or the catalog selection button.
:param path: path to the selected directory or file;
'''
self.selected_tank_import = path
self.exit_manager()
# print(self.selected_tank_import)
# print(self.root.get_screen("add_tank_screen").ids.new_tank.text)
self.tk = self.root.get_screen("add_tank_screen").ids.new_tank.text
toast(path)
db_reading.import_data(self.selected_tank_import, self.vessel_for_import, self.tk)
def choose_vessel_admin(self):
"""
Create a dropdown menu for selecting the Vessel`s Data Base
"""
self.vessel_name_db = []
self.vessels_admin = []
self.db_tuple_admin = {}
try:
try:
# scan current working Directory
scan_dir = os.listdir(file_location_detect)
for file in scan_dir:
if not file.endswith('_prev.db') and file.endswith(".db"):
parsed_vessel = str(file).removesuffix('.db').title()
self.vessel_name_db.append(parsed_vessel)
self.vessels_admin.append(parsed_vessel)
except Exception as error:
logger.debug(traceback.format_exc())
for vessel in iter(self.vessels_admin):
self.the_DB_admin[vessel] = self.vessels_admin[0]
# print(vessels_admin)
menu_items = [(
{
"viewclass": "OneLineListItem",
"text": f"{self.vessels_admin[i]}",
"on_release": lambda x=f"{self.vessels_admin[i]}": self.selected_vessel_import(x)
}) for i in range(len(self.vessels_admin))
]
self.menu_admin = MDDropdownMenu(
items=menu_items,
width_mult=4,
caller=self.root.get_screen("add_tank_screen").ids.drop_vessels,
)
self.menu_admin.open()
self.vessel_to_delete = self.vessels_admin
except ValueError as error:
logger.debug(traceback.format_exc())
pass
def selected_vessel_import(self, vessel: str):
self.root.get_screen("add_tank_screen").ids.drop_vessels.text = vessel
self.root.get_screen("del_vessel_screen").ids.drop_vessels.text = vessel
self.menu_admin.dismiss()
self.vessel_for_import = (str(vessel).lower() + ".db")
self.root.get_screen("add_tank_screen").ids.new_tank.disabled = False
self.root.get_screen("add_tank_screen").ids.btn_add.disabled = False
self.tk = self.root.get_screen("add_tank_screen").ids.new_tank.text = str()
def delete_vessel(self):
file_db = str(self.root.get_screen("del_vessel_screen").ids.drop_vessels.text).lower() + ".db"
file_db_prev = str(self.root.get_screen("del_vessel_screen").ids.drop_vessels.text).lower() + "_prev.db"
os.remove(str(file_location_detect + "/" + str(file_db)))
os.remove(str(file_location_detect + "/" + str(file_db_prev)))
if __name__ == "__main__":
try:
BunkerCalc().run()
except Exception as error:
logger.debug(traceback.format_exc())