142 lines
5.0 KiB
Python
142 lines
5.0 KiB
Python
import decimal
|
||
import traceback
|
||
from datetime import datetime
|
||
from dateutil.relativedelta import relativedelta
|
||
|
||
import psycopg2
|
||
from celery import shared_task
|
||
|
||
from django.db.models.functions import TruncMinute
|
||
from django.utils import timezone
|
||
|
||
from apps.main.models.scales_control import ScalesControl
|
||
from apps.main.models.worktime import FabricWorkTime
|
||
from sabron.util import logging
|
||
from sabron.util.sabronmodule import get_settings
|
||
|
||
|
||
@shared_task
|
||
def create_worktime_data() -> int:
|
||
"""
|
||
Создает объекты FabricWorkTime для анализа времени работы фабрики.
|
||
Если с весов нет ответа - фабрика не работает - конвейер стоит (5 минут без ответа)
|
||
Если с весов с Поз.4 меньше 20 - фабрика работает без нагрузки
|
||
"""
|
||
# TODO переписать под ситуации, создать модуль настроек для упр. конвейера
|
||
try:
|
||
now_date = timezone.now()
|
||
start_day = now_date - relativedelta(hours=24)
|
||
сontrol_conveyor = get_settings('control_conveyor')
|
||
latest_records = ScalesControl.objects.filter(
|
||
name=сontrol_conveyor,
|
||
time__gte=start_day
|
||
).annotate(
|
||
time_minute=TruncMinute('time')
|
||
).order_by('time_minute').distinct('time_minute')
|
||
if not latest_records:
|
||
print(list(latest_records))
|
||
return 1
|
||
current_record = latest_records[0]
|
||
for record in latest_records[1:]:
|
||
delta = (record.time - current_record.time).seconds / 60
|
||
rec = FabricWorkTime.objects.filter(time=current_record.time.replace(second=0, microsecond=0))
|
||
if delta > 5:
|
||
status = 'NW'
|
||
if rec:
|
||
next_rec = FabricWorkTime.objects.filter(time=record.time.replace(second=0, microsecond=0))
|
||
if next_rec:
|
||
next_rec_obj = next_rec.first()
|
||
next_rec_obj.status = status
|
||
next_rec_obj.save()
|
||
last_rec = rec.last()
|
||
last_rec.status = status
|
||
last_rec.save()
|
||
if not rec:
|
||
status = 'WO' if record.value > decimal.Decimal(20.0) else 'WA'
|
||
FabricWorkTime.objects.create(time=current_record.time.replace(second=0, microsecond=0), status=status)
|
||
current_record = record
|
||
return 0
|
||
except Exception:
|
||
logging.error(traceback.format_exc())
|
||
return 1
|
||
|
||
|
||
@shared_task
|
||
def create_scales_control_data():
|
||
print(f"Task started at {datetime.now()}")
|
||
scales_data = get_scales_data()
|
||
print(f"Task: selected data at {datetime.now()}")
|
||
write_scales_data(scales_data)
|
||
print(f"Task performed at {datetime.now()}")
|
||
|
||
|
||
def get_scales_data() -> list:
|
||
conn_postgres = psycopg2.connect(
|
||
dbname="vesi_db",
|
||
user="ktp_user",
|
||
password="rb,thrjl",
|
||
host="192.168.10.2",
|
||
port="5432"
|
||
)
|
||
|
||
with conn_postgres.cursor() as cursor:
|
||
cursor.execute("""
|
||
SELECT "Name", "Values", "Date", "Check"
|
||
FROM public.vesi
|
||
ORDER BY id DESC
|
||
LIMIT 20000;
|
||
""")
|
||
|
||
data = cursor.fetchall()
|
||
|
||
conn_postgres.close()
|
||
return data[::-1]
|
||
|
||
|
||
def write_scales_data(data: list):
|
||
postgres_conn = psycopg2.connect(
|
||
dbname="repcofkk_db",
|
||
user="repcofkk_user",
|
||
password="Angstrem*45",
|
||
host="127.0.0.1",
|
||
port="5432"
|
||
)
|
||
try:
|
||
with postgres_conn.cursor() as cursor:
|
||
for row in data:
|
||
name, value, date, check = row
|
||
cursor.execute("""
|
||
DO $$
|
||
DECLARE
|
||
value_exists BOOLEAN;
|
||
BEGIN
|
||
IF %s LIKE '%%Smena' OR %s LIKE '%%Month' THEN
|
||
SELECT EXISTS (
|
||
SELECT 1
|
||
FROM public.main_scalescontrol
|
||
WHERE "Name" = %s AND "Values" = %s
|
||
) INTO value_exists;
|
||
|
||
IF value_exists THEN
|
||
UPDATE public.main_scalescontrol
|
||
SET "Date" = %s
|
||
WHERE "Name" = %s AND "Values" = %s;
|
||
ELSE
|
||
INSERT INTO public.main_scalescontrol ("Name", "Values", "Date", "Check")
|
||
VALUES (%s, %s, %s, %s);
|
||
END IF;
|
||
END IF;
|
||
END $$;
|
||
""", (
|
||
name, name,
|
||
name, value,
|
||
date, name, value,
|
||
name, value, date, check
|
||
))
|
||
postgres_conn.commit()
|
||
except Exception:
|
||
print(traceback.format_exc())
|
||
print(row)
|
||
finally:
|
||
postgres_conn.close()
|