-
Notifications
You must be signed in to change notification settings - Fork 0
/
machine.py
1405 lines (1194 loc) · 46.8 KB
/
machine.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 hashlib
# import datetime
import json
import os
import psutil
import psycopg2
import psycopg2.extras
import re
import re
import requests
import socketio
import subprocess
import threading
import time
from datetime import datetime, time, date
from flask import Flask, render_template, request, redirect, url_for, jsonify, json, session
from flask_login import LoginManager, login_user, logout_user, current_user, login_required, LoginManager, UserMixin
from flask_socketio import SocketIO, emit
app = Flask(__name__)
app.secret_key = 'mark'
clients = {}
photo = ''
socketio = SocketIO(app)
global running_process
running_process = None
# Database configuration
db_host = 'localhost'
db_port = 5432
db_name = 'machine_automation_tbl'
db_user = 'flask_user'
db_password = '-clear1125'
# Programs configuration
programs = []
# Connect to the database
conn = psycopg2.connect(
host=db_host,
port=db_port,
dbname=db_name,
user=db_user,
password=db_password
)
cur = conn.cursor()
login_manager = LoginManager()
login_manager.init_app(app)
class User(UserMixin):
def __init__(self, id, firstname, lastname, username, fullname, employee_department, photo_url):
self.id = id
self.firstname = firstname
self.lastname = lastname
self.username = username
self.fullname = fullname
self.employee_department = employee_department
self.photo_url = photo_url
def get_id(self):
return str(self.id)
def is_active(self):
return True
@login_manager.user_loader
def load_user(user_id):
firstname = session.get('firstname')
lastname = session.get('lastname')
username = session.get('username')
fullname = session.get('fullname')
employee_department = session.get('employee_department')
photo_url = session.get('photo_url')
return User(user_id, firstname, lastname, username, fullname, employee_department, photo_url)
def view_table_func(self):
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cursor.execute(
"SELECT * FROM machine_tbl WHERE id IN (SELECT MAX(id) FROM machine_tbl GROUP BY name)")
total_count = cursor.fetchall()
return total_count
@app.route('/', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
form_username = request.form['username']
form_password = request.form['password']
if form_username == '' and form_password == '':
return """<script>
alert('Error')
</script>"""
else:
url = f"http://hris.teamglac.com/api/users/login?u={form_username}&p={form_password}"
response = requests.get(url).json()
if response['result'] == False:
return render_template('auth-login.html')
else:
user_data = response["result"]
session['firstname'] = user_data['firstname']
session['lastname'] = user_data['lastname']
session['username'] = user_data['username']
session['fullname'] = user_data['fullname']
session['employee_department'] = user_data['employee_department']
photo_url = session['photo_url'] = user_data['photo_url']
user_id = user_data['user_id']
user = User(user_id, user_data['firstname'], user_data['lastname'], user_data['username'],
user_data['fullname'], user_data['employee_department'], user_data['photo_url'])
# Login the user
login_user(user)
if photo_url == False or photo_url is None:
session['photo_url'] = """assets/compiled/jpg/1.jpg"""
else:
hris = "http://hris.teamglac.com/"
session['photo_url'] = hris + user_data['photo_url']
return redirect(url_for('index', success=True))
else:
# Display the login form
return render_template('auth-login.html')
@app.route('/machines')
def get_machines():
try:
cursor = conn.cursor()
cursor.execute("""
SELECT
id,
fetched_ip,
controller_name
FROM
fetched_ip_tbl
WHERE
id IN (SELECT MAX(id) FROM
fetched_ip_tbl
GROUP BY controller_name )
""")
rows = cursor.fetchall()
machines = []
for row in rows:
machines.append({
'id': row[0],
'fetched_ip': row[1],
'controller_name': row[2]
})
conn.commit() # Commit the transaction before closing the cursor
cursor.close()
return jsonify({'data': machines})
except Exception as e:
conn.rollback() # Rollback the transaction in case of an error
cursor.close()
print("Error executing query:", e)
return jsonify({'error': 'An error occurred while fetching machines.'}), 500
@app.route('/category')
def get_category():
cursor = conn.cursor()
cursor.execute("SELECT * FROM category_uph_tbl;")
rows = cursor.fetchall()
category_data = []
for row in rows:
category_data.append({
'id': row[0],
'category': row[1],
'uph': row[2]
})
cursor.close()
return jsonify({'data': category_data})
@app.route('/get_name', methods=['GET', 'POST'])
def get_name():
item_id = int(request.form['id']) # Retrieve ID from the request form data
# Perform a database query to fetch the fetched_ip based on the item ID
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cursor.execute(
"SELECT fetched_ip FROM fetched_ip_tbl WHERE id = %s", (item_id,))
result = cursor.fetchone()
# Check if result is not empty
if result:
# Fetch the 'fetched_ip' value from the result dictionary
ip = result['fetched_ip']
# Perform another database query using the ip
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cursor.execute("""
SELECT
id,
fetched_ip,
status,
sid,
port,
machine_name,
area,
controller_name
FROM
fetched_ip_tbl
WHERE
id IN (SELECT MAX(id) FROM
fetched_ip_tbl
GROUP BY port)
ORDER BY
id
DESC LIMIT 5
""", (ip,))
rows = cursor.fetchall()
machines = []
for row in rows:
machines.append({
'id': row[0],
'fetched_ip': row[1],
'status': row[2],
'sid': row[3],
'port': row[4],
'machine_name': row[5],
'area': row[6],
'controller_name': row[7],
})
conn.commit()
cursor.close()
return jsonify({'data': machines})
else:
return jsonify(result=None)
@app.route('/insert_machine_name', methods=['POST'])
def insert_machine_name():
cursor = conn.cursor()
form_id = request.form['id']
machine_name = request.form['selectMachineName']
area_var = request.form['selectArea']
cursor.execute(f"""UPDATE
public.fetched_ip_tbl
SET machine_name = '{machine_name}',
area = '{area_var}'
WHERE id = '{form_id}'""")
conn.commit()
cursor.close()
data = {
'form_id': form_id,
'machine_name': machine_name,
'area_var': area_var
}
return jsonify({'data': data})
@app.route('/insert_controller', methods=['POST'])
def insert_controller():
cursor = conn.cursor()
form_ip = request.form['ip']
controller_name_var = request.form['controllerInput']
cursor.execute(f"""UPDATE
public.fetched_ip_tbl
SET controller_name = '{controller_name_var}'
WHERE fetched_ip = '{form_ip}'""")
conn.commit()
cursor.close()
data = {
'form_ip': form_ip,
'controller_name_var': controller_name_var,
}
return jsonify({'data': data})
@app.route('/card_details_table')
def card_details_table():
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cursor.execute("""
SELECT
mdt.mo as MO,
mdt.emp_no as EMP_NO,
mdt.running_qty as RUNNING_QTY,
fit.start_date as START_TIME,
mdt.start_date as MACHINE_START_DATE,
mdt.class as MACHINE_NAME
FROM
public.fetched_ip_tbl AS fit
LEFT JOIN
public.machine_fetched_data_tbl AS mdt
ON
fit.port = mdt.class
""")
dataResult = cursor.fetchall()
capturedDatas = []
for data in dataResult:
capturedData = {
'MO': row[0],
'EMP_NO': row[1],
'RUNNING_QTY': row[2],
'START_TIME': row[3],
'MACHINE_START_DATE': row[4],
'MACHINE_NAME': row[5]
}
capturedDatas.append(capturedData)
cursor.close()
return jsonify({'data': capturedDatas})
@app.route('/delete_data', methods=['POST'])
def insert_data():
cursor = conn.cursor()
id = request.form['id']
cursor.execute("DELETE FROM machine_data_tbl WHERE id = %s", (id,))
conn.commit()
cursor.close()
return jsonify({'success': True})
@app.route('/card_details')
def get_card_details():
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cursor.execute("""
SELECT
t1.id,
t1.device_id,
t1.status,
t1.operator,
t1.assigned_gl,
t1.operation_code,
t1.operation,
t1.area
FROM machine_data_tbl t1
INNER JOIN (
SELECT device_id, MAX(id) AS max_id
FROM machine_data_tbl
GROUP BY device_id
) t2 ON t1.id = t2.max_id;
""")
result = cursor.fetchall()
cursor.close()
# Convert data to a list of dictionaries
container = []
for row in result:
data = {
'MO': row[0],
'EMP_NO': row[1],
'RUNNING_QTY': row[2],
'START_TIME': row[3],
'MACHINE_START_DATE': row[4],
'MACHINE_NAME': row[5]
}
container.append(data)
return jsonify(container)
@app.route('/card_details_wirebond')
def card_details_wirebond():
try:
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cursor.execute("""
SELECT
fit.id,
fit.area,
fit.port,
fit.controller_name,
fit.status,
mdt.mo,
mdt."totalProccessQty",
mdt.operation,
mdt.machine_name,
mdt.photo,
mdt."operatorIdNum",
fit.machine_name as machine,
mdt.status as mdt_status,
mdt.start_time,
mdt.stop_time,
CASE
WHEN stop_time IS NOT NULL THEN
CONCAT(
LPAD(EXTRACT(HOUR FROM (stop_time - start_time))::TEXT, 2, '0'), ':',
LPAD(EXTRACT(MINUTE FROM (stop_time - start_time))::TEXT, 2, '0'), ':',
LPAD(EXTRACT(SECOND FROM (stop_time - start_time))::TEXT, 2, '0')
)
ELSE
CONCAT(
LPAD(EXTRACT(HOUR FROM (NOW() - start_time))::TEXT, 2, '0'), ':',
LPAD(EXTRACT(MINUTE FROM (NOW() - start_time))::TEXT, 2, '0'), ':',
LPAD(EXTRACT(SECOND FROM (NOW() - start_time))::TEXT, 2, '0')
)
END AS total_running_time,
fit.start_date as fit_start_date,
fit.stop_date as fit_stop_date
FROM
public.fetched_ip_tbl AS fit
LEFT JOIN public.machine_data_tbl AS mdt ON fit.port = mdt.machine_name
WHERE
fit.area IN ('Wirebond', 'WIREBOND', 'wirebond')""")
card_data = cursor.fetchall()
cursor.close()
# Convert data to a list of dictionaries
cards = []
for row in card_data:
card = {
'id': row[0],
'area': row[1],
'port': row[2],
'controller_name': row[3],
'status': row[4],
'mo': row[5],
'totalProccessQty': row[6],
'operation': row[7],
'machine_name': row[8],
'photo': row[9],
'operatorIdNum': row[10],
'machine': row[11],
'mdt_status': row[12],
'start_time': row[13].strftime('%H:%M:%S') if row[13] is not None else None,
'stop_time': row[14].strftime('%H:%M:%S') if row[14] is not None else None,
'duration': str(row[15]) if row[15] is not None else None,
'fit_start_date': row[16].strftime('%H:%M:%S') if row[16] is not None else None,
'fit_stop_date': row[17].strftime('%H:%M:%S') if row[17] is not None else None
}
cards.append(card)
return jsonify(cards)
except psycopg2.Error as e:
conn.rollback() # Rollback the transaction in case of an error
return "An error occurred while processing the request.", 500
@app.route('/card_details_eol1')
def card_details_eol1():
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cursor.execute("""
SELECT
fit.status as STATUS,
mdt.mo as MO,
mdt.emp_no as EMP_NO,
mdt.running_qty as RUNNING_QTY,
fit.start_time as START_TIME,
fit.idle_time as IDLE_TIME,
mdt.start_date as MACHINE_START_DATE,
mdt.class as MACHINE_NAME
FROM
public.fetched_ip_tbl AS fit
LEFT JOIN
public.machine_fetched_data_tbl AS mdt
ON
fit.port = mdt.class
WHERE
fit.area = 'Eol1' OR fit.area = 'EOL1'
""")
card_data = cursor.fetchall()
cursor.close()
# Convert data to a list of dictionaries
cards = []
for row in card_data:
machine_start_date = None
if row[6] is not None:
machine_start_date = datetime.strptime(row[6], '%Y-%m-%d %H:%M:%S.%f').time()
card = {
'STATUS': row[0],
'MO': row[1],
'EMP_NO': row[2],
'RUNNING_QTY': row[3],
'IDLE_TIME': row[4],
'START_TIME': row[5].strftime('%H:%M:%S') if row[5] is not None else None,
'MACHINE_START_DATE': machine_start_date.strftime('%H:%M:%S') if machine_start_date else None,
'MACHINE_NAME': row[7]
}
cards.append(card)
return jsonify(cards)
@app.route('/card_details_eol2')
def card_details_eol2():
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cursor.execute("""
SELECT
mdt.mo as MO,
mdt.emp_no as EMP_NO,
mdt.running_qty as RUNNING_QTY,
fit.start_time as START_TIME,
mdt.start_date as MACHINE_START_DATE,
mdt.class as MACHINE_NAME
FROM
public.fetched_ip_tbl AS fit
LEFT JOIN
public.machine_fetched_data_tbl AS mdt
ON
fit.port = mdt.class
WHERE
fit.area = 'Eol2' OR fit.area = 'eol2'
""")
card_data = cursor.fetchall()
cursor.close()
# Convert data to a list of dictionaries
cards = []
for row in card_data:
card = {
'MO': row[0],
'EMP_NO': row[1],
'RUNNING_QTY': row[2],
'START_TIME': row[3],
'MACHINE_START_DATE': row[4],
'MACHINE_NAME': row[5]
}
cards.append(card)
return jsonify(cards)
@app.route('/card_details_mold')
def card_details_mold():
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cursor.execute("""
SELECT
mdt.mo as MO,
mdt.emp_no as EMP_NO,
mdt.running_qty as RUNNING_QTY,
fit.start_time as START_TIME,
mdt.start_date as MACHINE_START_DATE,
mdt.class as MACHINE_NAME
FROM
public.fetched_ip_tbl AS fit
LEFT JOIN
public.machine_fetched_data_tbl AS mdt
ON
fit.port = mdt.class
WHERE
fit.area = 'Mold' OR fit.area = 'mold'
""")
card_data = cursor.fetchall()
cursor.close()
# Convert data to a list of dictionaries
cards = []
for row in card_data:
card = {
'MO': row[0],
'EMP_NO': row[1],
'RUNNING_QTY': row[2],
'START_TIME': row[3],
'MACHINE_START_DATE': row[4],
'MACHINE_NAME': row[5]
}
cards.append(card)
return jsonify(cards)
@app.route('/card_details_die_prep')
def card_details_die_prep():
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cursor.execute("""
SELECT
mdt.mo as MO,
mdt.emp_no as EMP_NO,
mdt.running_qty as RUNNING_QTY,
fit.start_time as START_TIME,
mdt.start_date as MACHINE_START_DATE,area_var
mdt.class as MACHINE_NAME
FROM
public.fetched_ip_tbl AS fit
LEFT JOIN
public.machine_fetched_data_tbl AS mdt
ON
fit.port = mdt.class
WHERE
fit.area = 'Die Prep' OR fit.area = 'Die Prep'
""")
card_data = cursor.fetchall()
cursor.close()
# Convert data to a list of dictionaries
cards = []
for row in card_data:
card = {
'MO': row[0],
'EMP_NO': row[1],
'RUNNING_QTY': row[2],
'START_TIME': row[3],
'MACHINE_START_DATE': row[4],
'MACHINE_NAME': row[5]
}
cards.append(card)
return jsonify(cards)
@app.route('/card_details_die_attached')
def card_details_die_attached():
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cursor.execute("""
SELECT
mdt.mo as MO,
mdt.emp_no as EMP_NO,
mdt.running_qty as RUNNING_QTY,
fit.start_time as START_TIME,
mdt.start_date as MACHINE_START_DATE,
mdt.class as MACHINE_NAME
FROM
public.fetched_ip_tbl AS fit
LEFT JOIN
public.machine_fetched_data_tbl AS mdt
ON
fit.port = mdt.class
WHERE
fit.area = 'Eol1' OR fit.area = 'Die Attach'
""")
card_data = cursor.fetchall()
cursor.close()
# Convert data to a list of dictionaries
cards = []
for row in card_data:
card = {
'MO': row[0],
'EMP_NO': row[1],
'RUNNING_QTY': row[2],
'START_TIME': row[3],
'MACHINE_START_DATE': row[4],
'MACHINE_NAME': row[5]
}
cards.append(card)
return jsonify(cards)
@app.route('/machines/delete', methods=['POST'])
def delete_machine():
cursor = conn.cursor()
id = request.form['id']
cursor.execute("DELETE FROM fetched_ip_tbl WHERE id = %s", (id,))
conn.commit()
cursor.close()
return jsonify({'success': True})
@app.route('/showHistory', methods=['POST'])
def showHistory():
port = request.json['name']
print(port)
today = date.today()
print(today)
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cursor.execute(f"""
SELECT
id as ID,
port as PORT,
fetched_ip as IP,
status as STATUS,
status_date_changed as STATUS_DATE_CHANGED
FROM
fetched_ip_tbl
WHERE
status_date_changed
BETWEEN
'{today} 06:00'::timestamp AND '{today} 18:00'::timestamp
AND port = '{port}'
ORDER BY id DESC
""" )
result = cursor.fetchall()
cursor.close()
# Convert data to a list of dictionaries
data = []
for row in result:
card = {
'ID': row[0],
'PORT': row[1],
'IP': row[2],
'STATUS': row[3],
'STATUS_DATE_CHANGED': row[4]
}
data.append(card)
return jsonify(data)
# @app.route('/update_ip_data', methods=['POST'])
# def update_ip_data():
# status = request.json['message']
# stop_date = request.json['stop_date']
# sid = request.json['sid']
# cur.execute(f"UPDATE public.fetched_ip_tbl SET status ='{status}', stop_time='{stop_date}' WHERE sid='{sid}'")
# conn.commit()
# return jsonify("Data updated successfully in the database")
@app.route('/stop_update', methods=['POST'])
def stop_update():
try:
machine_name = request.json["machine_name"]
print(f"==>> machine_name: {machine_name}")
remove_py = re.sub('.py', '', machine_name)
client_ip = request.json["client_ip"]
message = request.json["message"]
sid = request.json["sid"]
stop_date = request.json["stop_date"]
fetchedGetDate = stop_date
with conn.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
cur.execute(
'INSERT INTO public.fetched_ip_tbl (fetched_ip, status, sid, port, status_date_changed) VALUES (%s, %s, %s, %s, %s)',
(client_ip, message, sid, remove_py, stop_date))
conn.commit()
return jsonify("Data inserted successfully into the database")
except psycopg2.Error as e:
error_message = "Error inserting data into the database: " + str(e)
conn.rollback()
return jsonify(error_message)
@app.route('/idle_update', methods=['POST'])
def function_idle_update():
try:
machine_name = request.json["machine_name"]
print(f"==>> machine_name: {machine_name}")
remove_py = re.sub('.py', '', machine_name)
client_ip = request.json["client_ip"]
status = request.json["status"]
sid = request.json["sid"]
idle_date = request.json['idle_date']
with conn.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
cur.execute(
'INSERT INTO public.fetched_ip_tbl (fetched_ip, status, sid, port, status_date_changed) VALUES (%s, %s, %s, %s, %s)',
(client_ip, status, sid, remove_py, idle_date))
conn.commit()
return jsonify("Data inserted successfully into the database")
except Exception as e:
return jsonify("Error updating data in the database: " + str(e))
# @app.route('/insert_ip_data', methods=['POST'])
# def insert_ip_data():
# try:
# machine_name = request.json["machine_name"]
# remove_py = re.sub('.py', '', machine_name)
# fetched_ip = request.json["fetched_ip"]
# status = request.json["status"]
# fetched_sid = request.json["fetched_sid"]
# get_start_date = request.json["get_start_date"]
# fetchedGetDate = get_start_date
# # fetchedStartDate = get_card_details()
# cur.execute(
# "SELECT COUNT(port) FROM public.fetched_ip_tbl WHERE port = %s", (remove_py,))
# count = cur.fetchone()[0]
# if count > 0:
# # data already exists, update
# cur.execute("UPDATE public.fetched_ip_tbl SET status = %s, start_time = %s, port = %s WHERE sid= %s",
# (status, fetchedGetDate, remove_py, fetched_sid))
# conn.commit() # commit the transaction
# return jsonify("Data updated successfully in the database")
# else:
# # data doesn't exist, insert
# cur.execute(
# "INSERT INTO public.fetched_ip_tbl (fetched_ip, status, sid, port, start_time) VALUES (%s, %s, %s, %s, %s)",
# (fetched_ip, status, fetched_sid, remove_py, fetchedGetDate))
# conn.commit() # commit the transaction
# return jsonify("Data inserted successfully into the database")
# except Exception as e:
# conn.rollback() # rollback the transaction if an error occurs
# return jsonify("An error occurred while inserting/updating data")
@app.route('/insert_ip_data', methods=['POST'])
def insert_ip_data():
try:
# Fetch data from the request
data = request.json
machine_name = data["machine_name"]
remove_py = re.sub('.py', '', machine_name)
fetched_ip = data["fetched_ip"]
status = data["status"]
fetched_sid = data["fetched_sid"]
get_start_date = data["get_start_date"]
fetched_get_date = get_start_date
with conn.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
cur.execute(
"INSERT INTO public.fetched_ip_tbl (fetched_ip, status, sid, port, status_date_changed) VALUES (%s, %s, %s, %s, %s)",
(fetched_ip, status, fetched_sid, remove_py, fetched_get_date))
conn.commit()
return jsonify("Data inserted successfully into the database")
except psycopg2.Error as e:
error_message = "Error inserting data into the database: " + str(e)
conn.rollback()
return jsonify(error_message)
except Exception as e:
error_message = "An error occurred: " + str(e)
return jsonify(error_message)
@app.route('/request_data', methods=['POST'])
def request_data():
data = request.get_json()
socketio.emit('dataPassed', {'data': data})
return jsonify(data=data)
@app.route('/getMachinesNamesApi')
def getMachinesNamesApi():
url = 'http://cmms.teamglac.com/apimachine2.php'
response = requests.get(url)
data = json.loads(response.text)['data']
classes = set() # Create a set to store unique values
for rec in data:
classes.add(rec['CLASS'])
unique_classes = list(classes)
return jsonify(unique_classes)
@app.route('/insertController', methods=['POST'])
def insertController():
controllerInput = request.form['controllerInput']
try:
with conn.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
cur.execute(
'INSERT INTO public.controllers_tbl (controller_name) VALUES (%s)',
(controllerInput,))
conn.commit()
return jsonify("Data inserted successfully into the database")
except psycopg2.Error as e:
error_message = "Error inserting data into the database: " + str(e)
conn.rollback()
return jsonify(error_message)
@app.route('/insertMachinesToController')
def insertMachinesToController():
cursor = conn.cursor()
cursor.execute("""
SELECT
id,
fetched_ip,
status,
sid,
port,
machine_name,
area,
start_time,
stop_time
FROM public.fetched_ip_tbl ORDER BY id ASC
""")
rows = cursor.fetchall()
machines = []
for row in rows:
start_date = row[7].strftime('%H:%M:%S') if row[7] is not None else None
stop_date = row[8].strftime('%H:%M:%S') if row[8] is not None else None
machines.append({
'id': row[0],
'fetched_ip': row[1], # Change 'machine_name' to 'text' for Select2 compatibility
'status': row[2],
'sid': row[3],
'port': row[4],
'machine_name': row[5],
'area': row[6],
'start_time': start_time,
'stop_date': stop_date
})
cursor.close()
return jsonify({'results': machines}) # Use 'results' instead of 'data' for Select2
@app.route('/processSelectedData', methods=['POST'])
def process_selected_data():
selected_data = request.form.get('selectedDataArray')
view_data = json.loads(selected_data)
# print(f"==>> view_data: {view_data}")
dataControllerID = int(request.form.get('dataControllerID').strip('"'))
# print(f"==>> dataControllerID: {dataControllerID}")
try:
with conn.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
for item in view_data:
value1 = item['port']
# print(f"==>> value1: {value1}")
value2 = item['id']
# print(f"==>> value2: {value2}")
if not value1 or not value2:
# Either value1 or value2 is empty, skip this iteration
continue
# Check if the combination of machine_id and controller_id already exists
cur.execute(
"SELECT COUNT(*) FROM public.controller_with_machine_tbl WHERE machine_id = %s AND controller_id = %s",
(value2, dataControllerID))
count = cur.fetchone()[0]
if count > 0:
msg = 1
return jsonify({'data': msg})
# Insert the data if it doesn't already exist
cur.execute(
"INSERT INTO public.controller_with_machine_tbl (machine_id, controller_id) VALUES (%s, %s)",
(value2, dataControllerID))
conn.commit()
msg = 0
return jsonify({'data': msg})
except psycopg2.Error as e:
error_message = "Error inserting data into the database: " + str(e)
conn.rollback()
return jsonify(error_message)
@app.route('/viewControllerResult', methods=['POST'])
def viewControllerResult():
data_id = int(request.form.get('data_id').strip('"'))
cursor = conn.cursor()
cursor.execute("""
SELECT
a.id as ID,
a.fetched_ip as FETCHED_IP,
a.status as STATUS,
a.sid as SID,
a.port as PORT,
a.machine_name as MACHINE_NAME,
a.area as AREA,
a.start_time as START_DATE,
a.stop_time as STOP_DATE,
b.remarks as REMARKS
FROM (
SELECT
a.id,
a.status,
a.start_time,
a.stop_time,
a.sid,
a.fetched_ip,
a.area,
a.port,
a.machine_name,
b.controller_id
FROM
public.fetched_ip_tbl a
LEFT JOIN
public.controller_with_machine_tbl b
ON
a.id = b.machine_id
) a
LEFT JOIN
public.controllers_tbl b
ON
b.id = a.controller_id
WHERE
a.controller_id = %s
""", (data_id,))
rows = cursor.fetchall()
result = []
for row in rows:
start_date = row[7].strftime('%H:%M:%S') if row[7] is not None else None
stop_date = row[8].strftime('%H:%M:%S') if row[8] is not None else None
result.append({
'ID': row[0],
'FETCHED_IP': row[1],
'STATUS': row[2],
'SID': row[3],
'PORT': row[4],
'MACHINE_NAME': row[5],
'AREA': row[6],
'START_DATE': start_date,
'STOP_DATE': stop_date,
'REMARKS': row[9]