o
    Li
                     @   s   d Z ddlZddlmZ ddlmZmZ ddlmZmZ ede	Z
eZeZdZdZd	Zd
d ZdefddZe
jdddgddd ZdS )zK
FillDrainPump config: reads schedule from file; logs ESP32 sync requests.
    N)datetime)	Blueprintrequest)FILLDRAIN_SCHEDULE_FILEFILLDRAIN_LOG_FILE	filldrainz08:00z19:005c                  C   s   t jtstttfS zVttddd} dd |  D }W d   n1 s'w   Y  t	|dkr:|d r:|d nt}t	|dkrJ|d rJ|d nt}t	|d	krZ|d	 rZ|d	 nt}|||fW S  t
yo   tttf Y S w )
zPRead on1, on2, duration from schedule file. Return (on1, on2, duration) strings.rutf-8encodingc                 S   s   g | ]}|  qS  )strip).0liner   r   ,/var/www/html/Server/blueprints/filldrain.py
<listcomp>   s    z!read_schedule.<locals>.<listcomp>Nr         )ospathisfileSCHEDULE_FILEDEFAULT_ON1DEFAULT_ON2DEFAULT_DURATIONopen	readlineslen	Exception)flineson1on2durationr   r   r   read_schedule   s   
   r%   datac              
   C   s   zCt jt}|rt j|st j|dd ttddd}t 	d}|
| d|  d W d	   W d	S 1 s<w   Y  W d	S  ty] } ztd
|  W Y d	}~d	S d	}~ww )z4Append one line to log file with timestamp and data.T)exist_okar
   r   z%Y-%m-%d %H:%M:%S UTCz | 
NzLog write error: )r   r   dirnameLOG_FILEisdirmakedirsr   r   utcnowstrftimewriter   print)r&   log_dirr    tser   r   r   	log_entry#   s   &r5   z/syncGETPOST)methodsc                  C   s   t jdkr/t jr/t jddpi } | dd}| dd}| dd}| dd}| d	d}n#t jdd}t jdd}t jdd}t jdd}t jd	d}t j|||||d
}t| t \}}}	| d| d|	 d}
|
dddifS )z
    ESP32 sends: epoch, time, on1, on2, duration (query or JSON).
    Respond with 3 lines: on1, on2, duration (from schedule file).
    r7   T)silentepoch timer"   r#   r$   )	client_ipr:   r<   r"   r#   r$   r)      zContent-Typeztext/plain; charset=utf-8)	r   methodis_jsonget_jsongetargsremote_addrr5   r%   )r&   r:   time_strr"   r#   r$   log_datas_on1s_on2
s_durationbodyr   r   r   sync0   s.   rK   )__doc__r   r   flaskr   r   configr   r   __name__bpr   r+   r   r   r   r%   dictr5   routerK   r   r   r   r   <module>   s    
