-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
1874 lines (1708 loc) · 81.1 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
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import flet as ft
from flet import AppBar, ElevatedButton, Page, Text, View, colors, TextField
import asyncio
import numpy as np
import matplotlib.pyplot as plt
import requests
import pyperclip
from tempgraph import tempGraph
from stopwatch import StopwatchApp
import copy
import re
import datetime
import sqlite3
os.environ["FLET_WS_MAX_MESSAGE_SIZE"] = "16000000"
async def main(page: Page):
################################
### Init
################################
time=[]
temp=[]
pressure=[]
humidity=[]
altitude=[]
a0=[]
a1=[]
a2=[]
a3=[]
global r_time, r_temp, r_pressure, r_humidity, r_altitude, r_a0, r_a1, r_a2, r_a3, r_time_str
r_time_str=[]
r_time=[]
r_temp=[]
r_pressure=[]
r_humidity=[]
r_altitude=[]
r_a0=[]
r_a1=[]
r_a2=[]
r_a3=[]
# ストレージ
# await page.client_storage.clear_async()
global recordStopWatchSystem
recordStopWatchSystem=StopwatchApp()
global recordStartTime, resetFlag, recordListSum, tempGraphSystem, recordListFloatSum, recordStatus, recordDataStatus, recordStartAltitude, recordTime, takeoffTime, takeoffRecordStartTime, isDbSaved
recordStartTime=-1.0
takeoffRecordStartTime=-1.0
takeoffTime=-1.0
recordStartAltitude=0.0
recordStatus=False
recordDataStatus=False
recordTime=-1
recordListSum=[]
recordListFloatSum=[]
resetFlag=True
isDbSaved=False
################################
### Page System
################################
page.title = "EBDAS - Ehime Baloon Data Analysis System"
body=[]
bodySide=[]
rtTab=[]
rtTabSide=[]
tempGraphSystem= tempGraph()
howtoRecordGuide = ft.Image(
src=f"howtoRecord.gif",
# width=100,
# height=40,
# fit=ft.ImageFit.FIT_HEIGHT,
visible=True
)
################################
### realtimeRenderSwitch
################################
async def rtRenderChange(e):
await page.client_storage.set_async("isRtRender", rtRenderSwitch.value)
if await page.client_storage.contains_key_async("isRtRender") == True:
rtRenderSwitch=ft.Switch(label="リアルタイム描画", on_change=rtRenderChange, value=await page.client_storage.get_async("isRtRender"))
else:
rtRenderSwitch=ft.Switch(label="リアルタイム描画", on_change=rtRenderChange, value=False)
################################
### Snackbar
################################
page.snack_bar = ft.SnackBar(
content=ft.Text("Hello, world!"),
action="Alright!",
)
async def openSnackbar(text):
page.snack_bar = ft.SnackBar(ft.Text(text))
page.snack_bar.open = True
await page.update_async()
###################
## Folder Pickup System
###################
global dir_path
dir_path=None
# Open directory dialog
async def get_directory_result(e: ft.FilePickerResultEvent):
directory_path = e.path if e.path else ""
await page.client_storage.set_async("directory_path", directory_path)
projectDirectory.value="保存先: "+directory_path
await openSnackbar("測定データの保存ディレクトリを設定しました: "+directory_path)
await projectDirectory.update_async()
await initDatabase()
get_directory_dialog = ft.FilePicker(on_result=get_directory_result)
page.overlay.append(get_directory_dialog)
global rawResponseData, recordRawData
rawResponseData=""
recordRawData=""
global connectStatus
connectStatus = False
###################
## Database System
###################
global dbname, conn, isDbConnected
dbname = None
conn = None
isDbConnected = False
async def initDatabase():
global dbname, conn, isDbConnected
if await page.client_storage.contains_key_async("directory_path") == True or await page.client_storage.get_async("directory_path")!="":
dir_path=await page.client_storage.get_async("directory_path")
if os.path.isdir(dir_path):
if os.path.isfile(dir_path+"/EBDAS_data.db"):
dbname = dir_path+"/EBDAS_data.db"
isDbConnected = True
else:
dbname = dir_path+"/EBDAS_data.db"
# テーブル作成
isDbConnected = True
conn = sqlite3.connect(dbname)
cur = conn.cursor()
cur.execute(
"CREATE TABLE IF NOT EXISTS data (id INTEGER PRIMARY KEY AUTOINCREMENT, baloon TEXT, weight INTEGER, datetime TEXT, recordLocation TEXT, recordTime REAL, chargeTime REAL, airTime REAL, temperature_ave REAL, pressure_init REAL, humidity_init REAL, altitude_max REAL, a_ave_init REAL, a0_max REAL, a1_max REAL, a2_max REAL, a3_max REAL, a0_location TEXT, a1_location TEXT, a2_location TEXT, a3_location TEXT, rawdata TEXT, recordNote TEXT)"
)
conn.commit()
conn.close()
await openSnackbar("データベースを作成しました。")
else:
await openSnackbar("ディレクトリが存在しません。再指定してください。")
###################
## 機材管理 System
###################
def find_option(option_name):
for option in baloonSelecter.options:
if option_name == option.key:
return option
return None
async def dropdown_changed(e):
if await page.client_storage.contains_key_async("hontai_ip") == False or await page.client_storage.get_async("hontai_ip")==None:
await openSnackbar("接続先が未設定です。")
baloonSelecter.value=None
await page.update_async()
await reloadBaloons(e)
return()
if await page.client_storage.contains_key_async("directory_path") == False or await page.client_storage.get_async("directory_path")=="":
await openSnackbar("ディレクトリが指定されていません。保存先を設定してください。")
baloonSelecter.value=None
await page.update_async()
await reloadBaloons(e)
return()
if os.path.isdir(await page.client_storage.get_async("directory_path")+"/"+baloonSelecter.value) == False:
await openSnackbar("ディレクトリが存在しません。")
baloonSelecter.value=None
await page.update_async()
await reloadBaloons(e)
return()
projectTitle.value = f"プロジェクト名: {baloonSelecter.value}"
if connectStatus==True and ((recordStatus==False and recordDataStatus==True) or recordDataStatus==False):
recordStartButton.disabled=False
await recordStartButton.update_async()
await page.update_async()
await page.client_storage.set_async("baloon", baloonSelecter.value)
async def add_clicked(e):
global dir_path
if not option_textbox.value:
option_textbox.error_text = "入力してください。"
await page.update_async()
return()
option_textbox.error_text = ""
if dir_path==None:
page.banner.content=ft.Column(spacing=0, controls=[ft.Text("データの保存先が未指定です。", theme_style=ft.TextThemeStyle.TITLE_LARGE), ft.Text("ファイル>ディレクトリを選択 から、測定したデータの保存先を指定してください。")])
page.banner.open = True
await page.update_async()
return()
newBaloonName=re.sub(r'[\\|/|:|?|.|"|<|>|\|]', '-', option_textbox.value)
try:
os.mkdir(dir_path+"/"+newBaloonName)
except FileExistsError as e:
print("FileExistsError")
await openSnackbar("既にディレクトリが存在します。別の名前を指定してください。")
except FileNotFoundError as e:
await openSnackbar("ディレクトリが存在しません。再度保存先を設定してください。")
except Exception as e:
await openSnackbar("予期しないエラーが発生しました: "+str(e))
else:
baloonSelecter.options.append(ft.dropdown.Option(newBaloonName))
baloonSelecter.value = newBaloonName
await openSnackbar("フォルダを作成しました: "+newBaloonName)
option_textbox.value = ""
await baloonSelecter.update_async()
await page.update_async()
async def delete_clicked(e):
option = find_option(baloonSelecter.value)
if option != None:
baloonSelecter.options.remove(option)
# d.value = None
await page.update_async()
# async def slider_changed(e):
# if weightInput.value == None:
# return()
# weightInput.value = format(weightInputSlider.value, ".0f")
# await weightInput.update_async()
# await page.update_async()
async def weightInput_changed(e):
if weightInput.value != "":
if int(weightInput.value) > 100:
weightInput.value = weightInput.value[:3]
# weightInputSlider.value = int(weightInput.value[:3])
await weightInput.update_async()
return()
# weightInputSlider.value = int(weightInput.value)
# await weightInputSlider.update_async()
baloonSelecter = ft.Dropdown(label="使用機材", width=150,hint_text="機材管理タブで追加可能", prefix_icon=ft.icons.AIRPLANEMODE_ACTIVE_ROUNDED, on_change=dropdown_changed)
weightInput = ft.TextField(label="積載重量", on_change=weightInput_changed, width=100, suffix_text="g", keyboard_type=ft.KeyboardType.NUMBER, input_filter=ft.InputFilter(allow=True, regex_string=r"[0-9]", replacement_string=""))
# weightInputSlider = ft.Slider(width=600, min=0, max=100, divisions=20, label="キッチンスケールで計測した値", on_change=slider_changed)
async def reloadBaloons(e):
global dir_path
if dir_path!=None:
files_dir = [
ft.dropdown.Option(f) for f in os.listdir(dir_path) if os.path.isdir(os.path.join(dir_path, f))
]
baloonSelecter.options=files_dir
await baloonSelecter.update_async()
else:
await openSnackbar("ディレクトリが指定されていません。保存先を設定してください。")
if await page.client_storage.contains_key_async("directory_path") == True or await page.client_storage.get_async("directory_path")!="":
dir_path=await page.client_storage.get_async("directory_path")
try:
files_dir = [
ft.dropdown.Option(f) for f in os.listdir(dir_path) if os.path.isdir(os.path.join(dir_path, f))
]
except FileNotFoundError as e:
await openSnackbar("ディレクトリが存在しません。再指定してください。: "+str(e))
await page.client_storage.set_async("directory_path", "")
dir_path=None
except Exception as e:
await openSnackbar("エラーが発生しました。ディレクトリを再指定してください。: "+str(e))
await page.client_storage.set_async("directory_path", "")
dir_path=None
else:
baloonSelecter.options=files_dir
await initDatabase()
await page.update_async()
# else:
# baloonSelecter.error_text="機材管理タブから追加してください。"
# await page.update_async()
option_textbox = ft.TextField(hint_text="新しいバルーンの名前を決めてください。", label="新しいバルーン名")
add = ft.ElevatedButton("追加", on_click=add_clicked)
delete = ft.OutlinedButton("Delete selected", on_click=delete_clicked)
global server_url
if await page.client_storage.contains_key_async("hontai_ip") == False:
server_url = None
elif await page.client_storage.get_async("hontai_ip")=="":
server_url = None
else:
server_url = await page.client_storage.get_async("hontai_ip")
async def view_hontai_port():
if await page.client_storage.contains_key_async("hontai_port") == False:
return("未設定")
elif await page.client_storage.get_async("hontai_port")=="":
return("未設定")
else:
return(await page.client_storage.get_async("hontai_port"))
async def close_banner(e):
page.banner.open = False
await page.update_async()
global bannerContents
bannerContents=ft.Text("")
global isRecordStop, isChargeCompleted
isRecordStop=True
isChargeCompleted=False
table=ft.DataTable(
heading_row_height=0,
# border=ft.border.all(2, "red"),
show_bottom_border=True,
#columns 里必须添加 DataColumn 类型的控件
#data_row_max_height=33,
horizontal_margin=0,
columns=[
ft.DataColumn(ft.Text("時間[sec]"), numeric=True),
ft.DataColumn(ft.Text("外気温度[℃]"), numeric=True),
ft.DataColumn(ft.Text("圧力[hPa]"), numeric=True),
ft.DataColumn(ft.Text("湿度[%]"), numeric=True),
ft.DataColumn(ft.Text("標高[m]"), numeric=True),
ft.DataColumn(ft.Text("a0[℃]"), numeric=True),
ft.DataColumn(ft.Text("a1[℃]"), numeric=True),
ft.DataColumn(ft.Text("a2[℃]"), numeric=True),
ft.DataColumn(ft.Text("a3[℃]"), numeric=True),
],
)
realtimeRecordTable=ft.DataTable(
heading_row_height=0,
show_bottom_border=True,
horizontal_margin=0,
columns=[
ft.DataColumn(ft.Text("時間[sec]"), numeric=True),
ft.DataColumn(ft.Text("外気温度[℃]"), numeric=True),
ft.DataColumn(ft.Text("圧力[hPa]"), numeric=True),
ft.DataColumn(ft.Text("湿度[%]"), numeric=True),
ft.DataColumn(ft.Text("標高[m]"), numeric=True),
ft.DataColumn(ft.Text("a0[℃]"), numeric=True),
ft.DataColumn(ft.Text("a1[℃]"), numeric=True),
ft.DataColumn(ft.Text("a2[℃]"), numeric=True),
ft.DataColumn(ft.Text("a3[℃]"), numeric=True),
],
)
async def addRealtimeData(resList, resListFloat):
global rawResponseData
b=ft.DataRow(
cells=[
ft.DataCell(ft.Text(resList[0], selectable=True, max_lines=1, no_wrap=True, size=16), on_tap=lambda e: pyperclip.copy(resList[0])),
ft.DataCell(ft.Text(resList[1], selectable=True, max_lines=1, no_wrap=True, size=16), on_tap=lambda e: pyperclip.copy(resList[1])),
ft.DataCell(ft.Text(resList[2], selectable=True, max_lines=1, no_wrap=True, size=16), on_tap=lambda e: pyperclip.copy(resList[2])),
ft.DataCell(ft.Text(resList[3], selectable=True, max_lines=1, no_wrap=True, size=16), on_tap=lambda e: pyperclip.copy(resList[3])),
ft.DataCell(ft.Text(resList[4], selectable=True, max_lines=1, no_wrap=True, size=16), on_tap=lambda e: pyperclip.copy(resList[4])),
ft.DataCell(ft.Text(resList[5], selectable=True, max_lines=1, no_wrap=True, size=16), on_tap=lambda e: pyperclip.copy(resList[5])),
ft.DataCell(ft.Text(resList[6], selectable=True, max_lines=1, no_wrap=True, size=16), on_tap=lambda e: pyperclip.copy(resList[6])),
ft.DataCell(ft.Text(resList[7], selectable=True, max_lines=1, no_wrap=True, size=16), on_tap=lambda e: pyperclip.copy(resList[7])),
ft.DataCell(ft.Text(resList[8], selectable=True, max_lines=1, no_wrap=True, size=16), on_tap=lambda e: pyperclip.copy(resList[8])),
])
realtimeRecordTable.rows.insert(0, b)
realtimeRecordTable.rows=realtimeRecordTable.rows[:10]
for i in range(0, 9):
realtimeData[i].value=resList[i]
# rtNowData[i].on_click=lambda e: pyperclip.copy(resList[i])
global recordStartTime, takeoffRecordStartTime, takeoffTime, isChargeCompleted, recordListFloatSum, recordListSum, recordTime, recordStartAltitude, recordStatus, recordDataStatus, recordRawData, recordDateTime, recordBaloonName, isRecordStop, r_time, r_temp, r_pressure, r_humidity, r_altitude, r_a0, r_a1, r_a2, r_a3, r_time_str
if isRecordStop==False:
if recordStartTime==-1.00:
recordStartTime=resListFloat[0]
recordRawData+="time[sec], temperature[degC], pressure[hPa], humidity[%], altitude[m], a0, a1, a2, a3\n"
recordBaloonName=baloonSelecter.value
dt_now = datetime.datetime.now()
recordDateTime=copy.deepcopy(dt_now.strftime('%Y-%m-%d_%H-%M-%S'))
recordDataStatus = True
recordList=copy.deepcopy(resList)
recordList[0]='{:.2f}'.format(resListFloat[0]-recordStartTime)
recordList[4]='{:.1f}'.format(resListFloat[4])
recordListFloat=copy.deepcopy(resListFloat)
recordListFloat[0]=round(resListFloat[0]-recordStartTime,2)
recordListFloat[4]=round(resListFloat[4],1)
if isChargeCompleted and recordListFloat[0]>float(takeoffTime) and takeoffRecordStartTime==-1.0:
takeoffRecordStartTime=resListFloat[0]
recordStartAltitude=resListFloat[4]
if recordStatus == False and recordListFloat[0]>float(recordTime)+0.5:
isRecordStop = True
recordRawData="time[sec], temperature[degC], pressure[hPa], humidity[%], altitude[m], a0, a1, a2, a3\n"
for i in range(len(recordListFloatSum)):
tempRecordListFloat = recordListFloatSum[i]
if tempRecordListFloat[0]-takeoffRecordStartTime+recordStartTime == -0.00:
tempRecordListFloat[0]=0.00
else:
tempRecordListFloat[0]=tempRecordListFloat[0]-takeoffRecordStartTime+recordStartTime
tempRecordListFloat[4]=tempRecordListFloat[4]-recordStartAltitude
tempRecordList = ['{:.1f}'.format(k) for k in tempRecordListFloat]
if '{:.2f}'.format(tempRecordListFloat[0]) == '-0.00':
tempRecordList[0] = '0.00'
else:
tempRecordList[0] = '{:.2f}'.format(tempRecordListFloat[0])
recordListFloatSum.append(tempRecordListFloat)
recordListSum.append(tempRecordList)
r_time_str.append(tempRecordList[0])
r_time.append(tempRecordListFloat[0])
r_temp.append(tempRecordListFloat[1])
r_pressure.append(tempRecordListFloat[2])
r_humidity.append(tempRecordListFloat[3])
r_altitude.append(tempRecordListFloat[4])
r_a0.append(tempRecordListFloat[5])
r_a1.append(tempRecordListFloat[6])
r_a2.append(tempRecordListFloat[7])
r_a3.append(tempRecordListFloat[8])
recordRawData+=', '.join(tempRecordList)+"\n"
rawRecorddata_tx.value=recordRawData
tempGraphSystem.visible=True
await tempGraphSystem.update_async()
recordSaveButton.disabled=False #
recordDeleteButton.disabled=False #
recordDeleteTitle.color="red" #
recordDeleteText.color="red" #
recordDeleteIcon.color="red" #
recordStartTitle.value="記録スタート"
recordStartText.value="気体充填開始"
recordStartTitle.color=None
recordStartText.color=None
recordStartIcon.name=ft.icons.RADIO_BUTTON_CHECKED
recordStartIcon.color="red"
recordStartButton.on_click=recordStart
await recordStartTitle.update_async()
await recordStartText.update_async()
await recordStartIcon.update_async()
await recordSaveButton.update_async()
await recordDeleteButton.update_async()
await rawRecorddata_tx.update_async()
await recordSaveButton.focus_async()
await tempGraphSystem.set(time=r_time, temp=r_temp, pressure=r_pressure, humidity=r_humidity, altitude=r_altitude, a0=r_a0, a1=r_a1, a2=r_a2, a3=r_a3)
await openSnackbar("測定データの取得が完了しました。")
else:
recordListSum.append(recordList)
recordListFloatSum.append(recordListFloat)
b=ft.DataRow(
cells=[
ft.DataCell(ft.Text(recordList[0], selectable=True, max_lines=1, no_wrap=True, size=16), on_tap=lambda e: pyperclip.copy(recordList[0])),
ft.DataCell(ft.Text(recordList[1], selectable=True, max_lines=1, no_wrap=True, size=16), on_tap=lambda e: pyperclip.copy(recordList[1])),
ft.DataCell(ft.Text(recordList[2], selectable=True, max_lines=1, no_wrap=True, size=16), on_tap=lambda e: pyperclip.copy(recordList[2])),
ft.DataCell(ft.Text(recordList[3], selectable=True, max_lines=1, no_wrap=True, size=16), on_tap=lambda e: pyperclip.copy(recordList[3])),
ft.DataCell(ft.Text(recordList[4], selectable=True, max_lines=1, no_wrap=True, size=16), on_tap=lambda e: pyperclip.copy(recordList[4])),
ft.DataCell(ft.Text(recordList[5], selectable=True, max_lines=1, no_wrap=True, size=16), on_tap=lambda e: pyperclip.copy(recordList[5])),
ft.DataCell(ft.Text(recordList[6], selectable=True, max_lines=1, no_wrap=True, size=16), on_tap=lambda e: pyperclip.copy(recordList[6])),
ft.DataCell(ft.Text(recordList[7], selectable=True, max_lines=1, no_wrap=True, size=16), on_tap=lambda e: pyperclip.copy(recordList[7])),
ft.DataCell(ft.Text(recordList[8], selectable=True, max_lines=1, no_wrap=True, size=16), on_tap=lambda e: pyperclip.copy(recordList[8])),
])
# table.rows.append(b) kx
# r_time.append(recordListFloat[0])
# r_temp.append(recordListFloat[1])
# r_pressure.append(recordListFloat[2])
# r_humidity.append(recordListFloat[3])
# r_altitude.append(recordListFloat[4])
# r_a0.append(recordListFloat[5])
# r_a1.append(recordListFloat[6])
# r_a2.append(recordListFloat[7])
# r_a3.append(recordListFloat[8])
recordRawData+=', '.join(recordList)+"\n"
rawRecorddata_tx.value=recordRawData
for i in range(0, 9):
rtNowData[i].value=recordList[i]
await table_column.update_async()
await rawRecorddata_tx.update_async()
# await table.update_async() kx
await realtimeTable.update_async()
await realtimeRecordTable.update_async()
await page.update_async()
# rtNowData[0].value=resList[0]
# rtNowData[0].on_click=lambda e: pyperclip.copy(resList[0])
time.append(resListFloat[0])
temp.append(resListFloat[1])
pressure.append(resListFloat[2])
humidity.append(resListFloat[3])
altitude.append(resListFloat[4])
a0.append(resListFloat[5])
a1.append(resListFloat[6])
a2.append(resListFloat[7])
a3.append(resListFloat[8])
if rtRenderSwitch.value:
await realtimeGraphSystem.set(time=time[-100:], temp=temp[-100:], pressure=pressure[-100:], humidity=humidity[-100:], altitude=altitude[-100:], a0=a0[-100:], a1=a1[-100:], a2=a2[-100:], a3=a3[-100:])
# if recordStatus:
# await tempGraphSystem.set(time=r_time, temp=r_temp, pressure=r_pressure, humidity=r_humidity, altitude=r_altitude, a0=r_a0, a1=r_a1, a2=r_a2, a3=r_a3)
#print(resList)
global recordDateTime
recordDateTime=""
recordBaloonName=""
async def addRecordData(resList, resListFloat):
return()
async def event_listener(response):
global rawResponseData
if response.startswith('time'):
await openSnackbar("遠隔データ測定キットに接続しました。データを受信しています。")
rawResponseData+=response[:85]+"\n"
rawdata_tx.value=rawResponseData
await rawdata_tx.update_async()
if (recordDataStatus==False):
recordStartButton.disabled=False
await recordStartButton.update_async()
#print(resList)
#resList
#print(f"Received response: {response}")
# print("Connected.")
page.window_resizable=False
await page.update_async()
return()
else:
rawResponseData+=response+"\n"
rawdata_tx.value=rawResponseData
await rawdata_tx.update_async()
try:
resList=[x.strip() for x in response.split(',')]
resListFloat=[float(x.strip()) for x in response.split(',')]
except Exception as e:
await openSnackbar("エラーが発生しました。不適切なデータを受信した可能性があります。: "+str(e))
print(e)
else:
await addRecordData(resList, resListFloat)
await addRealtimeData(resList, resListFloat)
async def connectPC(e):
global server_url, dir_path
howtoRecordGuide.visible=False
await howtoRecordGuide.update_async()
await tempGraphSystem.setVisibleYes()
# await countupTimer.reset(seconds=0)
if dir_path==None:
page.banner.content=ft.Column(spacing=0, controls=[ft.Text("データの保存先が未指定です。", theme_style=ft.TextThemeStyle.TITLE_LARGE), ft.Text("ファイル>ディレクトリを選択 から、測定したデータの保存先を指定してください。")])
page.banner.open = True
await page.update_async()
return()
await close_banner(e)
page.splash = ft.ProgressBar()
await page.update_async()
global connectStatus, resetFlag
global recordStatus, isRecordStop
connectStatus=True
setuzokuStartButton.text="接続中..."
setuzokusaki.disabled=True
setuzokuStartButton.disabled=True
setuzokuStopButton.disabled=False
time.clear()
temp.clear()
pressure.clear()
humidity.clear()
altitude.clear()
a0.clear()
a1.clear()
a2.clear()
a3.clear()
resetFlag=False
await realtimeGraphSystem.reset()
await setuzokuStartButton.update_async()
await setuzokusaki.update_async()
# await page.update_async()
global bannerContents
try:
response = requests.get(server_url, stream=True, timeout=10)
response.raise_for_status()
print("\nConnected to server: "+server_url+"\n")
page.splash = None
client = response.iter_lines(chunk_size=1, decode_unicode=True)
# await countupTimer.start()
for line in client:
if connectStatus==False:
# await setuzokuStatusView.update_async()
break
# if recordStatus==False:
# isRecordStop=True
# else:
# isRecordStop=False
if recordStatus==True:
isRecordStop=False
if not line:
continue
# print(line)
await event_listener(line)
# if line.startswith('data:'):
# data = line[6:]
# event_listener(data)
except requests.exceptions.RequestException as e:
bannerContents.value=f"エラー内容: {e}"
# eにRead timed outが入っている場合、接続がタイムアウトしたと判断
if "Read timed out" in str(e):
page.banner.content = ft.Column(spacing=0, controls=[ft.Text("測定キットからデータが送られてこなくなりました。", theme_style=ft.TextThemeStyle.TITLE_LARGE), bannerContents])
else:
page.banner.content = ft.Column(spacing=0, controls=[ft.Text("測定キットとの接続に失敗しました。", theme_style=ft.TextThemeStyle.TITLE_LARGE), bannerContents])
page.banner.open = True
asyncio.create_task(page.update_async())
# await disconnectPC(e)
print(f"Error connecting to the server: {e}")
if recordStatus:
await recordStop(e)
connectStatus = False
setuzokuStopButton.disabled=True
await setuzokuStopButton.update_async()
setuzokuStartButton.text="接続開始"
setuzokusaki.disabled=False
setuzokuStartButton.disabled=False
isRecordStop = True
if recordDataStatus:
recordSaveButton.disabled=False #
recordDeleteButton.disabled=False #
recordDeleteTitle.color="red" #
recordDeleteText.color="red" #
recordDeleteIcon.color="red" #
recordStartTitle.value="記録スタート"
recordStartText.value="気体充填開始"
recordStartTitle.color=None
recordStartText.color=None
recordStartIcon.name=ft.icons.RADIO_BUTTON_CHECKED
recordStartButton.disabled=True
recordStartButton.on_click=recordStart
# await countupTimer.stop()
page.window_resizable=True
page.splash = None
await page.update_async()
await recordStartTitle.update_async()
await recordStartText.update_async()
await recordStartIcon.update_async()
await recordSaveButton.update_async()
await recordDeleteButton.update_async()
else:
setuzokusaki.disabled=False
setuzokuStartButton.disabled=False
setuzokuStopButton.disabled=True
# setuzokuStatusView.visible=True
await menubaritem.update_async()
await menubar.update_async()
await page.update_async()
await openSnackbar("遠隔データ測定キットとの接続を終了しました。")
page.banner = ft.Banner(
# bgcolor=ft.colors.AMBER_100,
leading=ft.Icon(ft.icons.WARNING_AMBER_ROUNDED, color=ft.colors.AMBER, size=40),
content=ft.Column(spacing=0, controls=[ft.Text("測定キットとの接続に失敗しました。", theme_style=ft.TextThemeStyle.TITLE_LARGE), bannerContents]),
actions=[
ft.TextButton("再試行", on_click=connectPC),
ft.TextButton("閉じる", on_click=close_banner),
],
)
async def disconnectPC(e):
# global recordStatus
# if recordStatus:
# await openSnackbar("記録中のため、接続終了できません。")
# return()
if recordStatus:
await recordStop(e)
global connectStatus, recordDataStatus
connectStatus = False
setuzokuStopButton.disabled=True
await setuzokuStopButton.update_async()
setuzokuStartButton.text="接続開始"
setuzokusaki.disabled=False
setuzokuStartButton.disabled=False
isRecordStop = True
if recordDataStatus:
recordSaveButton.disabled=False #
recordDeleteButton.disabled=False #
recordDeleteTitle.color="red" #
recordDeleteText.color="red" #
recordDeleteIcon.color="red" #
recordStartTitle.value="記録スタート"
recordStartText.value="気体充填開始"
recordStartTitle.color=None
recordStartText.color=None
recordStartIcon.name=ft.icons.RADIO_BUTTON_CHECKED
recordStartButton.disabled=True
recordStartButton.on_click=recordStart
await recordStartTitle.update_async()
await recordStartText.update_async()
await recordStartIcon.update_async()
await recordSaveButton.update_async()
await recordDeleteButton.update_async()
# await countupTimer.stop()
page.window_resizable=True
page.splash = None
await page.update_async()
class Countdown(ft.UserControl):
def __init__(self, seconds):
super().__init__()
self.seconds = seconds
async def did_mount_async(self):
self.running = True
asyncio.create_task(self.update_timer())
async def will_unmount_async(self):
self.running = False
async def update_timer(self):
while self.seconds and self.running:
# mins, secs = divmod(self.seconds, 60)
self.countdown.value = "{:.1f}".format(self.seconds)
self.seconds -= 0.5
await self.update_async()
await asyncio.sleep(0.5)
def build(self):
self.countdown = ft.Text()
return self.countdown
async def open_settings(e):
page.dialog = dlg_modal
dlg_modal.open = True
await page.update_async()
async def close_resetAlert(e):
resetAlert.open = False
await page.update_async()
async def rtReset(e):
global recordStartTime, recordStatus, recordStartAltitude, connectStatus, resetFlag
if recordStatus:
await openSnackbar("記録中のため、リセットできません。")
return()
if connectStatus:
await openSnackbar("接続中のため、リセットできません。")
return()
global recordStopWatchSystem
recordTime=recordStopWatchSystem.stop()
recordStopWatchSystem.reset()
sensorLocationA0.value=None
await page.client_storage.remove_async("sensorLocation_a0")
recordTimeView.value="-"
await recordTimeView.update_async()
global rawResponseData, recordRawData, recordDataStatus
realtimeRecordTable.rows.clear()
# table.rows.clear() kx
global takeoffRecordStartTime, takeoffTime, recordListSum, recordListFloatSum, isChargeCompleted
takeoffRecordStartTime=-1.0
takeoffTime=-1.0
recordListSum=[]
recordListFloatSum=[]
isChargeCompleted=False
chargeTimeView.value="-"
airTimeView.value="-"
await chargeTimeView.update_async()
await airTimeView.update_async()
time.clear()
temp.clear()
pressure.clear()
humidity.clear()
altitude.clear()
a0.clear()
a1.clear()
a2.clear()
a3.clear()
r_time.clear()
r_time_str.clear()
r_temp.clear()
r_pressure.clear()
r_humidity.clear()
r_altitude.clear()
r_a0.clear()
r_a1.clear()
r_a2.clear()
r_a3.clear()
for i in range(0, 9):
rtNowData[i].value="-"
realtimeData[i].value="-"
rtNowData[i].on_click=lambda e: pyperclip.copy("-")
rawResponseData=""
recordRawData=""
rawdata_tx.value=""
rawRecorddata_tx.value=""
recordDeleteTitle.color=None
recordDeleteText.color=None
recordDeleteIcon.color=None
recordStartTime=-1.0
recordStartAltitude=0.0
recordStatus=False
recordDataStatus=False
baloonSelecter.value=None
recordStartButton.disabled=True
recordSaveButton.disabled=True
recordDeleteButton.disabled=True
recordNote.value=""
if resetFlag == False:
await tempGraphSystem.reset()
tempGraphSystem.visible=False
howtoRecordGuide.visible=True
await tempGraphSystem.update_async()
await howtoRecordGuide.update_async()
resetFlag=True
await realtimeGraphSystem.reset()
await close_resetAlert(e)
# await table.update_async() kx
await rawRecorddata_tx.update_async()
await table_column.update_async()
await realtimeTable.update_async()
await realtimeRecordTable.update_async()
await baloonSelecter.update_async()
await recordStartButton.update_async()
await recordSaveButton.update_async()
await recordDeleteButton.update_async()
await page.update_async()
resetAlert = ft.AlertDialog(
modal=True,
title=ft.Text("これまでのデータを削除しますか?"),
content=ft.Text("測定キットから送られてきたデータを全て削除します。"),
actions=[
ft.TextButton("削除する", on_click=rtReset),
ft.TextButton("削除しない", on_click=close_resetAlert),
],
actions_alignment=ft.MainAxisAlignment.END,
# on_dismiss=lambda e: print("Modal dialog dismissed!"),
)
async def open_resetAlert(e):
global recordStartTime, recordStatus
if recordStatus:
await openSnackbar("記録中のため、リセットできません。")
return()
page.dialog = resetAlert
resetAlert.open = True
await page.update_async()
if server_url==None:
setuzokusaki=ElevatedButton(f"接続先: 未設定です。クリックして設定してください。", on_click=open_settings, disabled=connectStatus)
setuzokuStartButton=ElevatedButton(f"接続開始", on_click=connectPC, disabled=True)
else:
setuzokusaki=ElevatedButton(f"接続先: {server_url}", on_click=open_settings, disabled=connectStatus)
setuzokuStartButton=ElevatedButton(f"接続開始", on_click=connectPC, disabled=connectStatus)
setuzokuStopButton=ElevatedButton(f"接続終了", on_click=disconnectPC, disabled=True)
rtResetButton=ft.ElevatedButton(text="リセット", on_click=rtReset, data=0)
# countupTimer=Countup(0)
await page.add_async(
ft.Row(
spacing=5,
controls=[
# Text("EBDAS"),
ft.Image(
src=f"ebdas.png",
# width=100,
height=50,
fit=ft.ImageFit.FIT_HEIGHT,
),
setuzokusaki,
setuzokuStartButton,
setuzokuStopButton,
rtResetButton,
rtRenderSwitch,
# rtAutoScSwitch
# ft.Text("接続時間:"),
],
)
)
async def close_dlg(e):
dlg_modal.open = False
await page.update_async()
async def save_settings(e):
global server_url
if not txt_hontai_ip.value:
txt_hontai_ip.error_text = "入力してください。"
await page.update_async()
return()
else:
txt_hontai_ip.error_text = ""
# if not txt_hontai_port.value:
# txt_hontai_port.error_text = "入力してください。"
# await page.update_async()
# return()
# else:
# txt_hontai_port.error_text = ""
await page.client_storage.set_async("hontai_ip", txt_hontai_ip.value)
server_url = txt_hontai_ip.value
# await page.client_storage.set_async("hontai_port", txt_hontai_port.value)
setuzokusaki.text=f"接続先: {txt_hontai_ip.value}"
setuzokusaki.disabled=False
setuzokuStartButton.disabled=False
await openSnackbar("設定を保存しました。")
dlg_modal.open = False
await page.update_async()
txt_hontai_ip = TextField(label="測定キット本体のアドレス", value=await page.client_storage.get_async("hontai_ip"), hint_text="http://KIT38Mikan.local:80")
# txt_hontai_port = TextField(label="測定キット本体のポート番号", value=await page.client_storage.get_async("hontai_port"))
dlg_modal = ft.AlertDialog(
modal=True,
title=ft.Text("設定"),
content=txt_hontai_ip,
actions=[
ft.TextButton("保存", on_click=save_settings),
ft.TextButton("キャンセル", on_click=close_dlg),
],
actions_alignment=ft.MainAxisAlignment.END,
#on_dismiss=lambda e: print("Modal dialog dismissed!"),
)
rtNowData=[
ft.Text("-", selectable=True, max_lines=1, no_wrap=True, weight=ft.FontWeight.BOLD, size=18),
ft.Text("-", selectable=True, max_lines=1, no_wrap=True, weight=ft.FontWeight.BOLD, size=18),
ft.Text("-", selectable=True, max_lines=1, no_wrap=True, weight=ft.FontWeight.BOLD, size=18),
ft.Text("-", selectable=True, max_lines=1, no_wrap=True, weight=ft.FontWeight.BOLD, size=18),
ft.Text("-", selectable=True, max_lines=1, no_wrap=True, weight=ft.FontWeight.BOLD, size=18),
ft.Text("-", selectable=True, max_lines=1, no_wrap=True, weight=ft.FontWeight.BOLD, size=18),
ft.Text("-", selectable=True, max_lines=1, no_wrap=True, weight=ft.FontWeight.BOLD, size=18),
ft.Text("-", selectable=True, max_lines=1, no_wrap=True, weight=ft.FontWeight.BOLD, size=18),
ft.Text("-", selectable=True, max_lines=1, no_wrap=True, weight=ft.FontWeight.BOLD, size=18),
]
realtimeData=[
ft.Text("-", selectable=True, max_lines=1, no_wrap=True, weight=ft.FontWeight.BOLD, size=18),
ft.Text("-", selectable=True, max_lines=1, no_wrap=True, weight=ft.FontWeight.BOLD, size=18),
ft.Text("-", selectable=True, max_lines=1, no_wrap=True, weight=ft.FontWeight.BOLD, size=18),
ft.Text("-", selectable=True, max_lines=1, no_wrap=True, weight=ft.FontWeight.BOLD, size=18),
ft.Text("-", selectable=True, max_lines=1, no_wrap=True, weight=ft.FontWeight.BOLD, size=18),
ft.Text("-", selectable=True, max_lines=1, no_wrap=True, weight=ft.FontWeight.BOLD, size=18),
ft.Text("-", selectable=True, max_lines=1, no_wrap=True, weight=ft.FontWeight.BOLD, size=18),
ft.Text("-", selectable=True, max_lines=1, no_wrap=True, weight=ft.FontWeight.BOLD, size=18),
ft.Text("-", selectable=True, max_lines=1, no_wrap=True, weight=ft.FontWeight.BOLD, size=18),
]
projectTitle = ft.Text("プロジェクト: -")
projectDirectory = ft.Text("保存先: -" if await page.client_storage.contains_key_async("directory_path") == False or await page.client_storage.get_async("directory_path")=="" else "保存先: "+ await page.client_storage.get_async("directory_path"))
projectFlyCount = ft.Text("飛行回数: -")
if await page.client_storage.contains_key_async("baloon") == True and await page.client_storage.get_async("baloon")!=None:
if await page.client_storage.contains_key_async("hontai_ip") == False or await page.client_storage.get_async("hontai_ip")==None:
await openSnackbar("接続先が未設定です。")
await page.client_storage.remove_async("baloon")
await page.update_async()
return()
if await page.client_storage.contains_key_async("directory_path") == False or await page.client_storage.get_async("directory_path")=="":
await openSnackbar("ディレクトリが指定されていません。保存先を設定してください。")
await page.client_storage.remove_async("baloon")
await page.update_async()
return()
if os.path.isdir(await page.client_storage.get_async("directory_path")+"/"+await page.client_storage.get_async("baloon")) == False:
await openSnackbar("ディレクトリが存在しません。")
await page.client_storage.remove_async("baloon")
await page.update_async()
return()
baloonSelecter.value=await page.client_storage.get_async("baloon")
projectTitle.value = f"プロジェクト名: {baloonSelecter.value}"
if connectStatus==True and ((recordStatus==False and recordDataStatus==True) or recordDataStatus==False):
recordStartButton.disabled=False
await recordStartButton.update_async()
await page.update_async()
async def openFilePicker(e):
await get_directory_dialog.get_directory_path_async(dialog_title="測定したデータを保存するディレクトリを選択してください。")
recordTimeView = ft.Text("-", selectable=True, max_lines=1, no_wrap=True, weight=ft.FontWeight.BOLD, size=18)
chargeTimeView = ft.Text("-", selectable=True, max_lines=1, no_wrap=True, weight=ft.FontWeight.BOLD, size=18)
airTimeView = ft.Text("-", selectable=True, max_lines=1, no_wrap=True, weight=ft.FontWeight.BOLD, size=18)