import paho.mqtt.client as mqtt
from time import sleep
import picamera
import time
import RPi.GPIO as GPIO
from ftplib import FTP
ftp=FTP('10.95.1.21','etudiants_geii','geii')

def on_connect(client, userdata,flags,rc):
    if rc == 0:
         print("Connected successfully.")
    else:
         print("Connection failed. rc= "+str("rc"))

def on_publish(client, userdata, mid):
    print("Message sent")
    
def on_subscribe(client, userdata, mid, granted_qos):
    print("Subscribe with mid "+str(mid)+" received.")

SNAP_Image=0

mqttclient = mqtt.Client()

# Assign event callbacks
mqttclient.on_publish = on_publish
mqttclient.on_subscribe = on_subscribe
mqttclient.on_connect = on_connect


# Connect
mqttclient.connect('broker.hivemq.com', 1883,60)

# Start subscription
mqttclient.subscribe("Projiut/Images/Eau")
mqttclient.subscribe("Eau/image")
mqttclient.subscribe("Eau/image/demande")

mqttclient.loop_start()

while True:
    def on_message(client, userdata, msg):
        print("Message received on topic "+msg.topic+" with QoS "+str(msg.qos) + " / " )
        if (msg.topic=='Eau/image/demande'):
            print ("image received: SNAP and publish")
            GPIO.setwarnings(False)
            GPIO.setmode(GPIO.BOARD)
            GPIO.setup(11,GPIO.OUT)
            GPIO.output(11,True)
            GPIO.setup(7,GPIO.OUT)
            GPIO.output(7,True)
            sleep(1)
            camera = picamera.PiCamera()

            try: 
                camera.start_preview()
                sleep(5)
                camera.capture('Demande/image.jpg', resize=(500,281))
                camera.stop_preview()
                pass
            finally:
                camera.close()
            sleep(1)
            GPIO.output(11,False)
            GPIO.output(7,False)
            # chargement de l'image avant envoi
            f=open("Demande/image.jpg", "rb") #3.7kiB in same folder
            fileContent = f.read()
            ftp.storbinary('STOR '+'CptEau/' +time.strftime('%Y-%m-%d-%h-%M')+'_Demande.jpg',f)
            byteArr = bytearray(fileContent)
            f.close()
            mqttclient.publish("Eau/image",byteArr,1)


    GPIO.setwarnings(False)
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(11,GPIO.OUT)
    GPIO.output(11,True)
    GPIO.setup(7,GPIO.OUT)
    GPIO.output(7,True)
    sleep(1)
    camera = picamera.PiCamera()

    try: 
        camera.start_preview()
        sleep(5)
        camera.capture('Frequence/image.jpg', resize=(500,281))
        camera.stop_preview()
        pass
    finally:
        camera.close()
    sleep(1)
    GPIO.output(11,False)
    GPIO.output(7,False)
    f=open("Frequence/image.jpg", "rb") #3.7kiB in same folder
    ftp.storbinary('STOR ' +'CptEau/'+time.strftime('%Y-%m-%d-%h-%M')+'.jpg',f)
    fileContent = f.read()
    byteArr1 = bytearray(fileContent)
    f.close()
    mqttclient.publish("Projiut/Images/Eau",byteArr1,1)
    mqttclient.on_message=on_message
    sleep(900)


