
    t)iH0                        d dl ma d dlZd dlmZ ddlmZmZmZm	Z	m
Z
 d dlZd dlmc mZ d dlZd dlm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Zd dlZ ej2                  ej4                  j6                  d	      e_        d
ZdZdZdZ e  ejB                               Z"g dZ#dZ$d Z% ejL                         ai Z'd Z(d Z)d Z*d Z+d Z,d Z-d Z.e/dk(  r e-       a	 	  ej`                  d       y# e1$ r  e2d        e.        Y yw xY w)    )clientN)timezone   )TtnstateReportProductReportcurrentloopTtn)
connection)Qutf-8)encoding	localhosti"  fomin_azHs6#2vG#%8bxsKZf4))zgrand_beton/report/1r   )zgrand_beton/report/2r   )zgrand_beton/report/4r   )zgrand_beton/report/8r   )zgrand_beton/report/16r   )zgrand_beton/report/32r   )zgrand_beton/report/64r   )zgrand_beton/report/128r   )zgrand_beton/report/256r   )zgrand_beton/report/512r   )zgrand_beton/production/1r   )zgrand_beton/production/2r   )zgrand_beton/production/4r   )zgrand_beton/production/8r   )zgrand_beton/production/16r   )zgrand_beton/production/32r   )zgrand_beton/production/64r   )zgrand_beton/production/128r   )zgrand_beton/production/256r   )zgrand_beton/production/512r   )zgrand_beton/ttn/1r   )zgrand_beton/ttn/2r   )zgrand_beton/ttn/4r   )zgrand_beton/ttn/8r   )zgrand_beton/ttn/16r   )zgrand_beton/ttn/32r   )zgrand_beton/ttn/64r   )zgrand_beton/ttn/128r   )zgrand_beton/ttn/256r   )zgrand_beton/ttn/512r   zgrand_beton/ttn/backc                  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   C   s*    Z%9%9%; &<r   c                     | t         v rht         |    D ][  \  }}}||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publishjsondumpslogginginfo)obj_idtopic_with_st_4r   topicstatuspayloads         r   update_status_for_other_topicsr(   I   sy    &3F&; 	P"E67'FaK !udjj&9qA{6(*UG:NO		P r   c                    t                t        j                  |      }d|v sd|v rh|j                  dd       }|j                  dd       }t	        d|        t        |t              rFt        j                  t        j                  j                  |d      t        j                               }|j                  d       }|j                  dg       }|D ]j  }|j                  dd       }|	 t        t        |j                  dd	            j                               }t                t        j                   j#                  t%        |
      t%        |      z        j'                         }	|	s8t        j                   j)                  ||||       t	        d| d| d|        nt	        d| d       t                t*        j                   j#                  |      j'                         rBt*        j                   j#                  |      j-                  |       t	        d| d|        nt	        d|        m |dk(  r|j                  dd       }t        j                  |      }d|d<   d| } | j2                  |t        j4                  |      j7                  d      t8        d      }|j:                  }|dk(  rt	        d | d!       nt	        d"| d#|        |d$k(  r|j                  dd       }|rt        j                  |      }d$|d<   d| } | j2                  |t        j4                  |      j7                  d      t8        d      }|j:                  }|dk(  rt	        d%|        y t	        d&| d'|        y y y d(|v r&|j                  d)g       }|j                  d*g       }|j                  d      }|D ]  }|j                  dd       }|j                  d+d       }|j                  d,d       }|j                  d-d       }|j                  d.d       }|j                  d/d       }|j                  d0d       }|j                  d1      xs d	}|j                  d2d       }|j                  d3d       }|j                  dd       }|j                  d4d       }|j                  d-d       } |j                  d5d       }!t                |rHt        j                  j                  |d      }"t        j                  |"t        j                               }t<        j                   j#                  |||!6      j'                         sYt=        ||||||||||||| ||!7      }#|#j?                          |D ])  }$|$j                  d5d       |j                  d5d       k(  r
t                t@        j                   j)                  |$j                  d.d       |$j                  d-d       |$j                  d8d       |$j                  d9d       |$j                  d:d       |$j                  d;d       |$j                  d<d       |$j                  d=d       |$j                  d>d       |$j                  d?d       |$j                  d@d       |$j                  dAd       |#jB                  |!B       , t                 y y # t.        $ r}
t	        d|
        Y d }
~
d }
~
wt0        $ r}t	        d|        Y d }~#d }~ww xY w)CNttn
productionr   datetimez___________ z%Y-%m-%d %H:%M:%S)tzinfoind_ttn )date)idTtn)r1   stater0   r   zSaved new Ttnstate: idTtn=z, state=z, date=zRecord with idTtn=z already exists)id)r2   zUpdated ttn: idTtn=z!No record found in ttn for idTtn=zValueError: zError:    bsu   zgrand_beton/ttn/r   F)r   retainr   z Message with st=15 published to z ------z%Failed to send message with st=15 to z, BSU result code:    z Message with st=13 published to z%Failed to send message with st=13 to z, result code: reportproductcurrent_loop	time_done	v_productnum_loopv_loopdrivercarclass_recipename_reciperecipe
time_startind_product)r1   idPlant
indProduct)	dateStarttimeEndvProduct
loopNumbervLoopr@   rA   classRecipe
nameReciperD   r1   	timeStartr>   rG   rH   code	dispenser
err_dosingerr_dosing_persentkorr_dosingkorr_humidityweight_fact_loopweight_fact_m3weight_recipe_loopweight_recipe_m3)rM   rL   rQ   	dispencerdoisingErrordoisingErrorPersentdoisingKorrhumidityKorrweightFactLoopweightFactM3weightRecipeLoopweightRecipeM3	idProductrH   )"r   r   loadsgetprint
isinstancestrr   
make_awarer,   strptimeget_current_timezonereplaceintstripr   objectsfilterr   existscreater
   update
ValueError	Exceptionr   r    encodeMQTT_QOSrcr   saver	   r3   )%r   r%   r'   datarQ   r0   ttn_listr*   r1   existing_recordveer5   new_payload	new_topicresultr&   product_listcurrent_loop_listrG   r:   rI   rJ   rK   rL   rM   r@   rA   rN   rO   rD   rP   r>   rH   
naive_dateproduct_objloops%                                        r   save_messager   R   s`   ::gD~.xxd#xx
D)TF#$ dC &&x'8'8'A'A$H['\^f^{^{^}~D ||4|(88E2& 	)CGGIt,E )CGGIr$: ; A A CDE%' '/&6&6&=&=tqu~5'fh $ + ((//e4dY`/a :5'$wW[V\]^ 25'IJ%'{{))U)3::<**e*4;;$;G 3E7(4&IJ A%IJ5	)B 2:((5$'C**W-K "K*3%0I#V^^Itzz+/F/M/Mg/V\dmrsFYYF{87KL=i[H[\b[cde2:((5$'C"jj1$&D!.se4	'	4::k3J3Q3QRY3Z`hqvwQ;<YKHIA)O\b[cde   
U	xx	2. HH^R8((5/# 1	 GT2Ikk+t4G{{;5H Z6JKK$/E[[40F++eT*C!++n5;K ]D9J[[40FKKt,EL$7I{{:t4H ]D9J%..77	CVW
$//
H<Y<Y<[\	??))wS])^eeg%'8XbC[]g!)h`g)	   "- Dxxt4MSW8XX)+%--44"hhx6#'88J#=!XXfd3"&((;"=%)XXlD%A,0HH5I4,P$(HH]D$A%)XXot%D'+xx0BD'I%)XX.>%E)-2F)M'+xx0BD'I"-..#- 5 ( c1	  
? " /L-..  )GA3-(()s%   1EZ==	[?[[?&[::[?c                 L    t        d|         | j                  t               y )Nz*Connected to MQTT broker with result code )rg   	subscribeMQTT_TOPICS_SUB)r   userdataflagsry   s       r   
on_connectr      s"    	6rd
;<F_%r   c                    t        | |j                  |j                  j                                	 t	        j
                  |j                  j                               }|j                  d      }|j                  d      }|T|t        vr	g t        |<   t        |   j                  |j                  ||f       |dk(  rt        ||j                  |        y y y # t        $ r}t        d       Y d }~y d }~ww xY w)Nr3   r   r   zReceived message:-----otladka)r   r%   r'   decoder   re   rf   r   appendr(   rv   rg   )r   r   msgr'   r#   
obj_statusr   s          r   
on_messager      s    CKK$6$6$890**S[[//12T"[[&
]*(*f%&!((#))Z)IJQ.vsyy&I    0-//0s   B#C 	C5 C00C5c                     d} t         j                  j                  |       rt        d       y t	        | d      5 }|j                  t        t        j                                      d d d        	 t        j                  t              at        t        _        t        t        _        t        j                  t        t                t        j"                  d t$        j&                  t$        j(                         t        j*                  d       t        dt,         dt.         d	       t        j0                  t,        t.        d
       t        j2                          t        d       t        S # 1 sw Y   xY w# t4        $ rL}t        d|        t         j                  j                  |       rt        j6                  |        Y d }~y d }~ww xY w)N/tmp/mqtt_client.lockzMQTT client is already running.w)	client_id)ca_certs	cert_reqstls_versionTzConnecting to MQTT broker :z...<   z MQTT client started successfullyzFailed to start MQTT client: )ospathrr   rg   openwriteri   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_setMQTT_BROKER	MQTT_PORTconnect
loop_startrv   remove)	lock_filefr   s      r   start_mqtt_clientr      s@    (I	ww~~i /0 
i	 "	BIIK !"~6&&}m< 	3KbKbc% 	*;-q3GH{Ir201)" ",  -aS1277>>)$IIi s%   -E-0C<E: -E7:	GAG

Gc                     t         r3t        j                          t        j                          t        d       d} t        j
                  j                  |       r*t        j                  d       t        j                          y y )NzMQTT client stoppedr   z'MQTT client is already running OTLADKA.)r   	loop_stop
disconnectrg   r   r   rr   r!   r"   sysexit)r   s    r   stop_mqtt_clientr     sX    #$ (I	ww~~i >?
 !r   __main__   z
Exiting...)3httpr   r   django.utilsr   modelsr   r   r   r	   r
   uuidpaho.mqtt.clientr   r   	django.dbr   r,   r   r   iodjango.db.modelsr   timer!   TextIOWrapperstdoutbufferr   r   r   r   ri   uuid4r   r   MQTT_TOPIC_PUBrx   r   r   r   r(   r   r   r   r   r   __name__sleepKeyboardInterruptrg   r   r   r   <module>r      s!     ! E E    
    
 	 	   Rcjj//'B
 	#ZTZZ\"@ ( 
 PC R&
0$%N z FDJJqM  
  ls   C2 2D	D	