293 lines
10 KiB
Python
293 lines
10 KiB
Python
import os
|
||
import traceback
|
||
from datetime import timedelta, datetime
|
||
|
||
import psycopg2
|
||
from celery import shared_task
|
||
|
||
from django.utils import timezone
|
||
from psycopg2 import OperationalError
|
||
|
||
from apps.main.models.scales_control import ScalesControl, Position
|
||
from apps.main.models.worktime import FabricWorkTime
|
||
from apps.main.services.base_service import DashboardBaseService
|
||
from apps.util.redis_api import RedisService
|
||
from repcofkk.production_settings import REDIS_HOST, REDIS_PORT
|
||
from sabron.util import logging
|
||
from sabron.util.sabronmodule import get_settings
|
||
|
||
|
||
@shared_task
|
||
def create_worktime_data():
|
||
control_conveyor = get_settings("control_conveyor")
|
||
now_date = DashboardBaseService.get_current_time()
|
||
start_shift = DashboardBaseService.get_shift_start(now_date)
|
||
|
||
with RedisService(host=REDIS_HOST, port=REDIS_PORT, db=1) as redis_service:
|
||
value = redis_service.hget_value(control_conveyor, "Value")
|
||
date_str = redis_service.hget_value(control_conveyor, "Date")
|
||
date = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S.%f")
|
||
|
||
obj_from_redis = {"value": value, "date": date}
|
||
delta = (now_date - obj_from_redis['date']).seconds / 60
|
||
|
||
try:
|
||
latest_worktime_obj = FabricWorkTime.objects.latest('time')
|
||
except FabricWorkTime.DoesNotExist:
|
||
status = 'WO' if delta < 5 else 'NW'
|
||
obj = FabricWorkTime.objects.create(status=status, time=obj_from_redis['date'])
|
||
return "Success. Created first obj: " + str(obj)
|
||
status = None
|
||
rounded_time = DashboardBaseService.round_time(latest_worktime_obj.time)
|
||
if (now_date.replace(minute=0, second=0, microsecond=0) == start_shift and
|
||
rounded_time != start_shift):
|
||
status = latest_worktime_obj.status
|
||
|
||
elif latest_worktime_obj.status == 'NW' and delta < 5:
|
||
status = 'WO'
|
||
|
||
elif latest_worktime_obj.status == 'WO' and delta > 5:
|
||
status = 'NW'
|
||
|
||
if status:
|
||
obj = FabricWorkTime.objects.create(status=status, time=obj_from_redis['date'])
|
||
return "Success. Created obj: " + str(obj)
|
||
|
||
return "Success. " + str(latest_worktime_obj)
|
||
|
||
|
||
# @shared_task
|
||
# def create_worktime_data() -> int:
|
||
# """
|
||
# Создает объекты FabricWorkTime для анализа времени работы фабрики.
|
||
# Если с весов нет ответа - фабрика не работает - конвейер стоит (5 минут без ответа)
|
||
# Если с весов с Поз.4 меньше 20 - фабрика работает без нагрузки
|
||
# """
|
||
#
|
||
#
|
||
# try:
|
||
# control_conveyor = get_settings("control_conveyor")
|
||
# now_date = DashboardBaseService.get_current_time()
|
||
# start_day = now_date - relativedelta(hours=24)
|
||
# latest_records = (
|
||
# ScalesControl.objects.filter(name=control_conveyor, time__gte=start_day)
|
||
# .annotate(time_minute=TruncMinute("time"))
|
||
# .order_by("time_minute")
|
||
# .distinct("time_minute")
|
||
# )
|
||
# if not latest_records:
|
||
# return f"No scales records. {now_date}"
|
||
# 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:
|
||
# 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 "Success"
|
||
# except Exception as e:
|
||
# logging.error(traceback.format_exc())
|
||
# return f"Exception: {e}"
|
||
|
||
|
||
def set_cache_value(key: str, value: str) -> str:
|
||
with RedisService(host=REDIS_HOST, port=REDIS_PORT, db=2) as redis_service:
|
||
value = redis_service.set_value("cache_tasks/" + key, value)
|
||
return value
|
||
|
||
|
||
def get_cache_value(key: str) -> bool:
|
||
with RedisService(host=REDIS_HOST, port=REDIS_PORT, db=2) as redis_service:
|
||
value = redis_service.get_value("cache_tasks/" + key)
|
||
return bool(int(value))
|
||
|
||
|
||
def delete_cache_value(key: str) -> str:
|
||
with RedisService(host=REDIS_HOST, port=REDIS_PORT, db=2) as redis_service:
|
||
value = redis_service.delete_value("cache_tasks/" + key)
|
||
return value
|
||
|
||
|
||
@shared_task
|
||
def create_scales_control_data():
|
||
cache = get_cache_value("create_scales_control_data")
|
||
if not cache:
|
||
set_cache_value("create_scales_control_data", "1")
|
||
scales_data = get_scales_data(300)
|
||
res = write_scales_data(scales_data)
|
||
delete_cache_value("create_scales_control_data")
|
||
return res
|
||
return "Skip"
|
||
|
||
|
||
@shared_task
|
||
def write_scale_control_data_to_redis():
|
||
try:
|
||
data = get_scales_data(300)
|
||
with RedisService(host=REDIS_HOST, port=REDIS_PORT, db=1) as redis_service:
|
||
for row in data:
|
||
redis_service.hset_value(row[0], key="Value", value=str(row[1]))
|
||
redis_service.hset_value(row[0], key="Date", value=str(row[2]))
|
||
return "Success"
|
||
except Exception as e:
|
||
logging.error("CELERY" + traceback.format_exc())
|
||
return str(e)
|
||
|
||
|
||
@shared_task
|
||
def thin_out_scales():
|
||
positions = Position.objects.all()
|
||
results = []
|
||
for position in positions:
|
||
pos_tags = [
|
||
position.aver_smena_tag,
|
||
position.aver_pred_smena_tag,
|
||
position.smena_tag,
|
||
position.pred_smena_tag,
|
||
position.month_tag,
|
||
position.sutki_tag,
|
||
]
|
||
for tag in pos_tags:
|
||
try:
|
||
res = thin_out_scale(tag)
|
||
if not res:
|
||
results.append({tag: "No scales Data"})
|
||
results.append({tag: res})
|
||
except Exception:
|
||
logging.error(f"Celery: {traceback.format_exc()} \n on tag {tag}")
|
||
results.append({tag: {traceback.format_exc()}})
|
||
return results
|
||
|
||
|
||
def thin_out_scale(tag) -> bool | int:
|
||
qs = list(
|
||
ScalesControl.objects.filter(
|
||
name=tag,
|
||
time__lte=DashboardBaseService.get_current_time() - timedelta(hours=12),
|
||
).order_by("time")
|
||
)
|
||
|
||
if len(qs) <= 2:
|
||
return False
|
||
i = 0
|
||
current_obj = qs[i]
|
||
latest_obj = qs[-1]
|
||
|
||
while current_obj != latest_obj:
|
||
end_range_date = current_obj.time + timedelta(hours=1)
|
||
|
||
rang = ScalesControl.objects.filter(
|
||
name=tag, time__range=(current_obj.time, end_range_date)
|
||
).order_by("time")
|
||
if len(rang) <= 2:
|
||
i += 1
|
||
current_obj = qs[i + 1]
|
||
continue
|
||
first_in_range = rang.first()
|
||
last_in_range = rang.last()
|
||
to_delete = rang.exclude(time=first_in_range.time).exclude(
|
||
time=last_in_range.time
|
||
)
|
||
to_delete.delete()
|
||
current_obj = last_in_range
|
||
i += 1
|
||
return len(to_delete)
|
||
|
||
|
||
def get_scales_data(limit: int = 20000) -> list:
|
||
try:
|
||
with psycopg2.connect(
|
||
dbname="vesi_db",
|
||
user="ktp_user",
|
||
password="rb,thrjl",
|
||
host="192.168.10.2",
|
||
port="5432",
|
||
) as conn_postgres:
|
||
with conn_postgres.cursor() as cursor:
|
||
cursor.execute(
|
||
"""
|
||
SELECT "Name", "Values", "Date", "Check"
|
||
FROM public.vesi
|
||
ORDER BY id DESC
|
||
LIMIT %s;
|
||
""",
|
||
(limit,),
|
||
)
|
||
data = cursor.fetchall()
|
||
return data[::-1]
|
||
except OperationalError:
|
||
return None
|
||
|
||
|
||
def write_scales_data(data: list):
|
||
if not data:
|
||
return "No scales data"
|
||
try:
|
||
with psycopg2.connect(
|
||
dbname=os.environ.get("POSTGRES_DB", "repcofkk_db"),
|
||
user=os.environ.get("POSTGRES_USER", "repcofkk_user"),
|
||
password=os.environ.get("POSTGRES_PASSWORD", "Angstrem*45"),
|
||
host=os.environ.get("POSTGRES_HOST", "127.0.0.1"),
|
||
port="5432",
|
||
) as postgres_conn:
|
||
with postgres_conn.cursor() as cursor: # TODO при настройке ОПС на запись в БД - убрать первое условие
|
||
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()
|
||
return "Success"
|
||
except Exception:
|
||
logging.error("CELERY: " + traceback.format_exc())
|
||
return traceback.format_exc()
|
||
finally:
|
||
postgres_conn.close()
|