Repository navigation
Expand file tree
/
Copy pathpythonsql.py
More file actions
144 lines (116 loc) · 5.04 KB
/
Copy pathpythonsql.py
File metadata and controls
144 lines (116 loc) · 5.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
import psycopg2
from psycopg2 import Error
import datetime
import serial
import time
from twilio.rest import Client
# -------------------- Introduction --------------------
print(r"""
_________ __ ___ __
/ _____/ _____ _____ ________/ |\_ |__ |__| ____
\_____ \ / \\__ \\_ __ \ __\ __ \| |/ \
/ \ Y Y \/ __ \| | \/| | | \_\ \ | | \
/_______ /__|_| (____ /__| |__| |___ /__|___| /
\/ \/ \/ \/ \/
""")
print("🗑️ Smart Bin Terminal - Initializing...\n")
# -------------------- PostgreSQL --------------------
def connect_to_postgresql():
try:
connection = psycopg2.connect(
host="192.168.183.98",
database="smartbin",
user="smartbin_user",
password="secure_password",
port="5432"
)
cursor = connection.cursor()
print("✅ Connexion PostgreSQL établie.")
return connection, cursor
except (Exception, Error) as error:
print(f"❌ Erreur de connexion PostgreSQL : {error}")
return None, None
def close_connection(connection, cursor):
if cursor:
cursor.close()
if connection:
connection.close()
print("🔒 Connexion PostgreSQL fermée.")
def add_row_to_history(bin_id, bin_level, bin_date, bin_temp, bin_humidity):
conn, cur = connect_to_postgresql()
if conn and cur:
try:
cur.execute("""
INSERT INTO history (id, level, date, temperature, humidity)
VALUES (%s, %s, %s, %s, %s)
""", (bin_id, bin_level*100, bin_date, bin_temp, bin_humidity))
conn.commit()
print(f"✅ Données insérées : id={bin_id}, niveau={bin_level*100}, temp={bin_temp}, humid={bin_humidity}")
# Envoi d'un SMS si température critique
if bin_temp >= 50:
send_sms_notification(bin_id, bin_temp, bin_date)
except Exception as e:
print(f"❌ Erreur d'insertion : {e}")
finally:
close_connection(conn, cur)
# -------------------- Envoi SMS Twilio --------------------
def send_sms_notification(bin_id, temperature, date):
try:
#Les SID/TOKEN sont à rajouter à la main
account_sid = ''
auth_token = ''
messaging_service_sid = ''
to_number = '+33769048181'
client = Client(account_sid, auth_token)
message = client.messages.create(
messaging_service_sid=messaging_service_sid,
body=f"⚠️ Alerte SmartBin\nID: {bin_id} | Température: {temperature}°C\nDate: {date}",
to=to_number
)
print("📲 SMS envoyé :", message.sid)
except Exception as e:
print("❌ Échec de l'envoi du SMS :", e)
# -------------------- Lecture Port Série --------------------
def read_from_serial(port='/dev/ttyUSB0', baudrate=115200):
taillemax = 200
try:
ser = serial.Serial(port, baudrate, timeout=2)
print(f"📡 Port série {port} ouvert.\n")
buffer = []
while True:
try:
line = ser.readline().decode(errors='ignore').strip()
if not line:
continue
print(f"📥 Reçu: {line}")
if line.startswith("id") or line.startswith("temp"):
buffer.append(line)
while len(buffer) >= 2:
if buffer[0].startswith("id") and buffer[1].startswith("temp"):
try:
line1 = buffer.pop(0)
line2 = buffer.pop(0)
bin_id = int(line1.split(';')[0].split(':')[1].strip())
level = float(line1.split(';')[1].split(':')[1].replace('cm','').strip())
level = level / taillemax
temp = float(line2.split(';')[0].split(':')[1].strip())
hum = float(line2.split(';')[1].split(':')[1].strip())
date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(f"✅ Données extraites : id={bin_id}, niveau={level}, temp={temp}, hum={hum}, date={date}")
add_row_to_history(bin_id, level, date, temp, hum)
except Exception as e:
print(f"❌ Erreur de parsing couple : {e}")
buffer = []
else:
buffer.pop(0)
time.sleep(0.1)
except Exception as e:
print(f"❌ Erreur de lecture/parsing : {e}")
continue
except serial.SerialException as e:
print(f"❌ Impossible d'ouvrir le port série : {e}")
# -------------------- Exécution principale --------------------
if __name__ == "__main__":
print("🔄 Démarrage de la lecture du port série...")
read_from_serial(port='/dev/ttyUSB0', baudrate=115200)
print("🔚 Fin de la lecture du port série.")