'''
  _   _ ____  __  __ 
 | \ | |  _ \|  \/  |
 |  \| | |_) | |\/| |
 | |\  |  __/| |  | |
 |_| \_|_|   |_|  |_|
                                     
Script to get NPM values (PM1, PM2.5 and PM10)
PM and the sensor temp/hum
And store them inside sqlite database
Uses RTC module for timing (from SQLite db)
/usr/bin/python3 /var/www/moduleair_pro_4g/NPM/get_data_v2.py
'''

import serial
import requests
import json
import sys
import sqlite3
import smbus2
import time
from datetime import datetime

# Connect to the SQLite database
conn = sqlite3.connect("/var/www/nebuleair_pro_4g/sqlite/sensors.db")
cursor = conn.cursor()

def load_config(config_file):
    try:
        with open(config_file, 'r') as file:
            config_data = json.load(file)
        return config_data
    except Exception as e:
        print(f"Error loading config file: {e}")
        return {}

# Load the configuration data
config_file = '/var/www/nebuleair_pro_4g/config.json'
config = load_config(config_file)
npm_solo_port = config.get('NPM_solo_port', '')  #port du NPM solo

ser = serial.Serial(
    port=npm_solo_port,
    baudrate=115200,
    parity=serial.PARITY_EVEN,
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.EIGHTBITS,
    timeout = 0.5
)

# 1️⃣ Request PM Data (PM1, PM2.5, PM10)

#ser.write(b'\x81\x11\x6E')      #data10s
ser.write(b'\x81\x12\x6D')      #data60s
time.sleep(0.5)  # Small delay to allow the sensor to process the request

#print("Start get_data_v2.py script")
byte_data = ser.readline()
#print(byte_data)
stateByte = int.from_bytes(byte_data[2:3], byteorder='big')
Statebits = [int(bit) for bit in bin(stateByte)[2:].zfill(8)]
PM1 = int.from_bytes(byte_data[9:11], byteorder='big')/10
PM25 = int.from_bytes(byte_data[11:13], byteorder='big')/10
PM10 = int.from_bytes(byte_data[13:15], byteorder='big')/10

# 2️⃣ Request Temperature & Humidity
ser.write(b'\x81\x14\x6B')  # Temp and humidity command
time.sleep(0.5)  # Small delay to allow the sensor to process the request
byte_data_temp_hum = ser.readline()

# Decode temperature and humidity values
temperature = int.from_bytes(byte_data_temp_hum[3:5], byteorder='big') / 100.0
humidity = int.from_bytes(byte_data_temp_hum[5:7], byteorder='big') / 100.0

#print(f"State: {Statebits}")
#print(f"PM1: {PM1}")
#print(f"PM25: {PM25}")
#print(f"PM10: {PM10}")
#print(f"temp: {temperature}")
#print(f"hum: {humidity}")

#GET RTC TIME from SQlite
cursor.execute("SELECT * FROM timestamp_table LIMIT 1")
row = cursor.fetchone()  # Get the first (and only) row
rtc_time_str = row[1]  # '2025-02-07 12:30:45'

#save to sqlite database
try:
    cursor.execute('''
    INSERT INTO data_NPM (timestamp,PM1, PM25, PM10, temp_npm, hum_npm) VALUES (?,?,?,?,?,?)'''
    , (rtc_time_str,PM1,PM25,PM10,temperature,humidity  ))

    # Commit and close the connection
    conn.commit()

    #print("Sensor data saved successfully!")

except Exception as e:
    print(f"Database error: {e}")    


conn.close()


