
    Lzj                        d dl Z d dlZd dlmc mZ d dlZd dlZd dlZd dlZd dl	Z	d dl
Z
d dlmZ d dlmZ d dlmZ d dlmZ ddlmZmZmZmZmZmZ  e
j2                  e
j4                  d	        e
j6                  e      Z ej<                  ej>                  j@                  d
      e_        dZ!dZ"dZ#dZ$ e% ejL                               Z'g dZ(d Z)i Z*d Z+d"dZ,d Z-d Z.d Z/d Z0d Z1d Z2d#dZ3d Z4d Z5d Z6d Z7d Z8edk(  r# e7       at        r	 	  e	jr                  d        yy# e:$ r ejw                  d!        e8        Y yw xY w)$    N)datetime)timezone)
connection)Q   )TtnstateReportProductReportcurrentloopTtnLogsz)%(asctime)s - %(levelname)s - %(message)s)levelformatutf-8)encoding	localhosti"  fomin_azHs6#2vG#%8bxsKZf4)!)zmomot_beton/report/1r   )zmomot_beton/report/2r   )zmomot_beton/report/4r   )zmomot_beton/report/8r   )zmomot_beton/report/16r   )zmomot_beton/report/32r   )zmomot_beton/report/64r   )zmomot_beton/report/128r   )zmomot_beton/report/256r   )zmomot_beton/report/512r   )zmomot_beton/report/1024r   )zmomot_beton/production/1r   )zmomot_beton/production/2r   )zmomot_beton/production/4r   )zmomot_beton/production/8r   )zmomot_beton/production/16r   )zmomot_beton/production/32r   )zmomot_beton/production/64r   )zmomot_beton/production/128r   )zmomot_beton/production/256r   )zmomot_beton/production/512r   )zmomot_beton/production/1024r   )zmomot_beton/reference/1/confirmr   )zmomot_beton/reference/2/confirmr   )zmomot_beton/reference/4/confirmr   )zmomot_beton/reference/8/confirmr   )z momot_beton/reference/16/confirmr   )z momot_beton/reference/32/confirmr   )z momot_beton/reference/64/confirmr   )z!momot_beton/reference/128/confirmr   )z!momot_beton/reference/256/confirmr   )z!momot_beton/reference/512/confirmr   )z"momot_beton/reference/1024/confirmr   c                  x    t         j                   r*t        j                         st        j                          y y y N)r   	is_usableclose     G/home/devuser/fomin/mqttuser/mqtt_project/mqtt_processor/mqtt_client.pyensure_connectionr   H   s*    Z%9%9%; &<r   c                 d   	 |}|rd| d| }|r!t        j                  |d      d d }| d| }t        j                  j	                  | t        j                         |       t        j                  d|  d	|d d
         y # t        $ r"}t        j                  d|        Y d }~y d }~ww xY w)N[z] Fensure_ascii   z	 | Data: )eventdatemessagezLog saved: z - d   zFailed to save log: )jsondumpsr   objectscreater   nowloggerinfo	Exceptionerror)
event_typer#   topicdatalog_messagedata_stres          r   save_log_eventr4   L   s    1eWBwi0Kzz$U;DSAH(M8*=K 	 	 	

 	k*STc1B0CDE 1+A3/001s   BB 	B/B**B/c                     | t         v rgt         |    D ]Z  \  }}}||k7  s|dk7  sd|d<   |j                  |t        j                  |      d       t        j                  d|  d| d       \ y y )	N      str   )qoszUpdated id=z
 in topic z
, set st=6)objects_by_idpublishr%   r&   r*   r+   )obj_idtopic_with_st_4clientr/   statuspayloads         r   update_status_for_other_topicsrA   a   sy    &3F&; 	O"E67'FaK !udjj&9qAk&E7*MN		O r   c                 2   | y	 t        |       }|d   }|dk(  ry|dk(  ry|dk(  ry|d	k(  ry
|dk(  ry|dk(  ry|dk(  ry|dk(  ry|dk(  ryt        j                  d| d|  d       y# t        $ r%}t        j	                  d|  d|        Y d }~yd }~ww xY w)N0000r   110002200033000440005500066000770008800099000zUnexpected first digit 'z' in code_component: z, using default '0000'z.Error determining typeCode for code_component : )strr*   warningr,   r-   )code_componentcode_strfirst_digitr3   s       r   !get_type_code_from_component_coder\   i   s    ~&qk#CCCCCCCCNN5k]BWXfWgg}~ EnEUUWXYWZ[\sF   A( A( A( A( A( A( A( A( A( A( (	B1BBc                 |   	 | j                  dg       }|st        j                  d|        yd}d}t        j                         5 }|D ]Z  }|j                  d      }|j                  d      }||t        j                  d|        C|r|j                  dd	      }t        |      }	|j                  d
|g       |j                         }
|
s9|j                  d|||	g       |dz  }t        j                  d| d| d|	        |
\  }}}d}g }||k7  r|j                  d| d       d}||	k7  r|j                  d|	 d       d}|sddj                  |       d| }|j                  |       |dz  }t        j                  d| d| d| d| d| d|	 d       ] 	 d d d        |dkD  s|dkD  r t        j                  d| d| d| d        yt        j                  d!|        y# 1 sw Y   LxY w# t        $ r2}d"| }t        j                  |       t        d#|||        Y d }~yd }~ww xY w)$N	componentz#No components found in report from Fr   rY   namez&Skipping component with missing data: z\//zn
                    SELECT id, name, typeCode FROM comp 
                    WHERE code = %s
                z
                        INSERT INTO comp (name, code, typeCode) 
                        VALUES (%s, %s, %s)
                    r   zSaved new component: name='z', code=z, typeCode=zname = ''TztypeCode = 'zUPDATE comp SET z, z WHERE id = zUpdated component: id=, code=z, old_name='z', new_name='z', old_typeCode='z', new_typeCode='zComponents processed from rV   z new, z updatedzNo new components to save from z%Error saving components to database: r-   )getr*   r+   r   cursorrX   replacer\   executefetchoneappendjoinr,   r-   r4   )r0   r/   component_listsaved_countupdated_countrd   r^   rY   r_   	type_codeexistingexisting_idexisting_nameexisting_type_codeshould_updateupdate_fieldsupdate_queryr3   	error_msgs                      r   save_components_to_databaserv      s   D+r2KK=eWEF  0	fF+ /f	!*/?!@ }}V,!)T\NN%KI;#WX<<s3D=nM	   %%'
 "??,NN $ 	:<
  1$KKK"=dV8NK[[fgpfq rsEMBK0B$)M$&M$,%,,xvQ-?@(,)Y6%,,|I;a-HI(,$)9$))M:R9SS_`k_l'm|4%*&<[MQ_P` a//<o]4& Q33E2FFWXaWbbc%e f[/f0	fd ?ma/KK4UG2k]&Q^P__ghi  KK9%ABm0	f 0	fp  ;A3?	Yw	5$7	sB   ,H  H  DG4AG4)1H  H  4G=9H   	H;	(H66H;c                    	 d| vr+d}t         j                  | d|        t        d|||        yd| vs| d   s+d}t         j                  | d|        t        d|||        yd| v r| d   rt        | |       d	}d	}| j	                  d
g       }| d   D ]  }|j	                  d      }|| j	                  dg       D cg c]  }|j	                  d      |k(  r| }	}| j	                  dg       D 
cg c]  }
|
j	                  d      |k(  r|
 }}
| j	                  d      | j	                  d      | j	                  d      |g|	|d}d
| v r| j	                  d
      |d
<   d| v r| j	                  d      |d<   d| v r| j	                  d      |d<   t        j                  |d      }t        j                  j                  |      j                         r2d| d}t         j                  |       t        d||d|i       |dz  }tt        j                  j                  |       |dz  }t         j                  d| dt        |	       dt        |       d        |d	kD  r t         j                  d| d| d| d       y"d | d| d}t         j                  |       t        d!||       y"c c}w c c}
w # t        $ r2}d#| }t         j                  |       t        d$|||        Y d }~yd }~ww xY w)%Ncurrent_loopz*Skipping report without current_loop fieldz from skippedFproductz$Skipping report without product datar^   r   pwr_loopind_productweight_manualbsur8   r   )r~   r8   r   rz   rx   r}   update_productr   )r%   z5Report with same JSON already exists for ind_product=z
, skipping	duplicater   z*Successfully saved Report for ind_product=z with z loops and z weight_manual recordszSuccessfully saved z Report records from z
, skipped z duplicatesz!No new Report records saved from r+   Tz!Error saving report to database: r-   )r*   r+   r4   rv   rc   r%   r&   r	   r'   filterexistsr(   lenr,   r-   )r0   r/   msgrk   skipped_countpwr_loop_listrz   r|   loop	all_loopsweightall_weight_manualsingle_report_datajson_strr3   ru   s                   r   save_report_to_databaser      sd   S%>CKK3%veW-.9c5$7D Y8CKK3%veW-.9c5$7$4#4'e4 R0I .	cG!++m4K" "&."!=88M*k9 I  &*XXor%B!!::m,; ! ! xxhhtn HHZ0#9 )!2" T!15*1E":.d"26((;2G";/4'7;xx@P7Q"#34zz"45IH~~$$($3::<Mk]ZdeC {C8TU"NN!!x!01KKKD[MQWX[\eXfWggrsv  xI  tJ  sK  Ka  b  c].	c` ?KK-k]:OPUwV`an`ooz{| 	 6eWJ}oU`aCKK63.e
!^  7s;	Yw	5$7	sH   .J= 3J= %AJ= J3J= 4J8E5J= +J= 3
J= =	K8(K33K8c           
         	 |j                  d      }d }|D ]  }|j                         st        |      } n |)d| }t        j	                  |       t        d|||        y| j                  d      }d }d| v r3d| d   v r,| d   d   }t        |t              r|j                  d      }n|}|&d}	t        j                  |	       t        d	|	||        y|&d
}	t        j                  |	       t        d	|	||        yt        j                  d| d| d| d|        t        j                         5 }
|
j                  d|g       |
j                         }|rt        j                  d|        |
j                  d|||g       |
j                  dkD  rt        j                  d| d| d|        n,d| d}	t        j                  |	       t        d	|	|||d       	 d d d        yd| }	t        j                  |	       t        d	|	|d|i       	 d d d        y# 1 sw Y   y xY w# t         $ r2}d| }t        j	                  |       t        d|||        Y d }~yd }~ww xY w)Nr`   z&Cannot extract BSU number from topic: r-   Fr8   reciper   z/Missing 'st' field in reference confirm messagerX   z5Missing 'datetime' field in reference confirm messagez$Processing reference confirm: topic=z, bsu=z, st=z, datetime=z
                SELECT id, name, code, options, entityName, isPause 
                FROM mainState 
                WHERE code = %s
            z!Found mainState record with code=z
                    UPDATE recipeState 
                    SET state = %s, date = %s 
                    WHERE codeBsu = %s
                r   z*Successfully updated recipeState: codeBsu=z, state=z, date=zrecipeState with codeBsu=z! does not exist - no rows updated)r~   stateTz$No mainState record found with code=r   z,Error processing reference confirm message: )splitisdigitintr*   r-   r4   rc   
isinstancedictrX   r+   r   rd   rf   rg   rowcountr,   )r0   r/   topic_parts	bsu_valuepartru   st_valuedatetime_valuedatetime_objr   rd   main_state_recordr3   s                r   process_reference_confirmr   '  s   Kkk#&	 	D||~I		
 @HILL#7Iud;88D>t
d8n <>*5L,-!-!1!1*!=!-CCNN39c5$7!ICNN39c5$7:5'	{RWX`Waalm{l|}~  	FNN  	 !' 1 ?zJK   	:	< ??Q&KK"LYKW_`h_iipq  qA  !B  C5i[@abCNN3'"9c5)V^:_`3	 	6 =XJGs#y#uw6IJ=	 	 	@  B1#F	Yw	5$7	sZ   (H* 8H* $A1H* 'H* >5H* 3B.H!H* *+HH* H'#H* 'H* *	I%3(I  I%c                     | sy 	 | j                  d      r| d d } d| v rt        j                  | d      }|S t        j                  | d      }|S # t        $ r%}t        j                  d|  d|        Y d }~y d }~ww xY w)NZ.z%Y-%m-%dT%H:%M:%S.%fz%Y-%m-%dT%H:%M:%SzError parsing datetime 'z': )endswithr   strptimer,   r*   r-   )datetime_strdtr3   s      r   parse_iso_datetimer   u  s      %',L,""<1GHB 	 ""<1DEB	 /~SDEs   1A A 	A=A88A=c                 :   	 t        | t              rt        |       }n| }t        |t              rt        |      }n|}|r|st        j	                  d|  d|        y|j                  d      }|j                  d      }t        ||      }||t        |      z  }t        j                  j                  |      j                         }|rt        j	                  d| d	| d
|        |S # t        $ r"}	t        j                  d|	        Y d }	~	yd }	~	ww xY w)NzCannot parse dates: start=z, end=Fr   )microsecond)	timeStarttimeEnd)idPlantzDuplicate found: timeStart=
, timeEnd=
, idPlant=z"Error checking product duplicate: )r   rW   r   r*   rX   re   r   r
   r'   r   r   r,   r-   )

time_starttime_endid_plantstart_dtend_dtstart_dt_secondend_dt_secondqueryr   r3   s
             r   check_product_duplicater     s    j#&)*5H!Hh$'1FFvNN7
|6(TU"**q*915O]CQx((E''.557NN88ITaSbblmulvwx 9!=>s   AC/ BC/ /	D8DDc                    t                	 |j                         }|sy d|v r0t        j                  d| d       |j	                  d      d   dz   }t        j                  |      }d|v rd|v rt        ||       |S |j                  d      }d }|j	                  d      d   j                         r|j	                  d      d   nd }	d|v rd}nd|v rd}nd|v rd}|j                  d      }
t        j                  d| d|	 d| d|
        |dv r|j                  d      }d }|rit        |t              rY	 t         j"                  j%                  |d      }t!        j&                  |t!        j(                               j+                  d       }|j                  dg       }|D ]  }|j                  d      }|	 t/        t        |      j                               }|dk(  rt        j                  d|        Y|rt0        j2                  j5                  ||       j7                         sSt0        j2                  j9                  ||
|t        j:                  |      !       t        j                  d"| d#|
 d$       nt        j                  d%|        nt0        j2                  j5                  |&      j7                         sRt0        j2                  j9                  ||
d t        j:                  |      !       t        j                  d"| d#|
 d$       t<        j2                  j5                  |'      j?                  |
(        |
d+k(  r|j                  dd       }|r|jA                         }d,|d<   d-| }| jC                  |t        j:                  |      tD        d./      }|jF                  }|dk(  rt        j                  d0|        n.d1| d2| }t        j                  |       t        d||||d3       |
d4k(  r|j                  dd       }|r|jA                         }d4|d<   d-| }| jC                  |t        j:                  |      tD        d./      }|jF                  }|dk(  rt        j                  d5|        |S d6| d2| }t        j                  |       t        d||||d3       |S |dk(  rftI        ||       |j                  d7g       }|j                  d8g       }|j                  d9g       }|j                  d:g       }|j                  d      }|D ]  }|j                  d;      }|j                  d      }|j                  d<      }|j                  d=      }tJ        j2                  j5                  ||>      j7                         r0d?| d@| dA} t        j                  |        t        dB| |||d>       tM        |||      r3dC| dD| dE| } t        j                  |        t        dB| ||||dF       |j                  d      }!d }"|!r4	 t!        j&                  t         j"                  j%                  |!d            }"tO        |      }#tO        |      }$|j                  dH      }%|%dI}%nt        |%      }%t        j                  dJ|# dK|$ dL| dM|%        	 tJ        j2                  j9                  |"|$|j                  dN      |j                  dO      |%|j                  dP      |j                  dQ      |j                  dR      xs dI|j                  dS      |j                  dT      ||#|j                  dO      ||U      }&t        j                  dV|&jP                   dW|# dK|$        |D ]  }'|'j                  d;      |k(  sd }(|D ]M  })|)j                  d;      |k(  s|)j                  dO      |'j                  dO      k(  s<|)j                  dX      }( n tR        j2                  j9                  |'j                  dH      |'j                  dO      |'j                  dY      |'j                  dZ      |'j                  d[      |'j                  d\      |'j                  d]      |'j                  d^      |'j                  d_      |'j                  d`      |'j                  da      |'j                  db      |(|&jP                  |c       t        j                  dd|( dM|'j                  dH       de|'j                  dY               |D ]  }*|*j                  d;      |k(  s	 tU        jV                         5 }+|+jY                  df|*j                  d;      |*j                  dO      |*j                  dY      |*j                  dg      |*j                  dZ      |&jP                  g       d d d        t        j                  dh|*j                  d;       di|*j                  dO       de|*j                  dY       dj|&jP                            |r|D ]  }*	 tJ        j2                  j5                  |*j                  d;      |>      j[                  dn      j]                         },|,rctU        jV                         5 }+|+jY                  do|*j                  d;      |*j                  dO      |*j                  dY      g       |+j_                         d   }-|-dk(  r|+jY                  df|*j                  d;      |*j                  dO      |*j                  dY      |*j                  dg      |*j                  dZ      |,jP                  g       t        j                  dp|*j                  d;       dj|,jP                          nIdq|*j                  d;       di|*j                  dO       } t        j                  |        t        dB| ||*       d d d        nHdr|*j                  d;       } t        j                  |        t        ds| |dt|*j                  d;      i        |S # t        $ r<}d| }t        j                  | d|        t        d||d	|d d
 i       Y d }~y d }~ww xY w# t,        $ r. d| }t        j                  |       t        d||d|i       Y w xY w# t        $ r&}t        j                  d)| d*|        Y d }~4d }~ww xY w# t        $ r5}dG| }t        j                  |       t        d||d|!i       Y d }~d }~ww xY w# 1 sw Y   fxY w# t        $ r6}dk| dl|* }t        j                  |       t        d|||*       Y d }~Fd }~ww xY w# t        $ r6}dm| }t        j                  |       t        d||||d>       Y d }~d }~ww xY w# 1 sw Y   xY w# t        $ r6}du| dl|* }t        j                  |       t        d|||*       Y d }~d }~ww xY w)vNz}{zExtra data detected in z. Taking first object.r   }zJSON Parse Error: z in r-   r@   r    	referenceconfirmr~   r`   r   ttn
productionreportr8   zMsg: z | Topic BSU: z | Source BSU: z | st: )r   r   r   z%Y-%m-%d %H:%M:%S)tzinfozDate error: r"   ind_ttnz;Skipping Ttnstate for idTtn=0 (real data from server) from )idTtnr"   )r   r   r"   r%   zSaved Ttnstate: z (st )z"Ttnstate already exists for idTtn=)r   )id)r   zDB Error for Ttn rV         zmomot_beton/ttn/F)r9   retainz Message with st=15 published to z%Failed to send message with st=15 to z, result code: )r~   r?      z Message with st=13 published to z%Failed to send message with st=13 to rz   rx   r}   r{   r|   r   	time_done)
indProductr   zProduct with indProduct=z and idPlant=z already exists, skippingr   z+SKIPPING product with duplicate time_start=z and time_end=z for idPlant=)r   r   r   zError parsing datetime: v_loop z&Attempting to save Product: timeStart=r   r   z, vLoop=	v_productnum_loopdrivercarclass_recipename_reciper   )	dateStartr   vProduct
loopNumbervLoopr   r   classRecipe
nameReciper   r   r   r   r   r   z#Successfully saved Product with id=z, timeStart=pwrcode	dispenser
err_dosingerr_dosing_persentkorr_dosingkorr_humidityweight_fact_loopweight_fact_m3weight_recipe_loopweight_recipe_m3)r   r   r   	dispencerdoisingErrordoisingErrorPersentdoisingKorrhumidityKorrweightFactLoopweightFactM3weightRecipeLoopweightRecipeM3	powerLoop	idProductr   zSaved loop: powerLoop=rb   a  
                                    INSERT INTO weightManual 
                                    (indProduct, numLoop, code, weight, dispenser, idProduct) 
                                    VALUES (%s, %s, %s, %s, %s, %s)
                                r   z Saved weight_manual: indProduct=z
, numLoop=z, idProduct=zError saving weight_manual: z, data: zError creating Product: z
-dateStartz
                                SELECT COUNT(*) FROM weightManual 
                                WHERE indProduct = %s AND numLoop = %s AND code = %s
                            z-Saved weight_manual (additional): indProduct=z*weight_manual duplicate found: indProduct=z0Product not found for weight_manual: indProduct=rX   r   z'Error saving additional weight_manual: )0r   stripr*   rX   r   r%   loadsr,   r-   r4   r   rc   r   r+   r   rW   r   r   r   
make_awareget_current_timezonere   
ValueErrorr   r   r'   r   r   r(   r&   r   updatecopyr;   MQTT_QOSrcr   r
   r   r   r   r   r   rd   rf   order_byfirstrg   ).r>   r/   payload_strclean_payloadr0   r3   ru   
source_bsumsg_type	topic_bsur   raw_dateprocessed_dater   ttn_listttn_item	idTtn_rawr   r~   new_payload	new_topicresultr?   product_listcurrent_loop_listweight_manual_listr   r   prodr   r   r   r   ds_rawdsparsed_time_startparsed_time_endv_loop_valueproduct_objr   power_loop_valuer   weight_itemrd   rz   counts.                                                 r   save_messager    s   #))+= NN4UG;QRS)//5a83>Mzz-( e	U 2!$.%JH(-C(8(<(D(D(FC $DI~%x		<	U	xH88D>D
KK%z	{/*U\]a\bcd((88J'
8S1N&&//:MN!)!4!4R9V9V9X!Y!a!aim!a!n 88E2&  	CH Y/I CC	N0023 A:KK"]^c]d ef "#++22^2T[[] ((//e4ncgcmcmnrcs/t&6ugU4&$JK &H$PQ#++222?FFH ((//e4dY]YcYcdhYi/j&6ugU4&$JK ""e",33$3?9	C@ 2:((5$'C"iik$&D!.se4		4::k3JPXafgQ;KK"B9+ NO"G	{Rabhai jILL+"7IucU[>\]2:((5$'C"iik$&D!.se4		4::k3JPXafgQ;KK"B9+ NOv Ks #H	{Rabhai jILL+"7IucU[>\]n Kk 
X	e,xx	2. HH^R8!XXor:R0((5/  w	jD-0JHHUOE,/Jxx,H%%W%MTTV0M'Rkls#{Cz^e8fg&z8WECJ<~^f]ggtu|t}~s#{Cz_gt{8|}XXj)FBT!,,X->->-G-GPc-deB !3: >0:O  88H-L#!"<0KK@AR@SS]^m]nnx  zA  yB  BJ  KW  JX  Y  ZOj%oo44 +!XXk2#xx
3&88H- $ 8 >B#xx688H-/!XXj1#) 5 $ A+..AQQ]^o]ppz  |K  {L  M  N . FDxx.*<+/(#0 &C"ww}5CPZH[_c_g_ghr_sHs36775> 0 %& *1188"&((8"4'+xx
';!%&!1&*hh{&;)-,)?049M0N(,(?)-/)B+/884F+G)-2B)C-1XX6J-K+/884F+G&6&1nn'1 9 " &<=M<NhW[W_W_`hWiVjjqrvrzrz  |B  sC  rD  %E  F7F< $6 SK"}5CS!+!2!2!4 # & 0$
 %0OOM$B$/OOJ$?$/OOF$;$/OOH$=$/OOK$@$/NN&"	!## #KK*J;??[hKiJj k11<1L0MWU`UdUdekUlTm n33>>>2B)D E!Syw	jt 1 .K-K%oo44#.??=#A ' 5  h|,UUW 
 '..0 UF"NN ,  !, > +
 ; + 7" %+OO$5a$8E$z & 0$
 %0OOM$B$/OOJ$?$/OOF$;$/OOH$=$/OOK$@$+JJ&"	!# !'.[\g\k\kly\z[{ |77>zzl-D !E )SS^SbSbcpSqRrr|  ~I  ~M  ~M  NX  ~Y  }Z  '[ &C 0 .{C T;U U> !QQ\Q`Q`anQoPpqs+&y#u|[__]jMk>lmS.K` Ko  (,		{$ug./w	59k$3>O2PQ	8  N*8*5	Y'w	568:LMNF  C02aSABBCH ! T":1# >ILL+"7Iuz6>RSSTP# #   ) S*FqcR]Q^(_I"LL3*7IukRRS
  j6qc:	Y'w	5`g:hiijU UF ! K"I!HU`Ta bILL+"7IukJJKs
  p. A	p. :Aq6 ??r0?Er0*3s"6C,u2#u2?#u2#Eu2=t0A.t#?A t0u2.A$wEv4Aw.	q372q..q363r-,r-0	s9ss"	t +*tt #t-(t00	u/9+u*$u2*u//u22	v1;+v,,v14v>	9w	x 
+w;;x c                     t         j                  d| d       |dk(  rt        ddd d|i       nt        dd| d d|i       | j                  t               y )	NzConnected to MQTT broker (code r   r   r+   z"MQTT Client connected successfullyr   r-   z(MQTT Client connection failed with code )r*   r+   r4   	subscribeMQTT_TOPICS_SUB)r>   userdataflagsr   s       r   
on_connectr    s_    
KK1"Q78	Qwv!CdTSUJWw"J2$ OQUX\^`Wab
_%r   c           
      ,   	 |j                   j                  d      }t        | |j                  |      }|r|j	                  d      rv|j	                  d      }|j	                  d      }|t
        vr	g t
        |<   t
        |   j                  |j                  ||f       |dk(  rt        ||j                  |        y y y y # t        $ rK}d| }t        j                  |       t        d||j                  d|j                   d d i       Y d }~y d }~ww xY w)	Nr   r   r8   r6   zError in on_message: r-   r@   r    )r@   decoder  r/   rc   r:   rh   rA   r,   r*   r-   r4   )	r>   r  r   r@   r0   r<   obj_str3   ru   s	            r   
on_messager    s    V++$$W-FCIIw7DHHTNXXd^FXXd^F]*(*f%&!((#))VT)BC{.vsyy&I  #4  V+A3/	Yw	399y#++dsBS6TUUVs   B9B? ?	DADDc                     d} t         j                  j                  |       rp	 t        | d      5 }t	        |j                               }d d d        t        j                  d       t        j                  d| d       t        dd| dd        y t        | d      5 }|j                  t        t        j                                      d d d        	 t!        j"                  t$              at(        t&        _        t*        t&        _        t&        j-                  t.        t0               t&        j3                  d t4        j6                  t4        j8                  	       t&        j;                  d
       t        j=                  dt>         d       t&        jA                  t>        tB        d       t&        jE                          t        ddd        t&        S # 1 sw Y   xY w# t        t        f$ r t        j                  |        Y xw xY w# 1 sw Y   ExY w# tF        $ re}d| }t        jI                  |       t        d|d        t         j                  j                  |       rt        j                  |        Y d }~y d }~ww xY w)N/tmp/mqtt_client.lockrr   z!MQTT client already running (PID r   rX   w)	client_id)ca_certs	cert_reqstls_versionTzConnecting to z...<   r+   z MQTT client started successfullyzFailed to start: r-   )%ospathr   openr   readkillr*   rX   r4   OSErrorr   removewriterW   getpidmqttClientMQTT_CLIENT_IDr>   r  r  username_pw_setMQTT_USERNAMEMQTT_PASSWORDtls_setssl	CERT_NONEPROTOCOL_TLS_CLIENTtls_insecure_setr+   MQTT_BROKERconnect	MQTT_PORT
loop_startr,   r-   )	lock_filefold_pidr3   ru   s        r   start_mqtt_clientrB    s   'I	ww~~i 	!i% (affh-(GGGQNN>wiqIJ9(I'RS&TVZ[ 
i	 "	BIIK !"~6&&}m<3KbKbc%n[M56{Ir2v!ADI1( ( $ 	!IIi 	!" "   's+	Yw	4077>>)$bii	&:sO   G# G	AG# -HDH G G# #$H
HH	J	$AJJ	c                      t         r5t         j                          t         j                          t        ddd        d} t        j
                  j                  |       rt	        j                  |        y y )Nr+   zMQTT client stoppedr  )r>   	loop_stop
disconnectr4   r'  r(  r   r-  )r?  s    r   stop_mqtt_clientrF    sP    v4d;'I	ww~~i 
		) !r   __main__   zStopping...)NNr   )<r%   uuidpaho.mqtt.clientr0  r>   r7  sysr'  iotimeloggingr   django.utilsr   	django.dbr   django.db.modelsr   modelsr   r	   r
   r   r   r   basicConfigINFO	getLogger__name__r*   TextIOWrapperstdoutbufferr;  r=  r4  r5  rW   uuid4r2  r  r   r:   r   r4   rA   r\   rv   r   r   r   r   r  r  r  rB  rF  sleepKeyboardInterruptr+   r   r   r   <module>r]     sp       
 
 	 	    !    L K   ',,/Z [			8	$Rcjj//'B
 	#ZTZZ\""F  1*OBENTlL\$!FdL	&V($L	 z F	

1    ! 	KK&	s   D+ +E
E