void setup() {
  // put your setup code here, to run once:
  Serial1.begin(115200);
  Serial1.println("Hello, Raspberry Pi Pico!");
}

void loop() {
  // put your main code here, to run repeatedly:
  delay(1); // this speeds up the simulation
}

from flask import Flask, render_template, redirect, url_for, request , Response ,jsonify ,send_file
import datetime
import time
import threading
import pandas as pd
import cv2
from picamera2 import Picamera2
import Adafruit_DHT
import RPi.GPIO as GPIO
import smbus
cv2.startWindowThread()

picam2 = Picamera2()
picam2.configure(picam2.create_preview_configuration(main={"format": 'XRGB8888', "size": (640, 480)}))
picam2.start()
global flame,hum,temp,Waterl,O2S ,Co2S ,Status,x ,auto , stat ,reco
reco ="0"
auto = 0
flame =0
hum =0
temp =0
Waterl =0
O2S = 0
Co2S=0
Status= "0"
x="0"
####################################################################################################

###ADC###
###########################################
address = 0x48
A0= 0x44 ### level water
A1= 0x45 ###gas1
A2= 0x46 ###gas2
bus = smbus.SMBus(1)
#############################################
###DHT22###
#############################################
DHT_SENSOR = Adafruit_DHT.DHT22
#############################################
#############################################
led1_pin = 17
led2_pin = 27
led3_pin = 22
led4_pin = 23
led5_pin = 24
led6_pin = 25
buzzer = 16
Relay1 = 6
Relay2 = 5
DHT_PIN = 13
flam = 26
GPIO.setmode(GPIO.BCM)
GPIO.setup(flam, GPIO.IN)
GPIO.setup(led1_pin, GPIO.OUT)
GPIO.setup(led2_pin, GPIO.OUT)
GPIO.setup(led3_pin, GPIO.OUT)
GPIO.setup(led4_pin, GPIO.OUT)
GPIO.setup(led5_pin, GPIO.OUT)
GPIO.setup(led6_pin, GPIO.OUT)
GPIO.setup(buzzer, GPIO.OUT)
GPIO.setup(Relay1, GPIO.OUT)
GPIO.setup(Relay2, GPIO.OUT)
##############################################
##############################################
# Define I2C address of the LCD
LCD_ADDRESS = 0x27

# Define some device constants
LCD_WIDTH = 16   # Maximum characters per line

# Define some device constants
LCD_CHR = 1 # Mode - Sending data
LCD_CMD = 0 # Mode - Sending command

LCD_LINE_1 = 0x80 # LCD RAM address for the 1st line
LCD_LINE_2 = 0xC0 # LCD RAM addreKLss for the 2nd line
LCD_LINE_3 = 0x94 # LCD RAM address for the 3rd line
LCD_LINE_4 = 0xD4 # LCD RAM address for the 4th line

LCD_BACKLIGHT  = 0x08  # On
#LCD_BACKLIGHT = 0x00  # Off

ENABLE = 0b00000100 # Enable bit

# Timing constants
E_PULSE = 0.0005
E_DELAY = 0.0005


###############################################

def lcd_byte(bits, mode):
    # Send byte to data pins
    # bits = the data
    # mode = 1 for data, 0 for command

    bits_high = mode | (bits & 0xF0) | LCD_BACKLIGHT
    bits_low = mode | ((bits<<4) & 0xF0) | LCD_BACKLIGHT

    # High bits
    bus.write_byte(LCD_ADDRESS, bits_high)
    lcd_toggle_enable(bits_high)

    # Low bits
    bus.write_byte(LCD_ADDRESS, bits_low)
    lcd_toggle_enable(bits_low)

def lcd_toggle_enable(bits):
    # Toggle enable
    time.sleep(E_DELAY)
    bus.write_byte(LCD_ADDRESS, (bits | ENABLE))
    time.sleep(E_PULSE)
    bus.write_byte(LCD_ADDRESS, (bits & ~ENABLE))
    time.sleep(E_DELAY)

def lcd_string(message, line):
    # Send string to display
    message = message.ljust(LCD_WIDTH," ")

    lcd_byte(line, LCD_CMD)

    for i in range(LCD_WIDTH):
        lcd_byte(ord(message[i]),LCD_CHR)

def lcd_display_message(message):
    lcd_string(message, LCD_LINE_1)


# Initialize display
lcd_byte(0x33,LCD_CMD) # 110011 Initialise
lcd_byte(0x32,LCD_CMD) # 110010 Initialise
lcd_byte(0x06,LCD_CMD) # 000110 Cursor move direction
lcd_byte(0x0C,LCD_CMD) # 001100 Display On,Cursor Off, Blink Off
lcd_byte(0x28,LCD_CMD) # 101000 Data length, number of lines, font size
lcd_byte(0x01,LCD_CMD) # 000001 Clear display
time.sleep(E_DELAY)
########################################


######################################################################################################
sensor_data = {
    "Date": [],
    "Time": [],
    "flame": [],
    "temp": [],
    "hum": [],
    "O2S": [],
    "Co2S": [],
    "Waterl": [],
    "Status": []

}


def save_sensor_values():
    global flame,hum,temp,Waterl,O2S ,Co2S ,Status

    # الحصول على الوقت والتاريخ الحالي
    current_time_str = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    # تقسيم النص إلى جزئين باستخدام الفراغ كفاصل
    current_time_parts = current_time_str.split(' ')
    # الجزء الأول يحتوي على التاريخ
    current_date_str = current_time_parts[0]
    # الجزء الثاني يحتوي على الوقت
    current_time_str = current_time_parts[1]
    # إضافة البيانات الحالية إلى القاموس
    sensor_data["Date"].append(current_date_str)
    sensor_data["Time"].append(current_time_str)
    sensor_data["flame"].append(flame)
    sensor_data["temp"].append(temp)
    sensor_data["hum"].append(hum)
    sensor_data["O2S"].append(O2S)
    sensor_data["Co2S"].append(Co2S)
    sensor_data["Waterl"].append(Waterl)
    sensor_data["Status"].append(Status)

    # إنشاء DataFrame باستخدام البيانات
    df = pd.DataFrame(sensor_data)

    # حفظ DataFrame في ملف CSV
    df.to_csv("sensor_data.csv", index=False)


def save_data():
    while True:
        save_sensor_values()
        time.sleep(2)

def framex():
    global reco
    # افتح مسجل الفيديو
    fourcc = cv2.VideoWriter_fourcc(*'XVID')  # يمكنك تغيير الرمز بتنسيق الفيديو المطلوب
    out = cv2.VideoWriter('output.avi', fourcc, 30.0, (640, 480))  # تعيين الاسم ومعلمات الفيديو


        # اغلق مسجل الفيديو وقم بتدمير النوافذ المفتوحة
    out.release()
    cv2.destroyAllWindows()

def generate_frames():
    while True:
        frame = picam2.capture_array()  # قراءة الإطارات من الكاميرا

        # تحويل الإطار إلى تنسيق JPEG
        ret, buffer = cv2.imencode('.jpg', frame)
        frame = buffer.tobytes()

        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')

app = Flask(__name__)

@app.route("/", methods=['GET', 'POST'])
def index():
    return redirect(url_for('login'))
@app.route("/login", methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        if username == 'smart' and password == '56515651':
            return redirect(url_for('home'))  # توجيه المستخدم إلى صفحة home.html
        else:
            return render_template('login.html', error=True) # إعادة تحميل صفحة الدخول مع عرض رسالة خطأ
    return render_template('login.html')


@app.route("/home")
def home():
    return render_template('home.html',flame=flame, temp=temp, hum=hum, Waterl=Waterl, O2S=O2S, Co2S=Co2S, Status=stat)

@app.route("/about")
def about():
    return render_template('about.html')

@app.route("/video_feed")
def video_feed():
    return Response(generate_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')

@app.route("/download_csv")
def download_csv():
    return send_file("sensor_data.csv", as_attachment=True)

@app.route('/AUTO', methods=['POST'])
def open_window():
    global x,auto
    auto= 1

    return jsonify({'message': 'AUTO'})

@app.route('/Manual', methods=['POST'])
def Manual():
    global x , auto
    auto = 0

    return jsonify({'message': 'Manual'})

@app.route('/fanopen', methods=['POST'])
def fanopen():
    global x
    x = "8"

    return jsonify({'message': 'fanopen'})

@app.route('/fanclose', methods=['POST'])
def fanclose():
    global x
    x = "18"

    return jsonify({'message': 'fanclose'})
#################################3
@app.route('/ligthon', methods=['POST'])
def ligthon():
    global x
    x = "9"

    return jsonify({'message': 'fanopen'})

@app.route('/ligthoff', methods=['POST'])
def ligthoff():
    global x
    x = "19"

    return jsonify({'message': 'ligthoff'})
########################################
@app.route('/dooron', methods=['POST'])
def dooron():
    global x
    x = "1"

    return jsonify({'message': 'dooron'})

@app.route('/dooroff', methods=['POST'])
def dooroff():
    global x
    x = "11"

    return jsonify({'message': 'dooroff'})
########################################
@app.route('/Isolateon', methods=['POST'])
def Isolateon():
    global x
    x = "5"

    return jsonify({'message': 'Isolateon'})

@app.route('/Isolateoff', methods=['POST'])
def Isolateoff():
    global x
    x = "15"

    return jsonify({'message': 'Isolateoff'})
########################################
@app.route('/gason', methods=['POST'])
def gason():
    global x
    x = "3"

    return jsonify({'message': 'gason'})

@app.route('/gasoff', methods=['POST'])
def gasoff():
    global x
    x = "13"

    return jsonify({'message': 'gasoff'})
########################################
@app.route('/wateron', methods=['POST'])
def wateron():
    global x
    x = "4"

    return jsonify({'message': 'wateron'})

@app.route('/wateroff', methods=['POST'])
def wateroff():
    global x
    x = "14"

    return jsonify({'message': 'wateroff'})
########################################

def start_flask():
    app.run(host='192.168.45.248', port=5000)


def Sensor():
    global flame,hum,temp,Waterl,O2S ,Co2S ,Status ,x,auto ,stat ,reco
    lcd_byte(0x01, LCD_CMD) # Clear display

    while True:




        bus.write_byte(address,A0)
        value0 = bus.read_byte(address)
        Waterl = int(((value0 /255 )*100))
        Waterl = "{0:0.1f} % ".format(Waterl)
        print(Waterl)


       ################################
        bus.write_byte(address,A1)
        value1 = bus.read_byte(address)
        value1 = int(((value1 /255 )*100))
        Co2S =value1
        Co2S = "{0:0.1f} % ".format(Co2S)
        print(value1)
        ###########################
        bus.write_byte(address,A2)
        value2 = bus.read_byte(address)

        value2 = int(((value2 /255 )*100))
        O2S =value2
        O2S = "{0:0.1f} % ".format(O2S)
        print(value2)
        humidity, temperature = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)
        temp = "{0:0.1f} C ".format(temperature)

        hum = "{0:0.1f} % ".format(humidity)
        if humidity is not None and temperature is not None:
            print("Temp = {0:0.1f} C  Humidity = {1:0.1f}%".format(temperature, humidity))

        else:
            print("Sensor failure")

        print (GPIO.input(flam))
        if  GPIO.input(flam):
            flame = "Not Detecting"
        else:
            flame = "Detecting fire"
        ####################################
        if auto == 1 :
            print ("auto")
            print (temperature)


            if flame == "Detecting fire" :
                print ("xxxxxxxxxxxxxxxxx")
                if temperature >20 and temperature <80  and  value2 < 50 and value1 >50:
                    Status="2"
                    reco ="A"

                if temperature >50 and  humidity < 30 and  value2 < 50 and value1 <55:
                    Status="1"
                    reco ="A"

            if flame == "Not Detecting" :
                if  value2 < 60 :
                    if value1 >65 :
                        Status="4"
                        reco ="A"
                        print (4)
                    else :
                        print("ggggggggggggggg")
                        Status="0"
                        reco ="B"

                if  value2 > 60 :
                        Status="3"
                        reco ="A"
                        print (3)
                if  temperature ==0 or humidity == 0 or value2 ==0 or value1 ==0 :
                    Status="5"
                    print (5)


            if (Status=="0"):
                stat = "Normal Condition"
                lcd_display_message("Normal Condition")
                GPIO.output(led1_pin, GPIO.LOW)
                GPIO.output(led2_pin, GPIO.LOW)
                GPIO.output(led3_pin, GPIO.LOW)
                GPIO.output(led4_pin, GPIO.LOW)
                GPIO.output(led5_pin, GPIO.LOW)
                GPIO.output(led6_pin, GPIO.LOW)
                GPIO.output(buzzer, GPIO.LOW)
                GPIO.output(Relay1, GPIO.HIGH)
                GPIO.output(Relay2, GPIO.HIGH)


            if (Status=="1"):
                stat ="Chemical Firing"
                lcd_display_message("Chemical Firing")
                GPIO.output(buzzer, GPIO.HIGH)
                GPIO.output(led5_pin, GPIO.HIGH)
                GPIO.output(led3_pin, GPIO.HIGH)
                GPIO.output(led1_pin, GPIO.HIGH)
                picam2.start_and_record_video("ChemicalFiring.mp4", duration=10)
            if (Status=="2"):
                stat = "Normal Firing"
                lcd_display_message("Normal Firing")
                GPIO.output(buzzer, GPIO.HIGH)
                GPIO.output(led5_pin, GPIO.HIGH)
                GPIO.output(led3_pin, GPIO.HIGH)
                GPIO.output(led1_pin, GPIO.HIGH)
                GPIO.output(led4_pin, GPIO.HIGH)
                picam2.start_and_record_video("Firing.mp4", duration=10)
            if (Status=="3"):
                lcd_display_message("Gas Leakage")
                stat = "Gas Leakage"
                GPIO.output(buzzer, GPIO.HIGH)
                GPIO.output(led3_pin, GPIO.HIGH)
                GPIO.output(led5_pin, GPIO.HIGH)
                GPIO.output(led1_pin, GPIO.HIGH)
                GPIO.output(Relay1, GPIO.LOW)
                picam2.start_and_record_video("Gas.mp4", duration=10)
            if (Status=="4"):
                stat = "Smoke Emmision"
                lcd_display_message("Smoke Emmision")
                GPIO.output(buzzer, GPIO.HIGH)
                GPIO.output(led3_pin, GPIO.HIGH)
                GPIO.output(led5_pin, GPIO.HIGH)
                GPIO.output(led1_pin, GPIO.HIGH)
                GPIO.output(Relay1, GPIO.LOW)
                picam2.start_and_record_video("Smoke.mp4", duration=10)
            if (Status=="5"):
                stat = "System Down"
                lcd_display_message("System Down")
                GPIO.output(led1_pin, GPIO.LOW)
                GPIO.output(led2_pin, GPIO.LOW)
                GPIO.output(led3_pin, GPIO.LOW)
                GPIO.output(led4_pin, GPIO.LOW)
                GPIO.output(led5_pin, GPIO.LOW)
                GPIO.output(led6_pin, GPIO.LOW)
                GPIO.output(buzzer, GPIO.LOW)
                GPIO.output(Relay1, GPIO.HIGH)
                GPIO.output(Relay2, GPIO.HIGH)
                picam2.start_and_record_video("SystemD.mp4", duration=10)
        else:
            stat = "manual"
            lcd_display_message("manual")
            print("manual")
            print (f"x = {x}")
        ##################################################
            if ( x== "0"):
                GPIO.output(led1_pin, GPIO.LOW)
                GPIO.output(led2_pin, GPIO.LOW)
                GPIO.output(led3_pin, GPIO.LOW)
                GPIO.output(led4_pin, GPIO.LOW)
                GPIO.output(led5_pin, GPIO.LOW)
                GPIO.output(led6_pin, GPIO.LOW)
                GPIO.output(buzzer, GPIO.LOW)
                GPIO.output(Relay1, GPIO.HIGH)
                GPIO.output(Relay2, GPIO.HIGH)
            if (x=="1"):
                GPIO.output(led1_pin, GPIO.HIGH)
                print("door open")
            if (x=="11"):
                GPIO.output(led1_pin, GPIO.LOW)
                print("door close")
            if (x=="2"):
                GPIO.output(led2_pin, GPIO.HIGH)
            if (x=="12"):
                GPIO.output(led2_pin, GPIO.LOW)
            if (x=="3"):
                GPIO.output(led3_pin, GPIO.HIGH)
            if (x=="13"):
                GPIO.output(led3_pin, GPIO.LOW)
            if (x=="4"):
                GPIO.output(led4_pin, GPIO.HIGH)
            if (x=="14"):
                GPIO.output(led4_pin, GPIO.LOW)
            if (x=="5"):
                GPIO.output(led5_pin, GPIO.HIGH)
            if (x=="15"):
                GPIO.output(led5_pin, GPIO.LOW)
            if (x=="6"):
                GPIO.output(led6_pin, GPIO.HIGH)
            if (x=="7"):
                GPIO.output(buzzer, GPIO.HIGH)
            if (x=="8"):
                print("fan on")
                GPIO.output(Relay1, GPIO.LOW)
            if (x=="18"):
                print ("fan off")
                GPIO.output(Relay1, GPIO.HIGH)
            if (x=="9"):
                print("light on")
                GPIO.output(Relay2, GPIO.LOW)
            if (x=="19"):
                print("light off")
                GPIO.output(Relay2, GPIO.HIGH)





if __name__ == "__main__":
    thread1 = threading.Thread(target=start_flask)
    thread2 = threading.Thread(target=Sensor)
    thread3 = threading.Thread(target=save_data)
    thread4 = threading.Thread(target=framex)
    thread1.start()
    thread2.start()
    thread3.start()
    thread4.start()
BOOTSELLED1239USBRaspberryPiPico©2020RP2-8020/21P64M15.00TTT