Compare commits

...

32 Commits

Author SHA1 Message Date
059552eb81 1.3 2026-03-31 23:37:54 +02:00
fa94a4564d on voit le bout du tunnel 2026-03-31 20:53:02 +02:00
6d8f7dad4a Maj 7segment 2026-03-31 20:36:38 +02:00
7790694fb9 Maj bouton 2026-03-31 20:31:02 +02:00
af8e674cb9 maj des API 2026-03-31 20:09:52 +02:00
bf5b24214c maj vers BCM 2026-03-31 20:09:26 +02:00
c378be1695 . 2026-03-30 23:22:11 +02:00
98aa5fceb1 . 2026-03-30 23:21:57 +02:00
488289e2cf . 2026-03-30 23:21:28 +02:00
76e8ecadc1 . 2026-03-30 23:19:01 +02:00
bb566f7da2 . 2026-03-30 23:17:08 +02:00
703f7df12f piou piou 2026-03-30 22:10:28 +02:00
dbf6e807ae mise à jour numéro je sais pas combien 2026-03-30 22:09:23 +02:00
fd17c22dfc maj README 2026-03-30 21:47:46 +02:00
5d6a2bb32b api presque fonctionnel 2026-03-30 21:46:43 +02:00
72a86ff512 wallah pardon sur le coran de l eglise c'est pas de ma faute 2026-03-30 20:53:53 +02:00
8c3713eff6 maj par maim 2026-03-30 20:04:58 +02:00
785508ba53 maj README 2026-03-30 20:02:03 +02:00
0d3f9d82d4 maj README 2026-03-30 20:01:32 +02:00
951f073481 maj README 2026-03-30 19:59:45 +02:00
9a109c49e6 1.1 2026-03-30 19:55:04 +02:00
4e7a41d7aa maj readme 2026-03-30 18:22:47 +02:00
119027dc00 ajout threading 2026-03-30 18:20:42 +02:00
87774e5303 liaison rfid html 2026-03-30 18:18:50 +02:00
0db365014a liaison rfid html 2026-03-30 18:16:20 +02:00
1eee629102 liaison rfid 2026-03-30 18:09:36 +02:00
474a10aa43 1.0 2026-03-30 17:49:18 +02:00
50a48c5292 liaison python et html 2026-03-30 14:00:03 +02:00
afee1262eb mise en place code panda sur html 2026-03-27 15:00:11 +01:00
9d3c201672 wola j'avais oublié ces codes 2026-03-27 13:33:32 +01:00
f5ba39da8d code esteban 2026-03-27 13:29:22 +01:00
1f84b5bc09 mise à jour par Greg 2026-03-26 14:47:53 +01:00
72 changed files with 5062 additions and 619 deletions

2
.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
*.pem
.env

View File

@@ -0,0 +1,19 @@
import Adafruit_DHT as dht
import time as t
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
capteur = dht.DHT11
pin = 25
def lire_temperature():
humidite, temperature = dht.read_retry(capteur, pin)
if temperature is not None:
print("Temp :", temperature, "°C")
else:
print("Erreur")
t.sleep(2)
lire_temperature()

Binary file not shown.

View File

@@ -0,0 +1,246 @@
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
class SystemeAlarme:
def __init__(self):
"""
Initialise les composants liés à l'alarme.
Cette classe gère uniquement la logique locale de sécurité :
- le capteur PIR
- le buzzer
- la LED RGB de statut
- le clavier 4x4
Elle ne dépend d'aucune autre partie du projet.
"""
# -----------------------------
# Définition des pins physiques
# -----------------------------
self.pinPir = 22
self.pinBuzzer = 12
self.pinLedRouge = 11
self.pinLedVerte = 13
self.pinLedBleue = 15
# Clavier 4x4
# 4 lignes + 4 colonnes
self.lignes = [29, 31, 33, 35]
self.colonnes = [37, 32, 36, 38]
# Disposition classique d'un clavier 4x4
self.touches = [
["1", "2", "3", "A"],
["4", "5", "6", "B"],
["7", "8", "9", "C"],
["*", "0", "#", "D"]
]
# -----------------------------
# Variables de fonctionnement
# -----------------------------
self.codeSecret = "1234"
self.codeSaisi = ""
# Etats possibles :
# - desarme
# - arme
# - alarme
self.etat = "desarme"
# Anti-rebond clavier
self.derniereLecture = 0
self.delaiLecture = 0.25
self.initialiserGPIO()
self.mettreAJourEtat()
def initialiserGPIO(self):
"""Configure les broches du Raspberry Pi pour l'alarme."""
GPIO.setup(self.pinPir, GPIO.IN)
GPIO.setup(self.pinBuzzer, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(self.pinLedRouge, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(self.pinLedVerte, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(self.pinLedBleue, GPIO.OUT, initial=GPIO.LOW)
for pin in self.lignes:
GPIO.setup(pin, GPIO.OUT, initial=GPIO.LOW)
for pin in self.colonnes:
GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
def definirCouleur(self, rouge, vert, bleu):
"""
Allume la LED RGB selon la couleur voulue.
Paramètres :
- rouge : True / False
- vert : True / False
- bleu : True / False
"""
GPIO.output(self.pinLedRouge, GPIO.HIGH if rouge else GPIO.LOW)
GPIO.output(self.pinLedVerte, GPIO.HIGH if vert else GPIO.LOW)
GPIO.output(self.pinLedBleue, GPIO.HIGH if bleu else GPIO.LOW)
def mettreAJourEtat(self):
"""
Met à jour les sorties selon l'état actuel du système.
- desarme : LED verte, buzzer éteint
- arme : LED bleue, buzzer éteint
- alarme : LED rouge, buzzer allumé
"""
if self.etat == "desarme":
self.definirCouleur(False, True, False)
GPIO.output(self.pinBuzzer, GPIO.LOW)
elif self.etat == "arme":
self.definirCouleur(False, False, True)
GPIO.output(self.pinBuzzer, GPIO.LOW)
elif self.etat == "alarme":
self.definirCouleur(True, False, False)
GPIO.output(self.pinBuzzer, GPIO.HIGH)
def armer(self):
"""Passe le système en mode armé."""
self.etat = "arme"
self.codeSaisi = ""
self.mettreAJourEtat()
print("Alarme activée.")
def desarmer(self):
"""Passe le système en mode désarmé."""
self.etat = "desarme"
self.codeSaisi = ""
self.mettreAJourEtat()
print("Alarme désactivée.")
def declencherAlarme(self):
"""
Déclenche l'alarme si un mouvement est détecté alors
que le système est armé.
"""
if self.etat != "alarme":
self.etat = "alarme"
self.codeSaisi = ""
self.mettreAJourEtat()
print("Intrusion détectée : alarme déclenchée.")
def lireClavier(self):
"""
Scanne le clavier 4x4.
Retour :
- la touche détectée
- None si aucune touche n'est pressée
"""
maintenant = time.time()
if maintenant - self.derniereLecture < self.delaiLecture:
return None
for indexLigne, ligne in enumerate(self.lignes):
GPIO.output(ligne, GPIO.HIGH)
for indexColonne, colonne in enumerate(self.colonnes):
if GPIO.input(colonne) == GPIO.HIGH:
GPIO.output(ligne, GPIO.LOW)
self.derniereLecture = maintenant
# Petite attente pour éviter la lecture multiple
time.sleep(0.05)
return self.touches[indexLigne][indexColonne]
GPIO.output(ligne, GPIO.LOW)
return None
def validerCode(self):
"""
Vérifie le code saisi.
Si le code est correct :
- alarme désarmée -> armée
- alarme armée -> désarmée
- alarme déclenchée -> désarmée
Si le code est faux :
- on efface la saisie
"""
if self.codeSaisi == self.codeSecret:
if self.etat == "desarme":
self.armer()
else:
self.desarmer()
else:
print("Code incorrect.")
self.codeSaisi = ""
def traiterClavier(self, touche):
"""
Gère la logique du clavier :
- chiffres : ajout au code saisi
- * : efface la saisie
- # : valide le code
"""
if touche is None:
return
print("Touche appuyée :", touche)
if touche == "*":
self.codeSaisi = ""
print("Saisie effacée.")
return
if touche == "#":
self.validerCode()
return
if touche.isdigit():
if len(self.codeSaisi) < 8:
self.codeSaisi += touche
print("Code en cours :", "*" * len(self.codeSaisi))
def surveillerPIR(self):
"""
Vérifie le capteur de mouvement.
Si un mouvement est détecté alors que l'alarme est armée,
on passe en état d'alarme.
"""
mouvement = GPIO.input(self.pinPir) == GPIO.HIGH
if self.etat == "arme" and mouvement:
self.declencherAlarme()
def mettreAJour(self):
"""
Fonction appelée en boucle dans le programme principal.
Elle :
- lit le clavier
- traite la touche appuyée
- surveille le PIR
- synchronise LED et buzzer avec l'état courant
"""
touche = self.lireClavier()
self.traiterClavier(touche)
self.surveillerPIR()
self.mettreAJourEtat()
def cleanup(self):
"""
Remet les sorties dans un état propre à la fermeture.
"""
GPIO.output(self.pinBuzzer, GPIO.LOW)
self.definirCouleur(False, False, False)

View File

@@ -0,0 +1,31 @@
import time
from alarme import SystemeAlarme
from porterfid import SystemePorteRFID
# ------------------------------------------------------------
# board1main.py
# ------------------------------------------------------------
# Ce fichier lance uniquement la logique locale de la board 1.
# Il ne dépend pas du site web, de la base de données ni de Flask.
# Son rôle est simplement de faire tourner :
# - le système d'alarme
# - le système de porte RFID
# ------------------------------------------------------------
alarme = SystemeAlarme()
porte = SystemePorteRFID()
try:
while True:
# Mise à jour des deux modules locaux
alarme.mettreAJour()
porte.mettreAJour()
time.sleep(0.05)
except KeyboardInterrupt:
print("\nArrêt manuel du programme.")
finally:
# On remet les sorties dans un état propre avant de quitter
alarme.cleanup()
porte.cleanup()

View File

@@ -0,0 +1,32 @@
import time
from thermostat import SystemeThermostat
from lumieres import SystemeLumieres
from volets import SystemeVolets
from etatsysteme import EtatSysteme
thermostat = SystemeThermostat()
lumieres = SystemeLumieres()
volets = SystemeVolets()
etat = EtatSysteme()
try:
while True:
erreurThermostat = thermostat.mettreAJour()
erreurLumieres = lumieres.mettreAJour()
erreurVolets = volets.mettreAJour()
if erreurThermostat or erreurLumieres or erreurVolets:
etat.signalerProbleme()
else:
etat.signalerOk()
time.sleep(0.2)
except KeyboardInterrupt:
print("\nArrêt du programme.")
finally:
thermostat.cleanup()
lumieres.cleanup()
volets.cleanup()
etat.cleanup()

View File

@@ -0,0 +1,49 @@
import RPi.GPIO as GPIO
import time as t
from septsegments import afficher_temperature
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
bouton_up = 23
bouton_down = 24
GPIO.setup(bouton_up, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(bouton_down, GPIO.IN, pull_up_down=GPIO.PUD_UP)
def test_boutons():
temperature = 18
etatPrecedent_up = GPIO.input(bouton_up)
etatPrecedent_down = GPIO.input(bouton_down)
print("Test lancé ! Appuie sur UP (23) pour monter, DOWN (24) pour descendre.")
while True:
etat_up = GPIO.input(bouton_up)
etat_down = GPIO.input(bouton_down)
if etat_up != etatPrecedent_up:
if etat_up == 0:
print("Bouton UP Appuyé ⬆️")
temperature += 1
if temperature >= 40:
temperature = 40
afficher_temperature(21,temperature)
etatPrecedent_up = etat_up
if etat_down != etatPrecedent_down:
if etat_down == 0:
print("Bouton DOWN Appuyé ⬇️")
temperature -= 1
if temperature <= 0:
temperature = 0
afficher_temperature(21,temperature)
etatPrecedent_down = etat_down
t.sleep(0.05)
if __name__ == "__main__":
try:
test_boutons()
except KeyboardInterrupt:
print("\nFin du test")
GPIO.cleanup()

View File

@@ -0,0 +1,25 @@
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
class EtatSysteme:
def __init__(self):
self.pinLedRouge = 19
self.pinLedVerte = 26
GPIO.setup(self.pinLedRouge, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(self.pinLedVerte, GPIO.OUT, initial=GPIO.LOW)
def signalerOk(self):
GPIO.output(self.pinLedVerte, GPIO.HIGH)
GPIO.output(self.pinLedRouge, GPIO.LOW)
def signalerProbleme(self):
GPIO.output(self.pinLedVerte, GPIO.LOW)
GPIO.output(self.pinLedRouge, GPIO.HIGH)
def cleanup(self):
GPIO.output(self.pinLedRouge, GPIO.LOW)
GPIO.output(self.pinLedVerte, GPIO.LOW)

View File

@@ -0,0 +1,87 @@
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
class SystemeLumieres:
def __init__(self):
# la pin de la 2e photorésistance manque sur le schéma
# donc ici on met une valeur temporaire
# elle apparaîtra peut-être un jour, comme la motivation en fin de projet
self.pinPhotoInterieure = 29
self.led1 = 6
self.led2 = 9
self.led3 = 13
self.boutonManuel = 36
self.modeManuel = False
self.lumieresAllumees = False
GPIO.setup(self.pinPhotoInterieure, GPIO.IN)
GPIO.setup(self.led1, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(self.led2, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(self.led3, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(self.boutonManuel, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
self.derniereLectureBouton = 0
self.delaiLectureBouton = 0.25
def lireLuminositeInterieure(self):
return GPIO.input(self.pinPhotoInterieure)
def allumerLumieres(self):
GPIO.output(self.led1, GPIO.HIGH)
GPIO.output(self.led2, GPIO.HIGH)
GPIO.output(self.led3, GPIO.HIGH)
self.lumieresAllumees = True
def eteindreLumieres(self):
GPIO.output(self.led1, GPIO.LOW)
GPIO.output(self.led2, GPIO.LOW)
GPIO.output(self.led3, GPIO.LOW)
self.lumieresAllumees = False
def gererBoutonManuel(self):
maintenant = time.time()
if maintenant - self.derniereLectureBouton < self.delaiLectureBouton:
return
if GPIO.input(self.boutonManuel):
self.modeManuel = not self.modeManuel
self.derniereLectureBouton = maintenant
if self.modeManuel:
self.lumieresAllumees = not self.lumieresAllumees
if self.lumieresAllumees:
self.allumerLumieres()
else:
self.eteindreLumieres()
else:
print("Lumières : retour en auto")
def mettreAJour(self):
self.gererBoutonManuel()
if self.modeManuel:
return False
luminosite = self.lireLuminositeInterieure()
if luminosite == 0:
self.allumerLumieres()
print("Lumières : on allume")
else:
self.eteindreLumieres()
print("Lumières : on coupe")
return False
def cleanup(self):
self.eteindreLumieres()

View File

@@ -0,0 +1,95 @@
import time
import threading
import RPi.GPIO as GPIO
from mfrc522 import SimpleMFRC522
import requests
import urllib3
# On cache le gros texte d'avertissement orange (InsecureRequestWarning)
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
class SystemePorteRFID:
def __init__(self):
"""
Initialise le système local d'accès par RFID.
Gère le lecteur RFID et la LED de la porte.
L'authentification est maintenant gérée par le serveur Flask et MariaDB.
"""
self.pinLed = 40
GPIO.setup(self.pinLed, GPIO.OUT, initial=GPIO.LOW)
self.lecteur = SimpleMFRC522()
self.badgeDetecte = None
self.derniereOuverture = 0
self.delaiEntreScans = 2
# Ce thread sert à ne pas bloquer la boucle principale
self.threadLecture = threading.Thread(target=self.boucleLectureRFID, daemon=True)
self.threadLecture.start()
def boucleLectureRFID(self):
"""
Boucle secondaire qui attend les badges RFID.
Utilise read_id() au lieu de read() pour éviter les erreurs "AUTH ERROR"
sur la mémoire interne des badges.
"""
while True:
try:
badgeId = self.lecteur.read_id()
self.badgeDetecte = badgeId
except Exception as erreur:
print("Erreur RFID :", erreur)
time.sleep(1)
def ouvrirPorte(self):
"""Simule l'ouverture de la porte avec la LED pendant 2 secondes."""
print("Porte ouverte.")
GPIO.output(self.pinLed, GPIO.HIGH)
time.sleep(2)
GPIO.output(self.pinLed, GPIO.LOW)
def traiterBadge(self, badgeId):
"""Envoie le numéro du badge à Flask pour vérification dans MariaDB."""
print(f"Badge détecté : {badgeId}")
try:
# Vérifie bien que l'URL correspond à ta route Flask (avec ou sans /api)
url = "https://127.0.0.1/rfid-scan"
donnees = {"badge_id": str(badgeId)}
# verify=False est nécessaire car le serveur local utilise un certificat auto-signé
reponse = requests.post(url, json=donnees, timeout=2, verify=False)
data = reponse.json()
if data.get("success") is True:
nom_utilisateur = data.get("username")
print(f"Accès autorisé par la base de données pour : {nom_utilisateur}")
self.ouvrirPorte()
else:
print("Accès refusé : ce badge n'est assigné à personne dans la base de données.")
except Exception as e:
print("Erreur de communication avec Flask :", e)
def mettreAJour(self):
"""Fonction appelée en boucle dans le programme principal."""
if self.badgeDetecte is None:
return
if time.time() - self.derniereOuverture < self.delaiEntreScans:
return
badgeId = self.badgeDetecte
self.badgeDetecte = None
self.derniereOuverture = time.time()
self.traiterBadge(badgeId)
def cleanup(self):
"""Eteint la LED de porte lors de la fermeture du programme."""
GPIO.output(self.pinLed, GPIO.LOW)

View File

@@ -0,0 +1,17 @@
import tm1637
import time as t
display = tm1637.TM1637(clk=4, dio=17)
display.brightness(2)
def afficher_temperature(temperature, temperature_moyenne):
print(f"Test affichage: Cible {temperature} | Moyenne {temperature_moyenne}")
try:
temp1 = int(temperature)
temp2 = int(temperature_moyenne)
texte_ecran = f"{temp1:02d}{temp2:02d}"
display.show(texte_ecran)
except Exception as e:
print(f"Erreur d'affichage : {e}")

View File

@@ -0,0 +1,76 @@
import time
import RPi.GPIO as GPIO
import Adafruit_DHT
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
class SystemeThermostat:
def __init__(self):
self.capteur = Adafruit_DHT.DHT11
self.pinDht = 25
self.boutonPlus = 16
self.boutonMoins = 18
# display 4 digits
# à brancher proprement quand le module exact sera fixé
self.pinDisplayClk = 7
self.pinDisplayDio = 11
self.temperatureCible = 18
self.temperatureReelle = None
self.derniereLectureBouton = 0
self.delaiLectureBouton = 0.25
GPIO.setup(self.boutonPlus, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(self.boutonMoins, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
def lireTemperature(self):
humidite, temperature = Adafruit_DHT.read_retry(self.capteur, self.pinDht)
if temperature is None:
print("Thermostat : lecture DHT11 impossible")
return None
return temperature
def lireBoutons(self):
maintenant = time.time()
if maintenant - self.derniereLectureBouton < self.delaiLectureBouton:
return
if GPIO.input(self.boutonPlus):
self.temperatureCible += 1
self.derniereLectureBouton = maintenant
print("Consigne :", self.temperatureCible, "°C")
elif GPIO.input(self.boutonMoins):
self.temperatureCible -= 1
self.derniereLectureBouton = maintenant
print("Consigne :", self.temperatureCible, "°C")
def afficherTemperatures(self):
# pour l'instant on affiche dans la console
# le vrai code du display ira ici
if self.temperatureReelle is None:
print("Temp réelle : -- | cible :", self.temperatureCible)
else:
print("Temp réelle :", str(self.temperatureReelle) + "°C", "| cible :", str(self.temperatureCible) + "°C")
def mettreAJour(self):
self.lireBoutons()
self.temperatureReelle = self.lireTemperature()
self.afficherTemperatures()
if self.temperatureReelle is None:
return True
return False
def cleanup(self):
# rien à éteindre ici, incroyable mais vrai
pass

View File

@@ -0,0 +1,73 @@
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
class SystemeVolets:
def __init__(self):
self.pinPhotoExterieure = 32
self.pinServo = 12
self.boutonManuel = 13
self.modeManuel = False
self.voletsOuverts = True
GPIO.setup(self.pinPhotoExterieure, GPIO.IN)
GPIO.setup(self.pinServo, GPIO.OUT)
GPIO.setup(self.boutonManuel, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
self.pwm = GPIO.PWM(self.pinServo, 50)
self.pwm.start(0)
self.derniereLectureBouton = 0
self.delaiLectureBouton = 0.25
def ouvrirVolets(self):
self.pwm.ChangeDutyCycle(7)
self.voletsOuverts = True
print("Volets : ouverts")
def fermerVolets(self):
self.pwm.ChangeDutyCycle(2)
self.voletsOuverts = False
print("Volets : fermés")
def gererBoutonManuel(self):
maintenant = time.time()
if maintenant - self.derniereLectureBouton < self.delaiLectureBouton:
return
if GPIO.input(self.boutonManuel):
self.derniereLectureBouton = maintenant
if self.voletsOuverts:
self.fermerVolets()
else:
self.ouvrirVolets()
self.modeManuel = True
print("Volets : mode manuel")
def lireLuminositeExterieure(self):
return GPIO.input(self.pinPhotoExterieure)
def mettreAJour(self):
self.gererBoutonManuel()
if self.modeManuel:
return False
luminosite = self.lireLuminositeExterieure()
if luminosite == 1:
self.fermerVolets()
else:
self.ouvrirVolets()
return False
def cleanup(self):
self.pwm.stop()

15
composants/test/PIR.py Normal file
View File

@@ -0,0 +1,15 @@
import RPi.GPIO as GPIO
import time as t
GPIO.setmode(GPIO.BOARD)
pir = 10
GPIO.setup(pir, GPIO.IN)
print("Stabilisation...")
t.sleep(10)
print("Stabilisation terminée")
while True:
print("PIR :", GPIO.input(pir))
t.sleep(0.5)

View File

@@ -0,0 +1,36 @@
import RPi.GPIO as GPIO
import time as t
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
led1 = 9
led2 = 6
led3 = 13 # example BCM pin
GPIO.setup(led1, GPIO.OUT)
GPIO.setup(led2, GPIO.OUT)
GPIO.setup(led3, GPIO.OUT)
print("Test LEDs...")
try:
while True:
GPIO.output(led1, GPIO.HIGH)
GPIO.output(led2, GPIO.HIGH)
GPIO.output(led3, GPIO.HIGH)
print("LED ON")
t.sleep(1)
GPIO.output(led1, GPIO.LOW)
GPIO.output(led2, GPIO.LOW)
GPIO.output(led3, GPIO.LOW)
print("LED OFF")
t.sleep(1)
except KeyboardInterrupt:
print("Stop")
finally:
GPIO.cleanup()

15
composants/test/ledRGB.py Normal file
View File

@@ -0,0 +1,15 @@
import RPi.GPIO as GPIO
import time as t
GPIO.setmode(GPIO.BOARD)
r, g, b = 11, 13, 15
GPIO.setup(r, GPIO.OUT)
GPIO.setup(g, GPIO.OUT)
GPIO.setup(b, GPIO.OUT)
while True:
GPIO.output(r, 1); t.sleep(1); GPIO.output(r, 0)
GPIO.output(g, 1); t.sleep(1); GPIO.output(g, 0)
GPIO.output(b, 1); t.sleep(1); GPIO.output(b, 0)

15
composants/test/rfid.py Normal file
View File

@@ -0,0 +1,15 @@
from mfrc522 import SimpleMFRC522 as RFIDReader
reader = RFIDReader()
print("En attente...")
try:
while True:
badgeId, text = reader.read()
print("ID :", badgeId)
print("Texte :", text)
print("-----")
except KeyboardInterrupt:
print("Stop")

19
composants/test/servo.py Normal file
View File

@@ -0,0 +1,19 @@
import RPi.GPIO as GPIO
import time as t
GPIO.setmode(GPIO.BOARD)
servo = 12
GPIO.setup(servo, GPIO.OUT)
pwm = GPIO.PWM(servo, 50)
pwm.start(0)
while True:
print("Position 1")
pwm.ChangeDutyCycle(2)
t.sleep(2)
print("Position 2")
pwm.ChangeDutyCycle(7)
t.sleep(2)

103
fastapi/README.md Normal file
View File

@@ -0,0 +1,103 @@
# Serveur FastAPI
## Description
Ce serveur **FastAPI** est destiné à être déployé sur le **deuxième Raspberry Pi** de larchitecture.
Son rôle principal est de **gérer et traiter toutes les requêtes envoyées par le Raspberry Pi 1**, afin de centraliser la logique de traitement et dassurer une communication fluide entre les deux.
---
## Architecture
* **Raspberry Pi 1**
* Envoie les requêtes (HTTP/API)
* Sert de client / déclencheur
* **Raspberry Pi 2 (ce serveur)**
* Héberge le serveur FastAPI
* Reçoit, traite et répond aux requêtes
* Exécute la logique métier
---
## Installation
Pour garantir une installation propre et optimale, il est recommandé dutiliser le script fourni.
### 1. Cloner le projet
```bash
git clone <repo_url>
cd <repo>
```
### 2. Lancer linstallation automatique
Le script `main.sh` permet de :
* créer un environnement virtuel Python (`venv`)
* installer toutes les dépendances nécessaires
* configurer lenvironnement correctement
```bash
chmod +x main.sh
./main.sh
```
---
## Environnement virtuel
Le projet utilise **Python venv** pour isoler les dépendances.
Si besoin, activation manuelle :
```bash
source venv/bin/activate
```
---
## Dépendances
Les dépendances sont listées dans le fichier :
```
requirements.txt
```
Elles sont automatiquement installées via le script `main.sh`.
---
## Lancement du serveur
Une fois linstallation terminée, le serveur peut être lancé avec :
```
python main
```
---
## Objectif
Ce serveur a pour objectif de :
* centraliser le traitement des requêtes
* améliorer les performances globales du système
* permettre une architecture distribuée entre plusieurs Raspberry Pi
---
## Notes
* Assurez-vous que les deux Raspberry Pi sont sur le même réseau.
* Vérifiez les ports et adresses IP pour permettre la communication entre les deux machines.
* Adapter la configuration si nécessaire selon votre environnement.
---

68
fastapi/main.py Normal file
View File

@@ -0,0 +1,68 @@
import os
import sys
from fastapi import FastAPI
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
composants = os.path.join(BASE_DIR, "composants", "byPanda")
sys.path.insert(0, composants)
from lumieres import SystemeLumieres
from thermostat import SystemeThermostat
#from volets import SystemeVolets
from etatsystemes import EtatSysteme
from septsegments import afficher_temperature
app = FastAPI(title="Loustiques API - Pi 2")
controleur_lumieres = SystemeLumieres()
controleur_thermostat = SystemeThermostat()
#controleur_volet = SystemeVolets()
etatSysteme = EtatSysteme()
@app.get("/up_led")
async def allumer_led():
try:
controleur_lumieres.allumerLumieres()
controleur_lumieres.modeManuel = True
etatSysteme.signalerOk()
return {"success": True, "message": "Lumière allumée par le Pi 2"}
except Exception as e:
etatSysteme.signalerProbleme()
return {"success": False, "message": str(e)}
@app.get("/down_led")
async def eteindre_led():
try:
controleur_lumieres.eteindreLumieres()
controleur_lumieres.modeManuel = True
etatSysteme.signalerOk()
return {"success": True, "message": "Lumière éteinte par le Pi 2"}
except Exception as e:
etatSysteme.signalerProbleme()
return {"success": False, "message": str(e)}
@app.get("/temperature")
async def read_temp():
try:
temp = controleur_thermostat.lireTemperature()
if temp is None:
etatSysteme.signalerProbleme()
return {"success": False, "message": "Impossible de lire le capteur DHT11"}
etatSysteme.signalerOk()
afficher_temperature(temp)
return {"success": True, "temperature": temp}
except Exception as e:
etatSysteme.signalerProbleme()
return {"success": False, "message": str(e)}
if __name__ == "__main__":
import uvicorn
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)

3
fastapi/requirement.txt Normal file
View File

@@ -0,0 +1,3 @@
fastapi
uvicorn
rpi.gpio

6
flask/.env Normal file
View File

@@ -0,0 +1,6 @@
DB_HOST=127.0.0.1
DB_PORT=3306
DB_USER=python
DB_PASSWORD=wolaouais
DB_NAME=Utilisateurs
DB_CHARSET=utf8mb4

View File

@@ -48,7 +48,32 @@ def login(username, password):
finally: finally:
cursor.close() cursor.close()
conn.close() conn.close()
def get_user_by_rfid(RFID):
conn = init()
if conn is None:
return None
try:
cursor = conn.cursor()
requete = "SELECT username FROM Auth WHERE RFID = %s"
cursor.execute(requete, (RFID))
resultat = cursor.fetchone()
if resultat:
username = resultat[0]
log.info(f"Badge RFID reconnu pour l'utilisateur : {username}")
return username
else:
log.info(f"Tentative RFID refusée : badge {RFID} inconnu.")
return None
except pymysql.err.OperationalError as e:
print(f"Erreur SQL RFID : {e}")
log.error(f"Erreur SQL RFID : {e}")
return None
finally:
if conn:
cursor.close()
conn.close()
def get_users(): def get_users():
conn = init() conn = init()

View File

@@ -2,6 +2,8 @@ from flask import Flask, render_template, request, jsonify
from flask_talisman import Talisman from flask_talisman import Talisman
from led import led from led import led
import os import os
import sys
import log
from add_user import add_user from add_user import add_user
import auth import auth
import re import re
@@ -11,6 +13,13 @@ Talisman(app, force_https=True,
content_security_policy=False ) content_security_policy=False )
current_user = None current_user = None
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
composants = os.path.join(BASE_DIR, "composants", "byPanda")
sys.path.insert(0, composants)
from alarme import SystemeAlarme
from lumiere import SystemeLumieres
from board1main import *
@app.route("/") @app.route("/")
def index(): def index():
return render_template("index.html") return render_template("index.html")
@@ -32,8 +41,37 @@ def dashboard():
@app.route("/led", methods=["POST"]) @app.route("/led", methods=["POST"])
def call_led(): def call_led():
led(current_user) etat = SystemeLumieres.mettreAJourEtat()
if (etat == 0):
SystemeLumieres.allumerLumieres
else:
SystemeLumieres.eteindreLumieres()
return jsonify({"success": True}) return jsonify({"success": True})
@app.route("/rfid-scan", methods=["POST"])
def rfid_scan():
global dernier_badge_scanne
data = request.get_json()
badge_id = str(data.get("badge_id"))
username = auth.get_user_by_rfid(badge_id)
if username:
dernier_badge_scanne = username
return jsonify({"success": True, "username": username})
else:
# Badge inconnu dans la BDD
return jsonify({"success": False})
@app.route("/alarme",methods=["POST"])
def armer_alarme():
SystemeAlarme.armer()
return jsonify({"success": True})
@app.route("/admin") @app.route("/admin")
def admin_page(): def admin_page():
@@ -69,11 +107,11 @@ def get_users():
users = auth.get_users() users = auth.get_users()
return jsonify({"success": True, "users": users}) return jsonify({"success": True, "users": users})
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if __name__ == "__main__": if __name__ == "__main__":
print("[*] Démarrage du lecteur RFID et de l'alarme en arrière-plan...")
thread_hardware = threading.Thread(target=call_board1, daemon=True)
thread_hardware.start()
app.run( app.run(
host="0.0.0.0", host="0.0.0.0",
port=443, port=443,

View File

@@ -3,33 +3,14 @@
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Admin — Loustiques</title> <title>Loustiques Home - Admin</title>
<link href="https://fonts.googleapis.com/css2?family=Space+Mono:wght@400;700&family=DM+Sans:wght@300;400;500&display=swap" rel="stylesheet">
<style> <style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; } *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
:root {
--bg: #0f0f0f;
--surface: #181818;
--surface2: #222222;
--border: rgba(255,255,255,0.08);
--border-hover: rgba(255,255,255,0.18);
--text: #f0ede8;
--muted: #888880;
--accent: #c8f060;
--accent-dim: rgba(200,240,96,0.12);
--danger: #ff5f57;
--danger-dim: rgba(255,95,87,0.12);
--success: #30d158;
--success-dim: rgba(48,209,88,0.1);
--mono: 'Space Mono', monospace;
--sans: 'DM Sans', sans-serif;
}
body { body {
background: var(--bg); font-family: system-ui, sans-serif;
color: var(--text); background: #1f1f1f;
font-family: var(--sans); color: #f0f0f0;
min-height: 100vh; min-height: 100vh;
display: flex; display: flex;
} }
@@ -37,8 +18,8 @@
aside { aside {
width: 220px; width: 220px;
min-height: 100vh; min-height: 100vh;
background: var(--surface); background: #1a1a1a;
border-right: 1px solid var(--border); border-right: 1px solid #2e2e2e;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
padding: 2rem 1.25rem; padding: 2rem 1.25rem;
@@ -47,22 +28,20 @@
} }
.logo { .logo {
font-family: var(--mono); font-size: 20px;
font-size: 13px; font-weight: 700;
color: var(--accent); color: #f0f0f0;
letter-spacing: 0.12em;
text-transform: uppercase;
margin-bottom: 2.5rem; margin-bottom: 2.5rem;
padding-bottom: 1.5rem; padding-bottom: 1.5rem;
border-bottom: 1px solid var(--border); border-bottom: 1px solid #2e2e2e;
} }
.logo span { .logo span {
display: block; display: block;
font-size: 10px; font-size: 15px;
color: var(--muted); color: #666;
margin-top: 4px; margin-top: 4px;
letter-spacing: 0.06em; font-weight: 400;
} }
nav a { nav a {
@@ -71,27 +50,26 @@
gap: 10px; gap: 10px;
padding: 8px 10px; padding: 8px 10px;
border-radius: 6px; border-radius: 6px;
font-size: 13.5px; font-size: 13px;
color: var(--muted); color: #888;
text-decoration: none; text-decoration: none;
margin-bottom: 2px; margin-bottom: 2px;
transition: all 0.15s; transition: all 0.15s;
} }
nav a.active, nav a:hover { nav a.active, nav a:hover {
background: var(--accent-dim); background: #2e2e3a;
color: var(--accent); color: #2563eb;
} }
nav a svg { width: 15px; height: 15px; flex-shrink: 0; } nav a svg { width: 15px; height: 15px; flex-shrink: 0; }
.sidebar-footer { .sidebar-footer {
margin-top: auto; margin-top: auto;
font-size: 12px; font-size: 15px;
color: var(--muted); color: #555;
font-family: var(--mono);
padding-top: 1rem; padding-top: 1rem;
border-top: 1px solid var(--border); border-top: 1px solid #2e2e2e;
} }
main { main {
@@ -104,34 +82,29 @@
.page-header { .page-header {
margin-bottom: 2.5rem; margin-bottom: 2.5rem;
} }
.page-header h1 { .page-header h1 {
font-family: var(--mono);
font-size: 22px; font-size: 22px;
font-weight: 700; font-weight: 700;
color: var(--text);
margin-bottom: 4px; margin-bottom: 4px;
} }
.page-header p { .page-header p {
font-size: 14px; font-size: 14px;
color: var(--muted); color: #888;
} }
.card { .card {
background: var(--surface); background: #2a2a2a;
border: 1px solid var(--border); border: 1px solid #333;
border-radius: 12px; border-radius: 8px;
padding: 1.75rem; padding: 1.75rem;
margin-bottom: 1.5rem; margin-bottom: 1.5rem;
} }
.card-title { .card-title {
font-family: var(--mono); font-size: 15px;
font-size: 11px;
letter-spacing: 0.1em; letter-spacing: 0.1em;
text-transform: uppercase; text-transform: uppercase;
color: var(--muted); color: #666;
margin-bottom: 1.25rem; margin-bottom: 1.25rem;
} }
@@ -146,169 +119,117 @@
flex-direction: column; flex-direction: column;
gap: 6px; gap: 6px;
} }
.form-group.full {
.form-group.full { grid-column: 1 / -1; } grid-column: 1 / -1;
}
label { label {
font-size: 12px; font-size: 12px;
color: var(--muted); color: #888;
font-family: var(--mono);
letter-spacing: 0.05em;
} }
input[type="text"], input[type="text"],
input[type="password"] { input[type="password"],
background: var(--surface2); select {
border: 1px solid var(--border); background: #333;
border-radius: 7px; border: 1px solid #3a3a3a;
border-radius: 6px;
padding: 10px 14px; padding: 10px 14px;
color: var(--text); color: #f0f0f0;
font-family: var(--mono); font-family: inherit;
font-size: 13px; font-size: 13px;
outline: none; outline: none;
transition: border-color 0.15s;
width: 100%; width: 100%;
transition: border-color 0.15s;
appearance: none;
} }
input:focus { input:focus, select:focus { border-color: #2563eb; }
border-color: var(--accent); input::placeholder { color: #555; }
}
.btn { .btn {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
gap: 8px; gap: 8px;
padding: 10px 20px; padding: 9px 18px;
border-radius: 7px; border-radius: 6px;
border: none; border: none;
font-family: var(--mono); font-family: inherit;
font-size: 12px; font-size: 13px;
letter-spacing: 0.05em;
cursor: pointer; cursor: pointer;
transition: all 0.15s; transition: all 0.15s;
} }
.btn-primary { .btn-primary { background: #2563eb; color: #fff; font-weight: 600; }
background: var(--accent); .btn-primary:hover { background: #1d4ed8; }
color: #0f0f0f;
font-weight: 700;
}
.btn-primary:hover { background: #d4f570; }
.btn-danger { .btn-danger {
background: var(--danger-dim); background: transparent;
color: var(--danger); color: #f87171;
border: 1px solid rgba(255,95,87,0.2); border: 1px solid rgba(248,113,113,0.3);
font-size: 12px;
padding: 6px 14px;
} }
.btn-danger:hover { background: rgba(248,113,113,0.1); }
.btn-danger:hover { background: rgba(255,95,87,0.2); } .form-actions { display: flex; justify-content: flex-end; margin-top: 1.25rem; }
.form-actions { .user-list { display: flex; flex-direction: column; }
display: flex;
justify-content: flex-end;
margin-top: 1.25rem;
}
.user-list { display: flex; flex-direction: column; gap: 0; }
.user-row { .user-row {
display: flex; display: flex;
align-items: center; align-items: center;
padding: 12px 0; padding: 12px 0;
border-bottom: 1px solid var(--border); border-bottom: 1px solid #333;
gap: 14px; gap: 14px;
transition: background 0.1s;
} }
.user-row:last-child { border-bottom: none; } .user-row:last-child { border-bottom: none; }
.avatar { .avatar {
width: 36px; width: 36px; height: 36px;
height: 36px;
border-radius: 50%; border-radius: 50%;
background: var(--accent-dim); background: #2e2e3a;
border: 1px solid rgba(200,240,96,0.2); border: 1px solid #3a3a4a;
display: flex; display: flex; align-items: center; justify-content: center;
align-items: center; font-size: 11px; font-weight: 600;
justify-content: center; color: #2563eb;
font-family: var(--mono);
font-size: 11px;
color: var(--accent);
flex-shrink: 0; flex-shrink: 0;
} }
.user-info { flex: 1; } .user-info { flex: 1; }
.user-name { font-size: 14px; font-weight: 500; margin-bottom: 2px; }
.user-name { .user-meta { font-size: 11px; color: #666; }
font-size: 14px;
font-weight: 500;
color: var(--text);
margin-bottom: 2px;
}
.user-meta {
font-size: 11px;
color: var(--muted);
font-family: var(--mono);
}
.badge { .badge {
font-size: 10px; font-size: 10px;
font-family: var(--mono);
padding: 3px 8px; padding: 3px 8px;
border-radius: 4px; border-radius: 4px;
letter-spacing: 0.05em;
} }
.badge-admin { .badge-admin { background: rgba(37,99,235,0.15); color: #2563eb; border: 1px solid rgba(37,99,235,0.3); }
background: var(--accent-dim); .badge-user { background: #333; color: #888; border: 1px solid #3a3a3a; }
color: var(--accent);
border: 1px solid rgba(200,240,96,0.2);
}
.badge-user {
background: var(--surface2);
color: var(--muted);
border: 1px solid var(--border);
}
.toast { .toast {
position: fixed; position: fixed;
bottom: 2rem; bottom: 2rem; right: 2rem;
right: 2rem; background: #2a2a2a;
background: var(--surface); border: 1px solid #333;
border: 1px solid var(--border);
border-radius: 8px; border-radius: 8px;
padding: 12px 18px; padding: 12px 18px;
font-size: 13px; font-size: 13px;
font-family: var(--mono); color: #f0f0f0;
color: var(--text);
transform: translateY(20px); transform: translateY(20px);
opacity: 0; opacity: 0;
transition: all 0.25s; transition: all 0.25s;
pointer-events: none; pointer-events: none;
z-index: 999; z-index: 999;
} }
.toast.show { transform: translateY(0); opacity: 1; } .toast.show { transform: translateY(0); opacity: 1; }
.toast.success { border-color: rgba(48,209,88,0.3); color: var(--success); } .toast.success { border-color: rgba(74,222,128,0.3); color: #4ade80; }
.toast.error { border-color: rgba(255,95,87,0.3); color: var(--danger); } .toast.error { border-color: rgba(248,113,113,0.3); color: #f87171; }
.strength-bar { .strength-bar { height: 3px; background: #333; border-radius: 2px; margin-top: 6px; overflow: hidden; }
height: 3px; .strength-fill { height: 100%; border-radius: 2px; transition: width 0.3s, background 0.3s; width: 0%; }
background: var(--surface2);
border-radius: 2px;
margin-top: 6px;
overflow: hidden;
}
.strength-fill {
height: 100%;
border-radius: 2px;
transition: width 0.3s, background 0.3s;
width: 0%;
}
</style> </style>
</head> </head>
<body> <body>
@@ -316,7 +237,7 @@
<aside> <aside>
<div class="logo"> <div class="logo">
Loustiques Loustiques
<span>panneau admin</span> <span>Panneau admin</span>
</div> </div>
<nav> <nav>
<a href="#" class="active"> <a href="#" class="active">
@@ -332,14 +253,12 @@
Système Système
</a> </a>
</nav> </nav>
<div class="sidebar-footer"> <div class="sidebar-footer">v0.1.0 — local</div>
v0.1.0 — local
</div>
</aside> </aside>
<main> <main>
<div class="page-header"> <div class="page-header">
<h1>utilisateurs</h1> <h1>Utilisateurs</h1>
<p>Créer et gérer les comptes d'accès.</p> <p>Créer et gérer les comptes d'accès.</p>
</div> </div>
@@ -347,23 +266,23 @@
<div class="card-title">Créer un utilisateur</div> <div class="card-title">Créer un utilisateur</div>
<div class="form-grid"> <div class="form-grid">
<div class="form-group"> <div class="form-group">
<label>nom d'utilisateur</label> <label>Nom d'utilisateur</label>
<input type="text" id="new-username" placeholder="ex: maxime" autocomplete="off"> <input type="text" id="new-username" placeholder="ex: maxime" autocomplete="off">
</div> </div>
<div class="form-group"> <div class="form-group">
<label>rôle</label> <label>Rôle</label>
<select id="new-role" style="background:var(--surface2);border:1px solid var(--border);border-radius:7px;padding:10px 14px;color:var(--text);font-family:var(--mono);font-size:13px;outline:none;width:100%;appearance:none;"> <select id="new-role">
<option value="user">user</option> <option value="user">user</option>
<option value="admin">admin</option> <option value="admin">admin</option>
</select> </select>
</div> </div>
<div class="form-group"> <div class="form-group">
<label>mot de passe</label> <label>Mot de passe</label>
<input type="password" id="new-password" placeholder="••••••••" oninput="checkStrength(this.value)"> <input type="password" id="new-password" placeholder="••••••••" oninput="checkStrength(this.value)">
<div class="strength-bar"><div class="strength-fill" id="strength-fill"></div></div> <div class="strength-bar"><div class="strength-fill" id="strength-fill"></div></div>
</div> </div>
<div class="form-group"> <div class="form-group">
<label>confirmer</label> <label>Confirmer</label>
<input type="password" id="confirm-password" placeholder="••••••••"> <input type="password" id="confirm-password" placeholder="••••••••">
</div> </div>
</div> </div>
@@ -377,17 +296,7 @@
<div class="card"> <div class="card">
<div class="card-title">Comptes existants</div> <div class="card-title">Comptes existants</div>
<div class="user-list" id="user-list"> <div class="user-list" id="user-list"></div>
<div class="user-row">
<div class="avatar">MA</div>
<div class="user-info">
<div class="user-name">maxime</div>
<div class="user-meta">créé le 24/03/2026</div>
</div>
<span class="badge badge-admin">admin</span>
<button class="btn btn-danger" onclick="deleteUser(this, 'maxime')">Supprimer</button>
</div>
</div>
</div> </div>
</main> </main>
@@ -408,7 +317,7 @@ function checkStrength(val) {
if (/[A-Z]/.test(val)) score++; if (/[A-Z]/.test(val)) score++;
if (/[0-9]/.test(val)) score++; if (/[0-9]/.test(val)) score++;
if (/[^A-Za-z0-9]/.test(val)) score++; if (/[^A-Za-z0-9]/.test(val)) score++;
const colors = ['#ff5f57', '#ff9f0a', '#ffd60a', '#30d158']; const colors = ['#f87171', '#fb923c', '#facc15', '#4ade80'];
fill.style.width = (score * 25) + '%'; fill.style.width = (score * 25) + '%';
fill.style.background = colors[score - 1] || 'transparent'; fill.style.background = colors[score - 1] || 'transparent';
} }
@@ -443,6 +352,7 @@ function createUser() {
}) })
.catch(() => showToast('Erreur réseau', 'error')); .catch(() => showToast('Erreur réseau', 'error'));
} }
function loadUsers() { function loadUsers() {
fetch('/admin/get_users') fetch('/admin/get_users')
.then(r => r.json()) .then(r => r.json())
@@ -455,6 +365,7 @@ function loadUsers() {
} }
loadUsers(); loadUsers();
function addUserRow(username, role) { function addUserRow(username, role) {
const initials = username.slice(0, 2).toUpperCase(); const initials = username.slice(0, 2).toUpperCase();
const today = new Date().toLocaleDateString('fr-FR'); const today = new Date().toLocaleDateString('fr-FR');

View File

@@ -3,208 +3,214 @@
<head> <head>
<meta charset="UTF-8"/> <meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/> <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Loustique Home — Dashboard</title> <title>Loustiques Home — Dashboard</title>
<link href="https://fonts.googleapis.com/css2?family=Syne:wght@400;700;800&family=DM+Mono:wght@300;400&display=swap" rel="stylesheet"/>
<style> <style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; } *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
:root {
--bg: #0a0a0f;
--panel: #111118;
--border: #1e1e2e;
--accent: #7c6aff;
--accent2: #ff6ab0;
--text: #e8e6f0;
--muted: #6b6880;
--success: #4ade80;
--warning: #fbbf24;
}
body { body {
font-family: 'DM Mono', monospace; font-family: system-ui, sans-serif;
background: var(--bg); background: #1f1f1f;
color: var(--text); color: #f0f0f0;
min-height: 100vh; min-height: 100vh;
overflow-x: hidden;
} }
/* Grid background */
body::before {
content: '';
position: fixed;
inset: 0;
background-image:
linear-gradient(rgba(124,106,255,0.03) 1px, transparent 1px),
linear-gradient(90deg, rgba(124,106,255,0.03) 1px, transparent 1px);
background-size: 40px 40px;
pointer-events: none;
z-index: 0;
}
.orb { position: fixed; border-radius: 50%; filter: blur(100px); opacity: 0.08; pointer-events: none; z-index: 0; }
.orb1 { width: 600px; height: 600px; background: var(--accent); top: -200px; left: -200px; }
.orb2 { width: 400px; height: 400px; background: var(--accent2); bottom: -100px; right: -100px; }
/* ── TOPBAR ── */
header { header {
position: relative; z-index: 10; display: flex;
display: flex; align-items: center; justify-content: space-between; align-items: center;
padding: 20px 36px; justify-content: space-between;
border-bottom: 1px solid var(--border); padding: 18px 32px;
background: rgba(10,10,15,0.8); border-bottom: 1px solid #2e2e2e;
backdrop-filter: blur(12px); background: #1a1a1a;
animation: fadeDown 0.5s ease forwards;
} }
@keyframes fadeDown { from { opacity: 0; transform: translateY(-10px); } to { opacity: 1; transform: translateY(0); } }
.logo { .logo {
font-family: 'Syne', sans-serif; font-size: 17px;
font-size: 18px; font-weight: 800; font-weight: 700;
letter-spacing: -0.02em;
} }
.logo span { background: linear-gradient(135deg, var(--accent), var(--accent2)); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text; }
.header-right { display: flex; align-items: center; gap: 20px; } .header-right {
display: flex;
align-items: center;
gap: 20px;
}
.status-dot { .status-dot {
display: flex; align-items: center; gap: 8px; display: flex;
font-size: 11px; color: var(--muted); letter-spacing: 0.05em; align-items: center;
gap: 8px;
font-size: 12px;
color: #888;
} }
.dot { width: 7px; height: 7px; border-radius: 50%; background: var(--success); box-shadow: 0 0 6px var(--success); animation: pulse 2s infinite; }
.dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: #4ade80;
animation: pulse 2s infinite;
}
@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.4; } } @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.4; } }
.logout { .logout {
font-family: 'DM Mono', monospace; font-family: inherit;
font-size: 11px; letter-spacing: 0.1em; text-transform: uppercase; font-size: 12px;
color: var(--muted); background: none; border: 1px solid var(--border); color: #888;
padding: 6px 14px; border-radius: 2px; cursor: pointer; background: none;
transition: color 0.2s, border-color 0.2s; border: 1px solid #3a3a3a;
padding: 6px 14px;
border-radius: 6px;
cursor: pointer;
transition: color 0.15s, border-color 0.15s;
} }
.logout:hover { color: var(--text); border-color: var(--muted); } .logout:hover { color: #f0f0f0; border-color: #666; }
/* ── MAIN ── */
main { main {
position: relative; z-index: 1; max-width: 1100px;
max-width: 1100px; margin: 0 auto; margin: 0 auto;
padding: 40px 36px; padding: 36px 32px;
} }
.welcome { .welcome {
margin-bottom: 40px; margin-bottom: 36px;
animation: fadeUp 0.5s 0.1s ease both; text-align: center;
} }
@keyframes fadeUp { from { opacity: 0; transform: translateY(16px); } to { opacity: 1; transform: translateY(0); } } .welcome .label {
font-size: 14px;
letter-spacing: 0.15em;
text-transform: uppercase;
color: #2563eb;
margin-bottom: 8px;
}
.welcome .label { font-size: 10px; letter-spacing: 0.2em; text-transform: uppercase; color: var(--accent); margin-bottom: 8px; } .welcome h1 {
.welcome h1 { font-family: 'Syne', sans-serif; font-size: 28px; font-weight: 800; letter-spacing: -0.02em; } font-size: 30px;
.welcome h1 span { background: linear-gradient(135deg, var(--accent), var(--accent2)); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text; } font-weight: 700;
}
/* ── GRID ── */
.grid { .grid {
display: grid; display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
gap: 16px; gap: 14px;
margin-bottom: 32px; margin-bottom: 32px;
} }
.card { .card {
background: var(--panel); background: #2a2a2a;
border: 1px solid var(--border); border: 1px solid #333;
border-radius: 2px; border-radius: 8px;
padding: 24px; padding: 22px;
position: relative; position: relative;
overflow: hidden;
animation: fadeUp 0.5s ease both;
} }
.card:nth-child(1) { animation-delay: 0.15s; } .card-label {
.card:nth-child(2) { animation-delay: 0.22s; } font-size: 11px;
.card:nth-child(3) { animation-delay: 0.29s; } letter-spacing: 0.1em;
.card:nth-child(4) { animation-delay: 0.36s; } text-transform: uppercase;
color: #888;
.card::before { margin-bottom: 10px;
content: '';
position: absolute; top: 0; left: 0; right: 0;
height: 1px;
background: linear-gradient(90deg, var(--accent), transparent);
} }
.card-label { font-size: 10px; letter-spacing: 0.15em; text-transform: uppercase; color: var(--muted); margin-bottom: 12px; } .card-value {
.card-value { font-family: 'Syne', sans-serif; font-size: 28px; font-weight: 800; letter-spacing: -0.02em; } font-size: 22px;
.card-sub { font-size: 11px; color: var(--muted); margin-top: 6px; } font-weight: 700;
}
.card-sub {
font-size: 12px;
color: #666;
margin-top: 6px;
}
.card-icon { .card-icon {
position: absolute; top: 20px; right: 20px; position: absolute;
width: 32px; height: 32px; opacity: 0.15; top: 20px;
right: 20px;
width: 28px;
height: 28px;
opacity: 0.15;
} }
/* ── ACTIONS ── */
.section-title { .section-title {
font-size: 10px; letter-spacing: 0.2em; text-transform: uppercase; font-size: 11px;
color: var(--muted); margin-bottom: 16px; letter-spacing: 0.15em;
display: flex; align-items: center; gap: 10px; text-transform: uppercase;
animation: fadeUp 0.5s 0.4s ease both; color: #666;
margin-bottom: 14px;
display: flex;
align-items: center;
gap: 10px;
} }
.section-title::after { content: ''; flex: 1; height: 1px; background: var(--border); } .section-title::after { content: ''; flex: 1; height: 1px; background: #2e2e2e; }
.actions { .actions {
display: grid; display: grid;
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
gap: 12px; gap: 12px;
animation: fadeUp 0.5s 0.45s ease both;
} }
.action-btn { .action-btn {
background: var(--panel); background: #2a2a2a;
border: 1px solid var(--border); border: 1px solid #333;
border-radius: 2px; border-radius: 8px;
padding: 18px 20px; padding: 18px 20px;
cursor: pointer; cursor: pointer;
text-align: left; text-align: left;
transition: border-color 0.2s, background 0.2s, transform 0.1s; color: #f0f0f0;
position: relative; overflow: hidden; position: relative;
color: var(--text); /* ← ajouter ça */ transition: border-color 0.15s, background 0.15s;
} }
.action-btn:hover { border-color: var(--accent); background: rgba(124,106,255,0.05); } .action-btn:hover { border-color: #2563eb; background: #2e2e3a; }
.action-btn:active { transform: scale(0.98); } .action-btn:active { transform: scale(0.98); }
.action-btn .a-label { .action-btn .a-label {
font-family: 'Syne', sans-serif; font-size: 14px;
font-size: 13px; font-weight: 700; font-weight: 600;
letter-spacing: 0.02em; display: block; margin-bottom: 4px; display: block;
margin-bottom: 4px;
}
.action-btn .a-sub {
font-size: 11px;
color: #888;
} }
.action-btn .a-sub { font-size: 10px; color: var(--muted); letter-spacing: 0.05em; }
.action-btn .a-arrow { .action-btn .a-arrow {
position: absolute; right: 16px; top: 50%; transform: translateY(-50%); position: absolute;
color: var(--muted); font-size: 16px; right: 16px;
transition: color 0.2s, right 0.2s; top: 50%;
transform: translateY(-50%);
color: #555;
font-size: 18px;
transition: color 0.15s, right 0.15s;
} }
.action-btn:hover .a-arrow { color: var(--accent); right: 12px; } .action-btn:hover .a-arrow { color: #2563eb; right: 12px; }
/* ── TOAST ── */
.toast { .toast {
position: fixed; bottom: 28px; right: 28px; position: fixed;
background: var(--panel); border: 1px solid var(--border); bottom: 24px;
border-radius: 2px; padding: 12px 18px; right: 24px;
font-size: 12px; color: var(--text); background: #2a2a2a;
display: flex; align-items: center; gap: 10px; border: 1px solid #333;
transform: translateY(20px); opacity: 0; border-radius: 8px;
padding: 12px 18px;
font-size: 13px;
color: #f0f0f0;
display: flex;
align-items: center;
gap: 10px;
transform: translateY(20px);
opacity: 0;
transition: transform 0.3s, opacity 0.3s; transition: transform 0.3s, opacity 0.3s;
z-index: 100; z-index: 100;
} }
.toast.show { transform: translateY(0); opacity: 1; } .toast.show { transform: translateY(0); opacity: 1; }
.toast-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--success); flex-shrink: 0; } .toast-dot { width: 6px; height: 6px; border-radius: 50%; background: #4ade80; flex-shrink: 0; }
</style> </style>
</head> </head>
<body> <body>
<div class="orb orb1"></div>
<div class="orb orb2"></div>
<header> <header>
<div class="logo">Loustique <span>Home</span></div> <div class="logo">Loustiques Home</div>
<div class="header-right"> <div class="header-right">
<div class="status-dot"><div class="dot"></div> Système actif</div> <div class="status-dot"><div class="dot"></div> Système actif</div>
<button class="logout" onclick="window.location.href='/'">Déconnexion</button> <button class="logout" onclick="window.location.href='/'">Déconnexion</button>
@@ -214,32 +220,32 @@
<main> <main>
<div class="welcome"> <div class="welcome">
<div class="label">Tableau de bord</div> <div class="label">Tableau de bord</div>
<h1>Bienvenue <span>chez vous.</span></h1> <h1>Bienvenue chez vous</h1>
</div> </div>
<div class="grid"> <div class="grid">
<div class="card"> <div class="card">
<svg class="card-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></svg> <svg class="card-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></svg>
<div class="card-label">Statut</div> <div class="card-label">Statut</div>
<div class="card-value" style="color: var(--success); font-size:20px;">En ligne</div> <div class="card-value" style="color:#4ade80;">En ligne</div>
<div class="card-sub">Serveur opérationnel</div> <div class="card-sub">Serveur opérationnel</div>
</div> </div>
<div class="card"> <div class="card">
<svg class="card-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg> <svg class="card-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
<div class="card-label">Heure locale</div> <div class="card-label">Heure locale</div>
<div class="card-value" id="clock" style="font-size:22px;">--:--</div> <div class="card-value" id="clock">--:--</div>
<div class="card-sub" id="date-display">--</div> <div class="card-sub" id="date-display">--</div>
</div> </div>
<div class="card"> <div class="card">
<svg class="card-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="2" y="3" width="20" height="14" rx="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/></svg> <svg class="card-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="2" y="3" width="20" height="14" rx="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/></svg>
<div class="card-label">Raspberry Pi</div> <div class="card-label">Raspberry Pi</div>
<div class="card-value" style="font-size:20px; color: var(--accent);">Actif</div> <div class="card-value" style="color:#2563eb;">Actif</div>
<div class="card-sub">Flask 3.1</div> <div class="card-sub">Flask 3.1</div>
</div> </div>
<div class="card"> <div class="card">
<svg class="card-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg> <svg class="card-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>
<div class="card-label">Session</div> <div class="card-label">Session</div>
<div class="card-value" style="font-size:20px;">Authentifiée</div> <div class="card-value">Authentifiée</div>
<div class="card-sub">Accès autorisé</div> <div class="card-sub">Accès autorisé</div>
</div> </div>
</div> </div>
@@ -251,6 +257,16 @@
<span class="a-label">💡 LED</span> <span class="a-label">💡 LED</span>
<span class="a-sub">Contrôler la LED</span> <span class="a-sub">Contrôler la LED</span>
<span class="a-arrow"></span> <span class="a-arrow"></span>
</button>
<button class="action-btn" onclick="callAlarm()">
<span class="a-label">💡 Alarme</span>
<span class="a-sub">Contrôler la alarme</span>
<span class="a-arrow"></span>
</button>
<button class="action-btn" onclick="callBoard1()">
<span class="a-label">💡 Board1</span>
<span class="a-sub">Contrôler la board1</span>
<span class="a-arrow"></span>
</button> </button>
<button class="action-btn" onclick="showToast('Fonction à venir...')"> <button class="action-btn" onclick="showToast('Fonction à venir...')">
<span class="a-label">⚙️ Paramètres</span> <span class="a-label">⚙️ Paramètres</span>
@@ -262,7 +278,7 @@
<span class="a-sub">État de la connexion</span> <span class="a-sub">État de la connexion</span>
<span class="a-arrow"></span> <span class="a-arrow"></span>
</button> </button>
<button class="action-btn" onclick="go_admin('Fonction à venir...')"> <button class="action-btn" onclick="go_admin()">
<span class="a-label">Administration</span> <span class="a-label">Administration</span>
<span class="a-sub">Administrer les loustiques</span> <span class="a-sub">Administrer les loustiques</span>
<span class="a-arrow"></span> <span class="a-arrow"></span>
@@ -276,7 +292,6 @@
</div> </div>
<script> <script>
function updateClock() { function updateClock() {
const now = new Date(); const now = new Date();
document.getElementById("clock").textContent = document.getElementById("clock").textContent =
@@ -293,17 +308,52 @@
const res = await fetch('/led', { const res = await fetch('/led', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' } headers: { 'Content-Type': 'application/json' }
}); });
const text = await res.text();
showToast("LED activée !"); showToast("LED activée !");
} catch { } catch {
showToast("Erreur lors de l'appel LED."); showToast("Erreur lors de l'appel LED.");
} }
} }
async function callAlarm() {
try {
const res = await fetch('/alarme', {
method: 'POST',
headers: { 'Content-Type': 'application/json' }
});
showToast("alarme activée !");
} catch {
showToast("Erreur lors de l'appel alarme.");
}
async function call_led_down() {
try {
const res = await fetch('http://pi32.local/down_led', {
method: 'GET',
headers: { 'Content-Type': 'application/json' }
});
showToast("led activée !");
} catch {
showToast("Erreur lors de l'appel board1.");
}}
}
async function call_led_up() {
try {
const res = await fetch('http://pi32.local/up_led', {
method: 'GET',
headers: { 'Content-Type': 'application/json' }
});
showToast("led activée !");
} catch {
showToast("Erreur lors de l'appel board1.");
}
function go_admin (){
}
function go_admin() {
window.location.href = "/admin"; window.location.href = "/admin";
} }
function showToast(msg) { function showToast(msg) {
const toast = document.getElementById("toast"); const toast = document.getElementById("toast");
document.getElementById("toast-text").textContent = msg; document.getElementById("toast-text").textContent = msg;

View File

@@ -3,200 +3,166 @@
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"/> <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Connexion</title> <title>Loustiques Home - Connexion</title>
<link href="https://fonts.googleapis.com/css2?family=Syne:wght@400;700;800&family=DM+Mono:wght@300;400&display=swap" rel="stylesheet"/>
<style> <style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; } * {
box-sizing: border-box;
:root { margin: 0;
--bg: #0a0a0f; padding: 0;
--panel: #111118;
--border: #1e1e2e;
--accent: #7c6aff;
--accent2: #ff6ab0;
--text: #e8e6f0;
--muted: #6b6880;
--success: #4ade80;
--error: #f87171;
} }
body { body {
font-family: 'DM Mono', monospace; font-family: system-ui, sans-serif;
background: var(--bg); background: #1f1f1f;
color: var(--text); color: #f0f0f0;
min-height: 100vh; min-height: 100vh;
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
overflow: hidden;
} }
body::before { .carte {
content: ''; width: 380px;
position: fixed;
inset: 0;
background-image:
linear-gradient(rgba(124,106,255,0.04) 1px, transparent 1px),
linear-gradient(90deg, rgba(124,106,255,0.04) 1px, transparent 1px);
background-size: 40px 40px;
animation: gridShift 20s linear infinite;
pointer-events: none;
}
@keyframes gridShift {
0% { transform: translate(0, 0); }
100% { transform: translate(40px, 40px); }
}
.orb { position: fixed; border-radius: 50%; filter: blur(80px); opacity: 0.15; pointer-events: none; }
.orb1 { width: 500px; height: 500px; background: var(--accent); top: -150px; left: -150px; animation: float1 12s ease-in-out infinite; }
.orb2 { width: 400px; height: 400px; background: var(--accent2); bottom: -100px; right: -100px; animation: float2 15s ease-in-out infinite; }
@keyframes float1 { 0%, 100% { transform: translate(0,0); } 50% { transform: translate(40px,30px); } }
@keyframes float2 { 0%, 100% { transform: translate(0,0); } 50% { transform: translate(-30px,-40px); } }
.card {
position: relative;
background: var(--panel);
border: 1px solid var(--border);
border-radius: 2px;
padding: 48px 44px;
width: 420px;
max-width: 95vw; max-width: 95vw;
animation: cardIn 0.6s cubic-bezier(0.16, 1, 0.3, 1) forwards; background: #2a2a2a;
opacity: 0; border-radius: 8px;
transform: translateY(20px); padding: 40px 36px;
} }
@keyframes cardIn { to { opacity: 1; transform: translateY(0); } } h1 {
font-size: 26px;
.card::before { font-weight: 700;
content: ''; margin-bottom: 8px;
position: absolute; text-align: center;
top: 0; left: 0; right: 0;
height: 2px;
background: linear-gradient(90deg, var(--accent), var(--accent2));
} }
.tag { font-size: 10px; letter-spacing: 0.2em; text-transform: uppercase; color: var(--accent); margin-bottom: 20px; display: flex; align-items: center; gap: 8px; } .soustitre {
.tag::before { content: ''; display: inline-block; width: 18px; height: 1px; background: var(--accent); } font-size: 14px;
color: #888;
margin-bottom: 36px;
text-align: center;
}
h1 { font-family: 'Syne', sans-serif; font-size: 32px; font-weight: 800; letter-spacing: -0.03em; margin-bottom: 8px; } .champ {
h1 span { background: linear-gradient(135deg, var(--accent), var(--accent2)); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text; } margin-bottom: 18px;
}
.subtitle { font-size: 12px; color: var(--muted); margin-bottom: 36px; letter-spacing: 0.02em; } label {
display: block;
.field { margin-bottom: 20px; } font-size: 13px;
font-weight: 500;
label { display: block; font-size: 10px; letter-spacing: 0.15em; text-transform: uppercase; color: var(--muted); margin-bottom: 8px; } margin-bottom: 6px;
color: #aaa;
}
input { input {
width: 100%; width: 100%;
background: rgba(255,255,255,0.03); padding: 11px 14px;
border: 1px solid var(--border); font-size: 14px;
border-radius: 2px; font-family: inherit;
padding: 12px 14px; border: 1px solid #3a3a3a;
font-family: 'DM Mono', monospace; border-radius: 6px;
font-size: 13px;
color: var(--text);
outline: none; outline: none;
transition: border-color 0.2s, background 0.2s, box-shadow 0.2s; transition: border-color 0.15s;
color: #f0f0f0;
background: #333;
}
input:focus {
border-color: #2563eb;
}
input::placeholder {
color: #555;
} }
input:focus { border-color: var(--accent); background: rgba(124,106,255,0.05); box-shadow: 0 0 0 3px rgba(124,106,255,0.1); }
input::placeholder { color: var(--muted); }
button { button {
width: 100%; width: 100%;
margin-top: 28px; margin-top: 10px;
padding: 14px; padding: 12px;
background: var(--accent); background: #2563eb;
border: none;
border-radius: 2px;
font-family: 'Syne', sans-serif;
font-size: 13px;
font-weight: 700;
letter-spacing: 0.1em;
text-transform: uppercase;
color: #fff; color: #fff;
border: none;
border-radius: 6px;
font-size: 14px;
font-weight: 600;
font-family: inherit;
cursor: pointer; cursor: pointer;
position: relative; transition: background 0.15s;
overflow: hidden;
transition: background 0.2s, transform 0.1s;
} }
button:hover { background: #6a58ee; }
button:active { transform: scale(0.98); } button:hover { background: #1d4ed8; }
button:disabled { opacity: 0.5; cursor: not-allowed; transform: none; } button:active { background: #1e40af; }
button.loading::after { button:disabled { opacity: 0.4; cursor: not-allowed; }
content: '';
position: absolute; inset: 0;
background: linear-gradient(90deg, transparent, rgba(255,255,255,0.15), transparent);
animation: shimmer 1.2s infinite;
}
@keyframes shimmer { 0% { transform: translateX(-100%); } 100% { transform: translateX(100%); } }
.message { .message {
margin-top: 16px; padding: 10px 14px; border-radius: 2px; margin-top: 14px;
font-size: 12px; letter-spacing: 0.03em; font-size: 13px;
display: none; align-items: center; gap: 8px; display: none;
}
.message.error {
display: block;
color: #f87171;
}
.message.success {
display: block;
color: #4ade80;
} }
.message.success { display: flex; background: rgba(74,222,128,0.08); border: 1px solid rgba(74,222,128,0.2); color: var(--success); }
.message.error { display: flex; background: rgba(248,113,113,0.08); border: 1px solid rgba(248,113,113,0.2); color: var(--error); }
.footer { margin-top: 28px; padding-top: 20px; border-top: 1px solid var(--border); font-size: 10px; color: var(--muted); text-align: center; letter-spacing: 0.05em; } .footer {
margin-top: 28px;
font-size: 12px;
color: #555;
}
</style> </style>
</head> </head>
<body> <body>
<div class="orb orb1"></div>
<div class="orb orb2"></div>
<div class="card"> <div class="carte">
<div class="tag">Authentification</div> <h1>Loustiques Home</h1>
<h1>Loustique Home</span></h1> <p class="soustitre">Connectez-vous pour accéder à votre espace.</p>
<p class="subtitle">Connectez-vous pour accéder à votre espace.</p>
<div class="field"> <div class="champ">
<label for="username">Identifiant</label> <label for="username">Identifiant</label>
<input type="text" id="username" placeholder="Nom du loustique" autocomplete="username" /> <input type="text" id="username" placeholder="Nom du loustique" autocomplete="username" />
</div> </div>
<div class="field"> <div class="champ">
<label for="password">Mot de passe</label> <label for="password">Mot de passe</label>
<input type="password" id="password" placeholder="Le secret du loustique" autocomplete="current-password" /> <input type="password" id="password" placeholder="Wola ouais" autocomplete="current-password" />
</div> </div>
<button id="btn" onclick="handleLogin()">Se connecter</button> <button id="btn" onclick="handleLogin()">Se connecter</button>
<div class="message" id="msg"> <div class="message" id="msg"></div>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path id="icon-path"/> <p class="footer">Accès réservé aux utilisateurs ajoutés par les loustiques.</p>
</svg>
<span id="msg-text"></span>
</div> </div>
<div class="footer">Accès réservé aux Utilisateurs étant ajoutés par les loustiques</div> <script>
</div> // 1. Écoute de la touche Entrée
<script>
["username", "password"].forEach(id => { ["username", "password"].forEach(id => {
document.getElementById(id).addEventListener("keydown", e => { document.getElementById(id).addEventListener("keydown", e => {
if (e.key === "Enter") handleLogin(); if (e.key === "Enter") handleLogin();
}); });
}); });
// 2. Fonction de connexion manuelle (Mot de passe)
async function handleLogin() { async function handleLogin() {
const username = document.getElementById("username").value.trim(); const username = document.getElementById("username").value.trim();
const password = document.getElementById("password").value; const password = document.getElementById("password").value;
const btn = document.getElementById("btn"); const btn = document.getElementById("btn");
const msg = document.getElementById("msg");
document.getElementById("msg").className = "message"; msg.className = "message";
if (!username || !password) { if (!username || !password) {
showMessage("error", "Veuillez remplir tous les champs."); msg.className = "message error";
msg.textContent = "Veuillez remplir tous les champs.";
return; return;
} }
btn.disabled = true; btn.disabled = true;
btn.classList.add("loading");
btn.textContent = "Vérification..."; btn.textContent = "Vérification...";
try { try {
@@ -208,30 +174,47 @@
const data = await res.json(); const data = await res.json();
if (data.success) { if (data.success) {
showMessage("success", data.message || "Connexion réussie !"); msg.className = "message success";
msg.textContent = "Connexion réussie !";
window.location.href = "/dashboard"; window.location.href = "/dashboard";
} else { } else {
showMessage("error", data.message || "Identifiants incorrects."); msg.className = "message error";
msg.textContent = data.message || "Identifiants incorrects.";
} }
} catch { } catch {
showMessage("error", "Impossible de contacter le serveur."); msg.className = "message error";
msg.textContent = "Impossible de contacter le serveur.";
} finally { } finally {
btn.disabled = false; btn.disabled = false;
btn.classList.remove("loading");
btn.textContent = "Se connecter"; btn.textContent = "Se connecter";
} }
} }
setInterval(async () => {
try {
function showMessage(type, text) { const res = await fetch('/api/check-rfid-login');
const data = await res.json();
if (data.success) {
const msg = document.getElementById("msg"); const msg = document.getElementById("msg");
const path = document.getElementById("icon-path"); const btn = document.getElementById("btn");
document.getElementById("msg-text").textContent = text; const inputs = document.querySelectorAll("input");
msg.className = "message " + type;
path.setAttribute("d", type === "success" btn.disabled = true;
? "M20 6L9 17l-5-5" inputs.forEach(input => input.disabled = true);
: "M12 2a10 10 0 1 0 0 20A10 10 0 0 0 12 2zm0 6v4m0 4h.01"
); msg.className = "message success";
msg.textContent = "Badge reconnu ! Bienvenue " + data.username + "...";
setTimeout(() => {
window.location.href = "/dashboard";
}, 1000);
} }
} catch (e) {
}
}, 2000);
</script> </script>
</body> </body>
</html> </html>

View File

@@ -3,33 +3,14 @@
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Logs — Loustiques</title> <title>Loustiques Home - Logs</title>
<link href="https://fonts.googleapis.com/css2?family=Space+Mono:wght@400;700&family=DM+Sans:wght@300;400;500&display=swap" rel="stylesheet">
<style> <style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; } *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
:root {
--bg: #0f0f0f;
--surface: #181818;
--surface2: #222222;
--border: rgba(255,255,255,0.08);
--border-hover: rgba(255,255,255,0.18);
--text: #f0ede8;
--muted: #888880;
--accent: #c8f060;
--accent-dim: rgba(200,240,96,0.12);
--danger: #ff5f57;
--danger-dim: rgba(255,95,87,0.12);
--success: #30d158;
--warning: #ff9f0a;
--mono: 'Space Mono', monospace;
--sans: 'DM Sans', sans-serif;
}
body { body {
background: var(--bg); font-family: system-ui, sans-serif;
color: var(--text); background: #1f1f1f;
font-family: var(--sans); color: #f0f0f0;
min-height: 100vh; min-height: 100vh;
display: flex; display: flex;
} }
@@ -37,8 +18,8 @@
aside { aside {
width: 220px; width: 220px;
min-height: 100vh; min-height: 100vh;
background: var(--surface); background: #1a1a1a;
border-right: 1px solid var(--border); border-right: 1px solid #2e2e2e;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
padding: 2rem 1.25rem; padding: 2rem 1.25rem;
@@ -47,22 +28,20 @@
} }
.logo { .logo {
font-family: var(--mono); font-size: 20px;
font-size: 13px; font-weight: 700;
color: var(--accent); color: #f0f0f0;
letter-spacing: 0.12em;
text-transform: uppercase;
margin-bottom: 2.5rem; margin-bottom: 2.5rem;
padding-bottom: 1.5rem; padding-bottom: 1.5rem;
border-bottom: 1px solid var(--border); border-bottom: 1px solid #2e2e2e;
} }
.logo span { .logo span {
display: block; display: block;
font-size: 10px; font-size: 15px;
color: var(--muted); color: #666;
margin-top: 4px; margin-top: 4px;
letter-spacing: 0.06em; font-weight: 400;
} }
nav a { nav a {
@@ -71,27 +50,26 @@
gap: 10px; gap: 10px;
padding: 8px 10px; padding: 8px 10px;
border-radius: 6px; border-radius: 6px;
font-size: 13.5px; font-size: 13px;
color: var(--muted); color: #888;
text-decoration: none; text-decoration: none;
margin-bottom: 2px; margin-bottom: 2px;
transition: all 0.15s; transition: all 0.15s;
} }
nav a.active, nav a:hover { nav a.active, nav a:hover {
background: var(--accent-dim); background: #2e2e3a;
color: var(--accent); color: #2563eb;
} }
nav a svg { width: 15px; height: 15px; flex-shrink: 0; } nav a svg { width: 15px; height: 15px; flex-shrink: 0; }
.sidebar-footer { .sidebar-footer {
margin-top: auto; margin-top: auto;
font-size: 12px; font-size: 15px;
color: var(--muted); color: #555;
font-family: var(--mono);
padding-top: 1rem; padding-top: 1rem;
border-top: 1px solid var(--border); border-top: 1px solid #2e2e2e;
} }
main { main {
@@ -107,40 +85,21 @@
margin-bottom: 2rem; margin-bottom: 2rem;
} }
.page-header h1 { .page-header h1 { font-size: 22px; font-weight: 700; margin-bottom: 4px; }
font-family: var(--mono); .page-header p { font-size: 14px; color: #888; }
font-size: 22px;
font-weight: 700;
color: var(--text);
margin-bottom: 4px;
}
.page-header p { font-size: 14px; color: var(--muted); } .controls { display: flex; align-items: center; gap: 10px; }
.controls {
display: flex;
align-items: center;
gap: 10px;
}
.live-dot { .live-dot {
width: 8px; width: 8px; height: 8px;
height: 8px;
border-radius: 50%; border-radius: 50%;
background: var(--success); background: #4ade80;
animation: pulse 2s infinite; animation: pulse 2s infinite;
} }
@keyframes pulse { @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.3; } }
0%, 100% { opacity: 1; }
50% { opacity: 0.3; }
}
.live-label { .live-label { font-size: 11px; color: #666; }
font-family: var(--mono);
font-size: 11px;
color: var(--muted);
}
.btn { .btn {
display: inline-flex; display: inline-flex;
@@ -148,54 +107,42 @@
gap: 6px; gap: 6px;
padding: 7px 14px; padding: 7px 14px;
border-radius: 6px; border-radius: 6px;
border: 1px solid var(--border); border: 1px solid #3a3a3a;
font-family: var(--mono); font-family: inherit;
font-size: 11px; font-size: 12px;
letter-spacing: 0.05em;
cursor: pointer; cursor: pointer;
background: var(--surface); background: #2a2a2a;
color: var(--muted); color: #888;
transition: all 0.15s; transition: all 0.15s;
} }
.btn:hover { border-color: #555; color: #f0f0f0; }
.btn:hover { border-color: var(--border-hover); color: var(--text); } .btn-danger { color: #f87171; border-color: rgba(248,113,113,0.3); background: rgba(248,113,113,0.05); }
.btn-danger:hover { background: rgba(248,113,113,0.1); }
.btn-danger { .filters { display: flex; gap: 8px; margin-bottom: 1rem; }
color: var(--danger);
border-color: rgba(255,95,87,0.2);
background: var(--danger-dim);
}
.btn-danger:hover { background: rgba(255,95,87,0.2); }
.filters {
display: flex;
gap: 8px;
margin-bottom: 1rem;
}
.filter-btn { .filter-btn {
padding: 5px 12px; padding: 5px 12px;
border-radius: 5px; border-radius: 5px;
border: 1px solid var(--border); border: 1px solid #3a3a3a;
background: transparent; background: transparent;
font-family: var(--mono); font-family: inherit;
font-size: 11px; font-size: 11px;
color: var(--muted); color: #888;
cursor: pointer; cursor: pointer;
transition: all 0.15s; transition: all 0.15s;
letter-spacing: 0.05em;
} }
.filter-btn.active { background: var(--accent-dim); color: var(--accent); border-color: rgba(200,240,96,0.25); } .filter-btn.active { background: #2e2e3a; color: #2563eb; border-color: rgba(37,99,235,0.3); }
.filter-btn[data-level="ERROR"].active { background: var(--danger-dim); color: var(--danger); border-color: rgba(255,95,87,0.25); } .filter-btn[data-level="ERROR"].active { background: rgba(248,113,113,0.1); color: #f87171; border-color: rgba(248,113,113,0.3); }
.filter-btn[data-level="WARNING"].active { background: rgba(255,159,10,0.1); color: var(--warning); border-color: rgba(255,159,10,0.25); } .filter-btn[data-level="WARNING"].active { background: rgba(251,191,36,0.1); color: #fbbf24; border-color: rgba(251,191,36,0.3); }
.filter-btn[data-level="INFO"].active { background: rgba(48,209,88,0.08); color: var(--success); border-color: rgba(48,209,88,0.25); } .filter-btn[data-level="INFO"].active { background: rgba(74,222,128,0.08); color: #4ade80; border-color: rgba(74,222,128,0.3); }
.log-container { .log-container {
background: var(--surface); background: #2a2a2a;
border: 1px solid var(--border); border: 1px solid #333;
border-radius: 12px; border-radius: 8px;
overflow: hidden; overflow: hidden;
} }
@@ -203,43 +150,36 @@
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
padding: 12px 16px; padding: 10px 16px;
border-bottom: 1px solid var(--border); border-bottom: 1px solid #333;
} }
.log-count { .log-count { font-size: 11px; color: #666; }
font-family: var(--mono);
font-size: 11px;
color: var(--muted);
}
.log-scroll { .log-scroll {
height: calc(100vh - 280px); height: calc(100vh - 280px);
overflow-y: auto; overflow-y: auto;
padding: 0; font-family: monospace;
} }
.log-scroll::-webkit-scrollbar { width: 4px; } .log-scroll::-webkit-scrollbar { width: 4px; }
.log-scroll::-webkit-scrollbar-track { background: transparent; } .log-scroll::-webkit-scrollbar-track { background: transparent; }
.log-scroll::-webkit-scrollbar-thumb { background: var(--border-hover); border-radius: 2px; } .log-scroll::-webkit-scrollbar-thumb { background: #444; border-radius: 2px; }
.log-line { .log-line {
display: grid; display: grid;
grid-template-columns: 160px 70px 80px 1fr; grid-template-columns: 160px 70px 80px 1fr;
gap: 0;
padding: 7px 16px; padding: 7px 16px;
border-bottom: 1px solid rgba(255,255,255,0.03); border-bottom: 1px solid rgba(255,255,255,0.03);
font-family: var(--mono);
font-size: 12px; font-size: 12px;
transition: background 0.1s;
align-items: center; align-items: center;
transition: background 0.1s;
} }
.log-line:hover { background: #333; }
.log-line:hover { background: var(--surface2); }
.log-line:last-child { border-bottom: none; } .log-line:last-child { border-bottom: none; }
.log-time { color: var(--muted); font-size: 11px; } .log-time { color: #666; font-size: 11px; }
.log-name { color: var(--muted); font-size: 11px; } .log-name { color: #666; font-size: 11px; }
.log-level { .log-level {
font-size: 10px; font-size: 10px;
@@ -247,15 +187,14 @@
border-radius: 4px; border-radius: 4px;
text-align: center; text-align: center;
width: fit-content; width: fit-content;
letter-spacing: 0.06em;
} }
.level-INFO { background: rgba(48,209,88,0.1); color: var(--success); } .level-INFO { background: rgba(74,222,128,0.1); color: #4ade80; }
.level-ERROR { background: var(--danger-dim); color: var(--danger); } .level-ERROR { background: rgba(248,113,113,0.1); color: #f87171; }
.level-WARNING { background: rgba(255,159,10,0.1); color: var(--warning); } .level-WARNING { background: rgba(251,191,36,0.1); color: #fbbf24; }
.level-DEBUG { background: var(--surface2); color: var(--muted); } .level-DEBUG { background: #333; color: #666; }
.log-msg { color: var(--text); padding-left: 12px; word-break: break-all; } .log-msg { color: #f0f0f0; padding-left: 12px; word-break: break-all; }
.empty-state { .empty-state {
display: flex; display: flex;
@@ -263,27 +202,25 @@
align-items: center; align-items: center;
justify-content: center; justify-content: center;
height: 200px; height: 200px;
color: var(--muted); color: #555;
font-family: var(--mono); font-size: 13px;
font-size: 12px;
gap: 8px; gap: 8px;
} }
.search-input { .search-input {
background: var(--surface2); background: #333;
border: 1px solid var(--border); border: 1px solid #3a3a3a;
border-radius: 6px; border-radius: 6px;
padding: 6px 12px; padding: 6px 12px;
color: var(--text); color: #f0f0f0;
font-family: var(--mono); font-family: inherit;
font-size: 12px; font-size: 12px;
outline: none; outline: none;
width: 220px; width: 220px;
transition: border-color 0.15s; transition: border-color 0.15s;
} }
.search-input:focus { border-color: #2563eb; }
.search-input:focus { border-color: var(--accent); } .search-input::placeholder { color: #555; }
.search-input::placeholder { color: var(--muted); }
</style> </style>
</head> </head>
<body> <body>
@@ -291,7 +228,7 @@
<aside> <aside>
<div class="logo"> <div class="logo">
Loustiques Loustiques
<span>panneau admin</span> <span>Panneau admin</span>
</div> </div>
<nav> <nav>
<a href="/admin"> <a href="/admin">
@@ -307,16 +244,14 @@
Système Système
</a> </a>
</nav> </nav>
<div class="sidebar-footer"> <div class="sidebar-footer">v0.1.0 — local</div>
v0.1.0 — local
</div>
</aside> </aside>
<main> <main>
<div class="page-header"> <div class="page-header">
<div> <div>
<h1>logs</h1> <h1>Logs</h1>
<p>Flux en temps réel de <code style="font-family:var(--mono);font-size:12px;color:var(--muted)">/var/log/loustique.log</code></p> <p>Flux en temps réel de <code style="font-size:12px;color:#888">/var/log/loustique.log</code></p>
</div> </div>
<div class="controls"> <div class="controls">
<div class="live-dot" id="live-dot"></div> <div class="live-dot" id="live-dot"></div>
@@ -441,13 +376,13 @@ function toggleLive() {
const btn = document.getElementById('toggle-label'); const btn = document.getElementById('toggle-label');
if (liveEnabled) { if (liveEnabled) {
dot.style.animationPlayState = 'running'; dot.style.animationPlayState = 'running';
dot.style.background = 'var(--success)'; dot.style.background = '#4ade80';
label.textContent = 'live'; label.textContent = 'live';
btn.textContent = 'Pause'; btn.textContent = 'Pause';
startInterval(); startInterval();
} else { } else {
dot.style.animationPlayState = 'paused'; dot.style.animationPlayState = 'paused';
dot.style.background = 'var(--muted)'; dot.style.background = '#555';
label.textContent = 'pausé'; label.textContent = 'pausé';
btn.textContent = 'Reprendre'; btn.textContent = 'Reprendre';
clearInterval(interval); clearInterval(interval);

16
to_do.txt Normal file
View File

@@ -0,0 +1,16 @@
1. ldr --> ETEINT ALLUME ou lux && activer les trois led (phyisque si possible faire en sorte d'eteindre les
lumières via html faire bouton auto ou manuel sur le html pour ldr)
2. Servo moteur phyisquement ouvrir/fermer et afficher l'etat sur l'html div presentoire
(36/13 convertir en BCM)
3. Faire la logique de l'alarme et que le peer detecte du mouvement ca sonne + RGB alarme
- bleu desactivée
- Vert activée
- Rouge activée et détection d'objet
activation du buzzer de façon COHÉRENTE !!!!!
4. RFID à vérifier
5. faire la connectivité des raspberries

View File

@@ -0,0 +1,260 @@
Metadata-Version: 2.1
Name: RPi.GPIO
Version: 0.7.1
Summary: A module to control Raspberry Pi GPIO channels
Home-page: http://sourceforge.net/projects/raspberry-gpio-python/
Author: Ben Croston
Author-email: ben@croston.org
License: MIT
Keywords: Raspberry Pi GPIO
Classifier: Development Status :: 5 - Production/Stable
Classifier: Operating System :: POSIX :: Linux
Classifier: License :: OSI Approved :: MIT License
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Software Development
Classifier: Topic :: Home Automation
Classifier: Topic :: System :: Hardware
License-File: LICENCE.txt
This package provides a Python module to control the GPIO on a Raspberry Pi.
Note that this module is unsuitable for real-time or timing critical applications. This is because you
can not predict when Python will be busy garbage collecting. It also runs under the Linux kernel which
is not suitable for real time applications - it is multitasking O/S and another process may be given
priority over the CPU, causing jitter in your program. If you are after true real-time performance and
predictability, buy yourself an Arduino http://www.arduino.cc !
Note that the current release does not support SPI, I2C, hardware PWM or serial functionality on the RPi yet.
This is planned for the near future - watch this space! One-wire functionality is also planned.
Although hardware PWM is not available yet, software PWM is available to use on all channels.
For examples and documentation, visit http://sourceforge.net/p/raspberry-gpio-python/wiki/Home/
Change Log
==========
0.7.1
-------
- Better RPi board + peri_addr detection (issue 190 / 191)
- Fix PyEval_InitThreads deprecation warning for Python 3.9 (issue 188)
- Fix build using GCC 10 (issue 187)
- Fix docstrings to not include licence
- Remove Debian/Raspbian stretch packaging support
- Use setuptools instead of distutils
- Added detection of Zero 2 W
- Tested and working with Python 2.7, 3.7, 3.8, 3.9, 3.10
0.7.0
-----
- Updated RPI_INFO to include RPi 4B
- Fixed pull up/down for Pi4 (issue 168)
- Fix spelling mistake in docstrings
- Tested and working on Raspbian Buster + Python 3.8.0b2
- Fix board detection for aarch64 (Issues 161 / 165)
- Fix checking mmap return value in c_gpio.c (issue 166)
0.6.5
-----
- Fix exception on re-export of /sys/class/gpio/gpioNN
0.6.4
-----
- Event cleanup bug (issue 145)
- Raise exception for duplicate PWM objects (issue 54 - Thijs Schreijer <thijs@thijsschreijer.nl>)
- Fix build warnings (Issue 146 - Dominik George)
- test.py runs unchanged for both python 2+3
- Soft PWM stops running fix (Issues 94, 111, 154)
- Soft PWM segfault fix (Luke Allen pull request)
0.6.3
-----
- Fix code so it builds under PyPy (Gasper Zejn)
- os.system breaks event detection - Matt Kimball (issue 127)
0.6.2
-----
- Rewrote Debian packaging mechanism
- RPI_INFO reports Pi 3
- Changed module layout - moved C components to RPi._GPIO
0.6.1
-----
- Update RPI_INFO to detect more board types
- Issue 118 - add_event_detect sometimes gives runtime error with unpriv user
- Issue 120 - setmode() remembers invalid mode
0.6.0a3
-------
- Now uses /dev/gpiomem if available to avoid being run as root
- Fix warnings with pull up/down on pins 3/5
- Correct base address on Pi 2 when devicetree is disabled
- caddr_t error on compile (Issue 109)
- Error on invalid parameters to setup() (issue 93)
- Add timeout parameter to wait_for_edge() (issue 91)
0.5.11
------
- Fix - pins > 26 missing when using BOARD mode
- Add getmode()
- Raise exception when a mix of modes is used
- GPIO.cleanaup() unsets the current pin mode
0.5.10
------
- Issue 95 - support RPi 2 boards
- Introduce RPI_INFO
- Deprecate RPI_REVISION
- Issue 97 - fixed docstring for setup()
0.5.9
-----
- Issue 87 - warn about pull up/down on i2c pins
- Issue 86/75 - wait_for_edge() bugfix
- Issue 84 - recognise RPi properly when using a custom kernel
- Issue 90 - cleanup() on a list/tuple of channels
0.5.8
-----
- Allow lists/tuples of channels in GPIO.setup()
- GPIO.output() now allows lists/tuples of values
- GPIO.wait_for_edge() bug fixes (issue 78)
0.5.7
-----
- Issue 67 - speed up repeated calls to GPIO.wait_for_event()
- Added bouncetime keyword to GPIO.wait_for_event()
- Added extra edge/interrupt unit tests
- GPIO.wait_for_event() can now be mixed with GPIO.add_event_detect()
- Improved cleanups of events
- Issue 69 resolved
0.5.6
-----
- Issue 68 - support for RPi Model B+
- Fix gpio_function()
0.5.5
-----
- Issue 52 - 'unallocate' a channel
- Issue 35 - use switchbounce with GPIO.event_detected()
- Refactored events code
- Rewrote tests to use unittest mechanism and new test board with loopbacks
- Fixed adding events after a GPIO.cleanup()
- Issue 64 - misleading /dev/mem permissions error
- Issue 59 - name collision with PWM constant and class
0.5.4
-----
- Changed release status (from alpha to full release)
- Warn when GPIO.cleanup() used with nothing to clean up (issue 44)
- Avoid collisions in constants (e.g. HIGH / RISING / PUD_DOWN)
- Accept BOARD numbers in gpio_function (issue 34)
- More return values for gpio_function (INPUT, OUTPUT, SPI, I2C, PWM, SERIAL, UNKNOWN)
- Tidy up docstrings
- Fix /dev/mem access error with gpio_function
0.5.3a
------
- Allow pydoc for non-root users (issue 27)
- Fix add_event_detect error when run as daemon (issue 32)
- Simplified exception types
- Changed from distribute to pip
0.5.2a
------
- Added software PWM (experimental)
- Added switch bounce handling to event callbacks
- Added channel number parameter to event callbacks (issue 31)
- Internal refactoring and code tidy up
0.5.1a
------
- Fixed callbacks for multiple GPIOs (issue 28)
0.5.0a
------
- Added new edge detection events (interrupt handling)
- Added add_event_detect()
- Added remove_event_detect()
- Added add_event_callback()
- Added wait_for_edge()
- Removed old experimental event functions
- Removed set_rising_event()
- Removed set_falling_event()
- Removed set_high_event()
- Removed set_low_event()
- Changed event_detected() for new edge detection functionality
- input() now returns 0/LOW == False or 1/HIGH == True (integers) instead of False or True (booleans).
- Fix error on repeated import (issue 3)
- Change SetupException to a RuntimeError so it can be caught on import (issue 25, Chris Hager <chris@linuxuser.at>)
- Improved docstrings of functions
0.4.2a
------
- Fix for installing on Arch Linux (Python 3.3) (issue 20)
- Initial value when setting a channel as an output (issue 19)
0.4.1a
------
- Added VERSION
- Permit input() of channels set as outputs (Eric Ptak <trouch@trouch.com>)
0.4.0a
------
- Added support for Revision 2 boards
- Added RPI_REVISION
- Added cleanup() function and removed automatic reset functionality on program exit
- Added get_function() to read existing GPIO channel functionality (suggestion from Eric Ptak <trouch@trouch.com>)
- Added set_rising_event()
- Added set_falling_event()
- Added set_high_event()
- Added set_low_event()
- Added event_detected()
- Added test/test.py
- Converted debian to armhf
- Fixed C function short_wait() (thanks to Thibault Porteboeuf <thibaultporteboeuf@gmail.com>)
0.3.1a
------
- Fixed critical bug with swapped high/low state on outputs
- Added pull-up / pull-down setup functionality for inputs
0.3.0a
------
- Rewritten as a C extension
- Now uses /dev/mem and SoC registers instead of /sys/class/gpio
- Faster!
- Make call to GPIO.setmode() mandatory
- Added GPIO.HIGH and GPIO.LOW constants
0.2.0
-----
- Changed status from alpha to beta
- Added setmode() to be able to use BCM GPIO 00.nn channel numbers
- Renamed InvalidPinException to InvalidChannelException
0.1.0
------
- Fixed direction bug
- Added MANIFEST.in (to include missing file)
- Changed GPIO channel number to pin number
- Tested and working!
0.0.3a
------
- Added GPIO table
- Refactored
- Fixed a few critical bugs
- Still completely untested!
0.0.2a
------
- Internal refactoring. Still completely untested!
0.0.1a
------
- First version. Completely untested until I can get hold of a Raspberry Pi!

View File

@@ -0,0 +1,31 @@
CHANGELOG.txt
INSTALL.txt
LICENCE.txt
MANIFEST.in
README.txt
create_gpio_user_permissions.py
setup.cfg
setup.py
RPi/__init__.py
RPi.GPIO.egg-info/PKG-INFO
RPi.GPIO.egg-info/SOURCES.txt
RPi.GPIO.egg-info/dependency_links.txt
RPi.GPIO.egg-info/top_level.txt
RPi/GPIO/__init__.py
source/c_gpio.c
source/c_gpio.h
source/common.c
source/common.h
source/constants.c
source/constants.h
source/cpuinfo.c
source/cpuinfo.h
source/event_gpio.c
source/event_gpio.h
source/py_gpio.c
source/py_pwm.c
source/py_pwm.h
source/soft_pwm.c
source/soft_pwm.h
test/issue_94_111_154.py
test/test.py

View File

@@ -0,0 +1,9 @@
../RPi/GPIO/__init__.py
../RPi/GPIO/__pycache__/__init__.cpython-311.pyc
../RPi/_GPIO.cpython-311-x86_64-linux-gnu.so
../RPi/__init__.py
../RPi/__pycache__/__init__.cpython-311.pyc
PKG-INFO
SOURCES.txt
dependency_links.txt
top_level.txt

View File

@@ -0,0 +1,25 @@
# Copyright (c) 2012-2021 Ben Croston
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software is furnished to do
# so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""This package provides a Python module to control the GPIO on a Raspberry Pi"""
from RPi._GPIO import *
VERSION = '0.7.1'

View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1,490 @@
Metadata-Version: 2.1
Name: flask-talisman
Version: 1.1.0
Summary: HTTP security headers for Flask.
Home-page: https://github.com/wntrblm/flask-talisman
Author: Alethea Katherine Flowers
Author-email: me@thea.codes
License: Apache Software License
Keywords: flask security https xss
Platform: UNKNOWN
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.5
Classifier: Programming Language :: Python :: 3.6
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Operating System :: POSIX
Classifier: Operating System :: MacOS
Classifier: Operating System :: Unix
License-File: LICENSE
Talisman: HTTP security headers for Flask
=========================================
|PyPI Version|
Talisman is a small Flask extension that handles setting HTTP headers
that can help protect against a few common web application security
issues.
The default configuration:
- Forces all connects to ``https``, unless running with debug enabled.
- Enables `HTTP Strict Transport
Security <https://developer.mozilla.org/en-US/docs/Web/Security/HTTP_strict_transport_security>`_.
- Sets Flask's session cookie to ``secure``, so it will never be set if
your application is somehow accessed via a non-secure connection.
- Sets Flask's session cookie to ``httponly``, preventing JavaScript
from being able to access its content. CSRF via Ajax uses a separate
cookie and should be unaffected.
- Sets Flask's session cookie to ``Lax``, preventing the cookie to be leaked
in CSRF-prone request methods.
- Sets
`X-Frame-Options <https://developer.mozilla.org/en-US/docs/Web/HTTP/X-Frame-Options>`_
to ``SAMEORIGIN`` to avoid
`clickjacking <https://en.wikipedia.org/wiki/Clickjacking>`_.
- Sets `X-Content-Type-Options
<https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options>`_
to prevent content type sniffing.
- Sets a strict `Content Security
Policy <https://developer.mozilla.org/en-US/docs/Web/Security/CSP/Introducing_Content_Security_Policy>`__
of ``default-src: 'self', 'object-src': 'none'``. This is intended to almost completely
prevent Cross Site Scripting (XSS) attacks. This is probably the only
setting that you should reasonably change. See the
`Content Security Policy`_ section.
- Sets a strict `Referrer-Policy <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy>`_
of ``strict-origin-when-cross-origin`` that governs which referrer information should be included with
requests made.
- Disables ``browsing-topics`` by default in the `Permissions-Policy <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Feature-Policy>`_
like `Drupal <https://www.drupal.org/project/drupal/issues/3209628>`_ to enhance privacy protection.
In addition to Talisman, you **should always use a cross-site request
forgery (CSRF) library**. It's highly recommended to use
`Flask-SeaSurf <https://flask-seasurf.readthedocs.org/en/latest/>`_,
which is based on Django's excellent library.
Installation & Basic Usage
--------------------------
Install via `pip <https://pypi.python.org/pypi/pip>`_:
::
pip install flask-talisman
After installing, wrap your Flask app with a ``Talisman``:
.. code:: python
from flask import Flask
from flask_talisman import Talisman
app = Flask(__name__)
Talisman(app)
There is also a full `Example App <https://github.com/wntrblm/flask-talisman/blob/master/example_app>`_.
Options
-------
- ``force_https``, default ``True``, forces all non-debug connects to
``https`` (`about HTTPS <https://developer.mozilla.org/en-US/docs/Glossary/https>`_).
- ``force_https_permanent``, default ``False``, uses ``301`` instead of
``302`` for ``https`` redirects.
- ``frame_options``, default ``SAMEORIGIN``, can be ``SAMEORIGIN``,
``DENY``, or ``ALLOWFROM`` (`about Frame Options <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options>`_).
- ``frame_options_allow_from``, default ``None``, a string indicating
the domains that are allowed to embed the site via iframe.
- ``strict_transport_security``, default ``True``, whether to send HSTS
headers (`about HSTS <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security>`_).
- ``strict_transport_security_preload``, default ``False``, enables HSTS
preloading. If you register your application with
`Google's HSTS preload list <https://hstspreload.appspot.com/>`_,
Firefox and Chrome will never load your site over a non-secure
connection.
- ``strict_transport_security_max_age``, default ``ONE_YEAR_IN_SECS``,
length of time the browser will respect the HSTS header.
- ``strict_transport_security_include_subdomains``, default ``True``,
whether subdomains should also use HSTS.
- ``content_security_policy``, default ``default-src: 'self'`, 'object-src': 'none'``, see the
`Content Security Policy`_ section (`about Content Security Policy <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy>`_).
- ``content_security_policy_nonce_in``, default ``[]``. Adds a per-request nonce
value to the flask request object and also to the specified CSP header section.
I.e. ``['script-src', 'style-src']``
- ``content_security_policy_report_only``, default ``False``, whether to set
the CSP header as "report-only" (as `Content-Security-Policy-Report-Only`)
to ease deployment by disabling the policy enforcement by the browser,
requires passing a value with the ``content_security_policy_report_uri``
parameter
- ``content_security_policy_report_uri``, default ``None``, a string
indicating the report URI used for `CSP violation reports
<https://developer.mozilla.org/en-US/docs/Web/Security/CSP/Using_CSP_violation_reports>`_
- ``referrer_policy``, default ``strict-origin-when-cross-origin``, a string
that sets the Referrer Policy header to send a full URL when performing a same-origin
request, only send the origin of the document to an equally secure destination
(HTTPS->HTTPS), and send no header to a less secure destination (HTTPS->HTTP) (`about Referrer Policy <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy>`_).
- ``feature_policy``, default ``{}``, see the `Feature Policy`_ section (`about Feature Policy <https://developer.mozilla.org/en-US/docs/Web/HTTP/Feature_Policy>`_).
- ``permissions_policy``, default ``{'browsing-topics': '()'}``, see the `Permissions Policy`_ section (`about Permissions Policy <https://developer.mozilla.org/en-US/docs/Web/HTTP/Feature_Policy>`_).
- ``document_policy``, default ``{}``, see the `Document Policy`_ section (`about Document Policy <https://wicg.github.io/document-policy/>`_).
- ``session_cookie_secure``, default ``True``, set the session cookie
to ``secure``, preventing it from being sent over plain ``http`` (`about cookies (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie)_`).
- ``session_cookie_http_only``, default ``True``, set the session
cookie to ``httponly``, preventing it from being read by JavaScript.
- ``session_cookie_samesite``, default ``Lax``, set this to ``Strict`` to prevent the cookie from being sent by the browser to the target site in all cross-site browsing context, even when following a regular link.
- ``force_file_save``, default ``False``, whether to set the
`X-Download-Options <https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/compatibility/jj542450(v=vs.85)?redirectedfrom=MSDN>`_
header to ``noopen`` to prevent IE >= 8 to from opening file downloads
directly and only save them instead.
- ``x_content_type_options``, default ``True``, Protects against MIME sniffing vulnerabilities (`about Content Type Options <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options>`_).
- ``x_xss_protection``, default ``False``, Protects against cross-site scripting (XSS) attacks (`about XSS Protection <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-XSS-Protection>`_). This option is disabled by default because no modern browser (`supports this header <https://caniuse.com/mdn-http_headers_x-xss-protection>`_) anymore.
For a full list of (security) headers, check out: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers.
Per-view options
~~~~~~~~~~~~~~~~
Sometimes you want to change the policy for a specific view. The
``force_https``, ``frame_options``, ``frame_options_allow_from``,
`content_security_policy``, ``feature_policy``, ``permissions_policy``
and ``document_policy`` options can be changed on a per-view basis.
.. code:: python
from flask import Flask
from flask_talisman import Talisman, ALLOW_FROM
app = Flask(__name__)
talisman = Talisman(app)
@app.route('/normal')
def normal():
return 'Normal'
@app.route('/embeddable')
@talisman(frame_options=ALLOW_FROM, frame_options_allow_from='*')
def embeddable():
return 'Embeddable'
Content Security Policy
-----------------------
The default content security policy is extremely strict and will
prevent loading any resources that are not in the same domain as the
application. Most web applications will need to change this policy.
If you're not ready to deploy Content Security Policy, you can set
`content_security_policy` to `False` to disable sending this header
entirely.
A slightly more permissive policy is available at
``flask_talisman.GOOGLE_CSP_POLICY``, which allows loading Google-hosted JS
libraries, fonts, and embeding media from YouTube and Maps.
You can and should create your own policy to suit your site's needs.
Here's a few examples adapted from
`MDN <https://developer.mozilla.org/en-US/docs/Web/Security/CSP/Using_Content_Security_Policy>`_:
Example 1
~~~~~~~~~
This is the default policy. A web site administrator wants all content
to come from the site's own origin (this excludes subdomains) and disallow
legacy HTML elements.
.. code:: python
csp = {
'default-src': '\'self\'',
'object-src': '\'none\'',
}
talisman = Talisman(app, content_security_policy=csp)
Example 2
~~~~~~~~~
A web site administrator wants to allow content from a trusted domain
and all its subdomains (it doesn't have to be the same domain that the
CSP is set on.)
.. code:: python
csp = {
'default-src': [
'\'self\'',
'*.trusted.com'
]
}
Example 3
~~~~~~~~~
A web site administrator wants to allow users of a web application to
include images from any origin in their own content, but to restrict
audio or video media to trusted providers, and all scripts only to a
specific server that hosts trusted code.
.. code:: python
csp = {
'default-src': '\'self\'',
'img-src': '*',
'media-src': [
'media1.com',
'media2.com',
],
'script-src': 'userscripts.example.com'
}
In this example content is only permitted from the document's origin
with the following exceptions:
- Images may loaded from anywhere (note the ``*`` wildcard).
- Media is only allowed from media1.com and media2.com (and not from
subdomains of those sites).
- Executable script is only allowed from userscripts.example.com.
Example 4
~~~~~~~~~
A web site administrator for an online banking site wants to ensure that
all its content is loaded using SSL, in order to prevent attackers from
eavesdropping on requests.
.. code:: python
csp = {
'default-src': 'https://onlinebanking.jumbobank.com'
}
The server only permits access to documents being loaded specifically
over HTTPS through the single origin onlinebanking.jumbobank.com.
Example 5
~~~~~~~~~
A web site administrator of a web mail site wants to allow HTML in
email, as well as images loaded from anywhere, but not JavaScript or
other potentially dangerous content.
.. code:: python
csp = {
'default-src': [
'\'self\'',
'*.mailsite.com',
],
'img-src': '*'
}
Note that this example doesn't specify a ``script-src``; with the
example CSP, this site uses the setting specified by the ``default-src``
directive, which means that scripts can be loaded only from the
originating server.
Example 6
~~~~~~~~~
A web site administrator wants to allow embedded scripts (which might
be generated dynamicially).
.. code:: python
csp = {
'default-src': '\'self\'',
'script-src': '\'self\'',
}
talisman = Talisman(
app,
content_security_policy=csp,
content_security_policy_nonce_in=['script-src']
)
The nonce needs to be added to the script tag in the template:
.. code:: html
<script nonce="{{ csp_nonce() }}">
//...
</script>
Note that the CSP directive (`script-src` in the example) to which the `nonce-...`
source should be added needs to be defined explicitly.
Example 7
~~~~~~~~~
A web site adminstrator wants to override the CSP directives via an
environment variable which doesn't support specifying the policy as
a Python dictionary, e.g.:
.. code:: bash
export CSP_DIRECTIVES="default-src 'self'; image-src *"
python app.py
Then in the app code you can read the CSP directives from the environment:
.. code:: python
import os
from flask_talisman import Talisman, DEFAULT_CSP_POLICY
talisman = Talisman(
app,
content_security_policy=os.environ.get("CSP_DIRECTIVES", DEFAULT_CSP_POLICY),
)
As you can see above the policy can be defined simply just like the official
specification requires the HTTP header to be set: As a semicolon separated
list of individual CSP directives.
Feature Policy
--------------
**Note:** Feature Policy has largely been `renamed Permissions Policy <https://github.com/w3c/webappsec-feature-policy/issues/359>`_
in the latest draft and some features are likely to move to Document Policy.
At this writing, most browsers support the ``Feature-Policy`` HTTP Header name.
See the `Permissions Policy`_ and `Document Policy`_ sections below should you wish
to set these.
Also note that the Feature Policy specification did not progress beyond the `draft https://wicg.github.io/feature-policy/`
stage before being renamed, but is `supported in some form in most browsers
<https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Feature-Policy#Browser_compatibility>`_.
The default feature policy is empty, as this is the default expected behaviour.
Geolocation Example
~~~~~~~~~~~~~~~~~~~
Disable access to Geolocation interface.
.. code:: python
feature_policy = {
'geolocation': '\'none\''
}
talisman = Talisman(app, feature_policy=feature_policy)
Permissions Policy
------------------
Feature Policy has been split into Permissions Policy and Document Policy but
at this writing `browser support of Permissions Policy is very limited <https://caniuse.com/permissions-policy>`_,
and it is recommended to still set the ``Feature-Policy`` HTTP Header.
Permission Policy support is included in Talisman for when this becomes more
widely supported.
Note that the `Permission Policy is still an Working Draft <https://www.w3.org/TR/permissions-policy/>`_.
When the same feature or permission is set in both Feature Policy and Permission Policy,
the Permission Policy setting will take precedence in browsers that support both.
It should be noted that the syntax differs between Feature Policy and Permission Policy
as can be seen from the ``geolocation`` examples provided.
The default Permissions Policy is ``browsing-topics=()``, which opts sites out of
`Federated Learning of Cohorts <https://wicg.github.io/floc/>`_ an interest-based advertising initiative
called Topics API.
Permission Policy can be set either using a dictionary, or using a string.
Geolocation and Microphone Example
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Disable access to Geolocation interface and Microphone using dictionary syntax
.. code:: python
permissions_policy = {
'geolocation': '()',
'microphone': '()'
}
talisman = Talisman(app, permissions_policy=permissions_policy)
Disable access to Geolocation interface and Microphone using string syntax
.. code:: python
permissions_policy = 'geolocation=(), microphone=()'
talisman = Talisman(app, permissions_policy=permissions_policy)
Document Policy
---------------
Feature Policy has been split into Permissions Policy and Document Policy but
at this writing `browser support of Document Policy is very limited <https://caniuse.com/document-policy>`_,
and it is recommended to still set the ``Feature-Policy`` HTTP Header.
Document Policy support is included in Talisman for when this becomes more
widely supported.
Note that the `Document Policy is still an Unofficial Draft <https://wicg.github.io/document-policy/>`_.
The default Document Policy is empty, as this is the default expected behaviour.
Document Policy can be set either using a dictionary, or using a string.
Oversized-Images Example
~~~~~~~~~~~~~~~~~~~~~~~~
Forbid oversized-images using dictionary syntax:
.. code:: python
document_policy = {
'oversized-images': '?0'
}
talisman = Talisman(app, document_policy=document_policy)
Forbid oversized-images using string syntax:
.. code:: python
document_policy = 'oversized-images=?0'
talisman = Talisman(app, document_policy=document_policy)
Disclaimer
----------
This code originated at Google, but is not an official Google product,
experimental or otherwise. It was forked on June 6th, 2021 from the
unmaintained GoogleCloudPlatform/flask-talisman.
There is no silver bullet for web application security. Talisman can
help, but security is more than just setting a few headers. Any
public-facing web application should have a comprehensive approach to
security.
Contributing changes
--------------------
- See `CONTRIBUTING.md`_
Licensing
---------
- Apache 2.0 - See `LICENSE`_
.. _LICENSE: https://github.com/wntrblm/flask-talisman/blob/master/LICENSE
.. _CONTRIBUTING.md: https://github.com/wntrblm/flask-talisman/blob/master/CONTRIBUTING.md
.. |PyPI Version| image:: https://img.shields.io/pypi/v/flask-talisman.svg
:target: https://pypi.python.org/pypi/flask-talisman

View File

@@ -0,0 +1,13 @@
flask_talisman-1.1.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
flask_talisman-1.1.0.dist-info/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
flask_talisman-1.1.0.dist-info/METADATA,sha256=AwnGEfgydNEYCwtRCtDWiQB6hSaTi1QBQrdWhw997_0,18722
flask_talisman-1.1.0.dist-info/RECORD,,
flask_talisman-1.1.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
flask_talisman-1.1.0.dist-info/WHEEL,sha256=z9j0xAa_JmUKMpmz72K0ZGALSM_n-wQVmGbleXx2VHg,110
flask_talisman-1.1.0.dist-info/top_level.txt,sha256=mXVUQo_kTE7G1KmO-Pl2mbgm8braqn1FfwVzSh2rh68,15
flask_talisman/__init__.py,sha256=cTbxfRkVoP9JwIwHJFEymT3-ZuOr4uspReRunGwSNns,1027
flask_talisman/__pycache__/__init__.cpython-311.pyc,,
flask_talisman/__pycache__/talisman.cpython-311.pyc,,
flask_talisman/__pycache__/talisman_test.cpython-311.pyc,,
flask_talisman/talisman.py,sha256=Y2q-X4ug-91wpS54wArEP0LWpA0bErDNW86ZL-hPhEY,17033
flask_talisman/talisman_test.py,sha256=Ht7OTCm2VXWJJlxXNxGmMARGn3dYQg51E4lrpT772dY,14153

View File

@@ -0,0 +1,6 @@
Wheel-Version: 1.0
Generator: bdist_wheel (0.37.1)
Root-Is-Purelib: true
Tag: py2-none-any
Tag: py3-none-any

View File

@@ -0,0 +1 @@
flask_talisman

View File

@@ -0,0 +1,31 @@
# Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from .talisman import (
ALLOW_FROM, DEFAULT_CSP_POLICY, DEFAULT_DOCUMENT_POLICY,
DEFAULT_FEATURE_POLICY, DEFAULT_PERMISSIONS_POLICY, DENY,
GOOGLE_CSP_POLICY, NONCE_LENGTH, SAMEORIGIN, Talisman)
__all__ = (
'ALLOW_FROM',
'DEFAULT_CSP_POLICY',
'DEFAULT_DOCUMENT_POLICY',
'DEFAULT_FEATURE_POLICY',
'DEFAULT_PERMISSIONS_POLICY',
'DENY',
'GOOGLE_CSP_POLICY',
'NONCE_LENGTH',
'SAMEORIGIN',
'Talisman',
)

View File

@@ -0,0 +1,465 @@
# Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from collections import OrderedDict
import flask
DENY = 'DENY'
SAMEORIGIN = 'SAMEORIGIN'
ALLOW_FROM = 'ALLOW-FROM'
ONE_YEAR_IN_SECS = 31556926
DEFAULT_REFERRER_POLICY = 'strict-origin-when-cross-origin'
DEFAULT_CSP_POLICY = {
'default-src': '\'self\'',
'object-src': '\'none\'',
}
DEFAULT_SESSION_COOKIE_SAMESITE = "Lax"
GOOGLE_CSP_POLICY = {
# Fonts from fonts.google.com
'font-src': '\'self\' themes.googleusercontent.com *.gstatic.com',
# <iframe> based embedding for Maps and Youtube.
'frame-src': '\'self\' www.google.com www.youtube.com',
# Assorted Google-hosted Libraries/APIs.
'script-src': '\'self\' ajax.googleapis.com *.googleanalytics.com '
'*.google-analytics.com',
# Used by generated code from http://www.google.com/fonts
'style-src': '\'self\' ajax.googleapis.com fonts.googleapis.com '
'*.gstatic.com',
'object-src': '\'none\'',
'default-src': '\'self\' *.gstatic.com',
}
DEFAULT_PERMISSIONS_POLICY = {
# Disable Topics API
'browsing-topics': '()'
}
DEFAULT_DOCUMENT_POLICY = {
}
DEFAULT_FEATURE_POLICY = {
}
NONCE_LENGTH = 32
class Talisman(object):
"""
Talisman is a Flask extension for HTTP security headers.
"""
def __init__(self, app=None, **kwargs):
if app is not None:
self.init_app(app, **kwargs)
def init_app(
self,
app,
feature_policy=DEFAULT_FEATURE_POLICY,
permissions_policy=DEFAULT_PERMISSIONS_POLICY,
document_policy=DEFAULT_DOCUMENT_POLICY,
force_https=True,
force_https_permanent=False,
force_file_save=False,
frame_options=SAMEORIGIN,
frame_options_allow_from=None,
strict_transport_security=True,
strict_transport_security_preload=False,
strict_transport_security_max_age=ONE_YEAR_IN_SECS,
strict_transport_security_include_subdomains=True,
content_security_policy=DEFAULT_CSP_POLICY,
content_security_policy_report_uri=None,
content_security_policy_report_only=False,
content_security_policy_nonce_in=None,
referrer_policy=DEFAULT_REFERRER_POLICY,
session_cookie_secure=True,
session_cookie_http_only=True,
session_cookie_samesite=DEFAULT_SESSION_COOKIE_SAMESITE,
x_content_type_options=True,
x_xss_protection=False):
"""
Initialization.
Args:
app: A Flask application.
feature_policy: A string or dictionary describing the
feature policy for the response.
permissions_policy: A string or dictionary describing the
permissions policy for the response.
document_policy: A string or dictionary describing the
document policy for the response.
force_https: Redirects non-http requests to https, disabled in
debug mode.
force_https_permanent: Uses 301 instead of 302 redirects.
frame_options: Sets the X-Frame-Options header, defaults to
SAMEORIGIN.
frame_options_allow_from: Used when frame_options is set to
ALLOW_FROM and is a string of domains to allow frame embedding.
strict_transport_security: Sets HSTS headers.
strict_transport_security_preload: Enables HSTS preload. See
https://hstspreload.org.
strict_transport_security_max_age: How long HSTS headers are
honored by the browser.
strict_transport_security_include_subdomains: Whether to include
all subdomains when setting HSTS.
content_security_policy: A string or dictionary describing the
content security policy for the response.
content_security_policy_report_uri: A string indicating the report
URI used for CSP violation reports
content_security_policy_report_only: Whether to set the CSP header
as "report-only", which disables the enforcement by the browser
and requires a "report-uri" parameter with a backend to receive
the POST data
content_security_policy_nonce_in: A list of csp sections to include
a per-request nonce value in
referrer_policy: A string describing the referrer policy for the
response.
session_cookie_secure: Forces the session cookie to only be sent
over https. Disabled in debug mode.
session_cookie_http_only: Prevents JavaScript from reading the
session cookie.
session_cookie_samesite: Sets samesite parameter on session cookie
force_file_save: Prevents the user from opening a file download
directly on >= IE 8
x_content_type_options: Prevents MIME type sniffing
x_xss_protection: Prevents the page from loading when the browser
detects reflected cross-site scripting attacks
See README.rst for a detailed description of each option.
"""
if isinstance(feature_policy, dict):
self.feature_policy = OrderedDict(feature_policy)
else:
self.feature_policy = feature_policy
if isinstance(permissions_policy, dict):
self.permissions_policy = OrderedDict(permissions_policy)
else:
self.permissions_policy = permissions_policy
if isinstance(document_policy, dict):
self.document_policy = OrderedDict(document_policy)
else:
self.document_policy = document_policy
self.force_https = force_https
self.force_https_permanent = force_https_permanent
self.frame_options = frame_options
self.frame_options_allow_from = frame_options_allow_from
self.strict_transport_security = strict_transport_security
self.strict_transport_security_preload = \
strict_transport_security_preload
self.strict_transport_security_max_age = \
strict_transport_security_max_age
self.strict_transport_security_include_subdomains = \
strict_transport_security_include_subdomains
if isinstance(content_security_policy, dict):
self.content_security_policy = OrderedDict(content_security_policy)
else:
self.content_security_policy = content_security_policy
self.content_security_policy_report_uri = \
content_security_policy_report_uri
self.content_security_policy_report_only = \
content_security_policy_report_only
if self.content_security_policy_report_only and \
self.content_security_policy_report_uri is None:
raise ValueError(
'Setting content_security_policy_report_only to True also '
'requires a URI to be specified in '
'content_security_policy_report_uri')
self.content_security_policy_nonce_in = (
content_security_policy_nonce_in or []
)
app.jinja_env.globals['csp_nonce'] = self._get_nonce
self.referrer_policy = referrer_policy
self.session_cookie_secure = session_cookie_secure
app.config['SESSION_COOKIE_SAMESITE'] = session_cookie_samesite
if session_cookie_http_only:
app.config['SESSION_COOKIE_HTTPONLY'] = True
self.force_file_save = force_file_save
self.x_content_type_options = x_content_type_options
self.x_xss_protection = x_xss_protection
self.app = app
app.before_request(self._force_https)
app.before_request(self._make_nonce)
app.after_request(self._set_response_headers)
def _get_local_options(self):
view_function = flask.current_app.view_functions.get(
flask.request.endpoint)
view_options = getattr(
view_function, 'talisman_view_options', {})
view_options.setdefault('force_https', self.force_https)
view_options.setdefault('frame_options', self.frame_options)
view_options.setdefault(
'frame_options_allow_from', self.frame_options_allow_from)
view_options.setdefault(
'content_security_policy', self.content_security_policy)
view_options.setdefault(
'content_security_policy_nonce_in',
self.content_security_policy_nonce_in)
view_options.setdefault(
'permissions_policy', self.permissions_policy)
view_options.setdefault(
'document_policy', self.document_policy)
view_options.setdefault(
'feature_policy', self.feature_policy
)
return view_options
def _force_https(self):
"""Redirect any non-https requests to https.
Based largely on flask-sslify.
"""
if self.session_cookie_secure:
if not self.app.debug:
self.app.config['SESSION_COOKIE_SECURE'] = True
criteria = [
self.app.debug,
flask.request.is_secure,
flask.request.headers.get('X-Forwarded-Proto', 'http') == 'https',
]
local_options = self._get_local_options()
if local_options['force_https'] and not any(criteria):
if flask.request.url.startswith('http://'):
url = flask.request.url.replace('http://', 'https://', 1)
code = 302
if self.force_https_permanent:
code = 301
r = flask.redirect(url, code=code)
return r
def _set_response_headers(self, response):
"""Applies all configured headers to the given response."""
options = self._get_local_options()
self._set_feature_policy_headers(response.headers, options)
self._set_permissions_policy_headers(response.headers, options)
self._set_document_policy_headers(response.headers, options)
self._set_frame_options_headers(response.headers, options)
self._set_content_security_policy_headers(response.headers, options)
self._set_hsts_headers(response.headers)
self._set_referrer_policy_headers(response.headers)
return response
def _make_nonce(self):
local_options = self._get_local_options()
if (
local_options['content_security_policy'] and
local_options['content_security_policy_nonce_in'] and
not getattr(flask.request, 'csp_nonce', None)):
flask.request.csp_nonce = get_random_string(NONCE_LENGTH)
def _get_nonce(self):
return getattr(flask.request, 'csp_nonce', '')
def _parse_structured_header_policy(self, policy):
if isinstance(policy, str):
return policy
policies = []
for section, content in policy.items():
policy_part = '{}={}'.format(section, content)
policies.append(policy_part)
policy = ', '.join(policies)
return policy
def _parse_policy(self, policy):
local_options = self._get_local_options()
if isinstance(policy, str):
# parse the string into a policy dict
policy_string = policy
policy = OrderedDict()
for policy_part in policy_string.split(';'):
policy_parts = policy_part.strip().split(' ')
policy[policy_parts[0]] = " ".join(policy_parts[1:])
policies = []
for section, content in policy.items():
if not isinstance(content, str):
content = ' '.join(content)
policy_part = '{} {}'.format(section, content)
if (
hasattr(flask.request, 'csp_nonce') and
section in local_options['content_security_policy_nonce_in']):
policy_part += " 'nonce-{}'".format(flask.request.csp_nonce)
policies.append(policy_part)
policy = '; '.join(policies)
return policy
def _set_feature_policy_headers(self, headers, options):
if not options['feature_policy']:
return
policy = options['feature_policy']
policy = self._parse_policy(policy)
headers['Feature-Policy'] = policy
def _set_permissions_policy_headers(self, headers, options):
if not options['permissions_policy']:
return
policy = options['permissions_policy']
policy = self._parse_structured_header_policy(policy)
headers['Permissions-Policy'] = policy
def _set_document_policy_headers(self, headers, options):
if not options['document_policy']:
return
policy = options['document_policy']
policy = self._parse_structured_header_policy(policy)
headers['Document-Policy'] = policy
def _set_frame_options_headers(self, headers, options):
if not options['frame_options']:
return
headers['X-Frame-Options'] = options['frame_options']
if options['frame_options'] == ALLOW_FROM:
headers['X-Frame-Options'] += " {}".format(
options['frame_options_allow_from'])
def _set_content_security_policy_headers(self, headers, options):
if self.x_xss_protection:
headers['X-XSS-Protection'] = '1; mode=block'
if self.x_content_type_options:
headers['X-Content-Type-Options'] = 'nosniff'
if self.force_file_save:
headers['X-Download-Options'] = 'noopen'
if not options['content_security_policy']:
return
policy = options['content_security_policy']
policy = self._parse_policy(policy)
if self.content_security_policy_report_uri and \
'report-uri' not in policy:
policy += '; report-uri ' + self.content_security_policy_report_uri
csp_header = 'Content-Security-Policy'
if self.content_security_policy_report_only:
csp_header += '-Report-Only'
headers[csp_header] = policy
def _set_hsts_headers(self, headers):
criteria = [
flask.request.is_secure,
flask.request.headers.get('X-Forwarded-Proto', 'http') == 'https',
]
if not self.strict_transport_security or not any(criteria):
return
value = 'max-age={}'.format(self.strict_transport_security_max_age)
if self.strict_transport_security_include_subdomains:
value += '; includeSubDomains'
if self.strict_transport_security_preload:
value += '; preload'
headers['Strict-Transport-Security'] = value
def _set_referrer_policy_headers(self, headers):
headers['Referrer-Policy'] = self.referrer_policy
def __call__(self, **kwargs):
"""Use talisman as a decorator to configure options for a particular
view.
Only force_https, frame_options, frame_options_allow_from,
content_security_policy, content_security_policy_nonce_in
and feature_policy can be set on a per-view basis.
Example:
app = Flask(__name__)
talisman = Talisman(app)
@app.route('/normal')
def normal():
return 'Normal'
@app.route('/embeddable')
@talisman(frame_options=ALLOW_FROM, frame_options_allow_from='*')
def embeddable():
return 'Embeddable'
"""
def decorator(f):
setattr(f, 'talisman_view_options', kwargs)
return f
return decorator
try:
import secrets
def get_random_string(length): # pragma: no cover
# Note token_urlsafe returns a 'length'-byte string which is then
# base64 encoded so is longer than length, so only return last
# 'length' characters.
return secrets.token_urlsafe(length)[:length]
except ImportError: # pragma: no cover
import random
import string
rnd = random.SystemRandom()
def get_random_string(length):
allowed_chars = (
string.ascii_lowercase +
string.ascii_uppercase +
string.digits)
return ''.join(
rnd.choice(allowed_chars)
for _ in range(length))

View File

@@ -0,0 +1,344 @@
# Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
import unittest
import flask
from flask_talisman import ALLOW_FROM, DENY, NONCE_LENGTH, Talisman
HTTPS_ENVIRON = {'wsgi.url_scheme': 'https'}
def hello_world():
return 'Hello, world'
def with_nonce():
return flask.render_template_string(
'<script nonce="{{csp_nonce()}}"></script>'
)
class TestTalismanExtension(unittest.TestCase):
def setUp(self):
self.app = flask.Flask(__name__)
self.talisman = Talisman(self.app)
self.client = self.app.test_client()
self.app.route('/')(hello_world)
self.app.route('/with_nonce')(with_nonce)
def testDefaults(self):
# HTTPS request.
response = self.client.get('/', environ_overrides=HTTPS_ENVIRON)
headers = {
'X-Frame-Options': 'SAMEORIGIN',
'Strict-Transport-Security':
'max-age=31556926; includeSubDomains',
'X-Content-Type-Options': 'nosniff',
'Referrer-Policy': 'strict-origin-when-cross-origin'
}
for key, value in headers.items():
self.assertEqual(response.headers.get(key), value)
csp = response.headers.get('Content-Security-Policy')
self.assertIn('default-src \'self\'', csp)
self.assertIn('object-src \'none\'', csp)
def testForceSslOptionOptions(self):
# HTTP request from Proxy
response = self.client.get('/', headers={
'X-Forwarded-Proto': 'https'
})
self.assertEqual(response.status_code, 200)
# HTTP Request, should be upgraded to https
response = self.client.get('/')
self.assertEqual(response.status_code, 302)
self.assertTrue(response.headers['Location'].startswith('https://'))
# Permanent redirects
self.talisman.force_https_permanent = True
response = self.client.get('/')
self.assertEqual(response.status_code, 301)
# Disable forced ssl, should allow the request.
self.talisman.force_https = False
response = self.client.get('/')
self.assertEqual(response.status_code, 200)
def testForceXSSProtectionOptions(self):
self.talisman.x_xss_protection = True
# HTTP request from Proxy
response = self.client.get('/')
self.assertIn('X-XSS-Protection', response.headers)
self.assertEqual(response.headers['X-XSS-Protection'], '1; mode=block')
def testHstsOptions(self):
self.talisman.force_ssl = False
# No HSTS headers for non-ssl requests
response = self.client.get('/')
self.assertNotIn('Strict-Transport-Security', response.headers)
# Secure request with HSTS off
self.talisman.strict_transport_security = False
response = self.client.get('/', environ_overrides=HTTPS_ENVIRON)
self.assertNotIn('Strict-Transport-Security', response.headers)
# HSTS back on
self.talisman.strict_transport_security = True
# HTTPS request through proxy
response = self.client.get('/', headers={
'X-Forwarded-Proto': 'https'
})
self.assertIn('Strict-Transport-Security', response.headers)
# No subdomains
self.talisman.strict_transport_security_include_subdomains = False
response = self.client.get('/', environ_overrides=HTTPS_ENVIRON)
self.assertNotIn(
'includeSubDomains', response.headers['Strict-Transport-Security'])
# Preload
self.talisman.strict_transport_security_preload = True
response = self.client.get('/', environ_overrides=HTTPS_ENVIRON)
self.assertIn('preload', response.headers['Strict-Transport-Security'])
def testFrameOptions(self):
self.talisman.frame_options = DENY
response = self.client.get('/', environ_overrides=HTTPS_ENVIRON)
self.assertEqual(response.headers['X-Frame-Options'], 'DENY')
self.talisman.frame_options = ALLOW_FROM
self.talisman.frame_options_allow_from = 'example.com'
response = self.client.get('/', environ_overrides=HTTPS_ENVIRON)
self.assertEqual(
response.headers['X-Frame-Options'], 'ALLOW-FROM example.com')
self.talisman.frame_options = None
response = self.client.get('/', environ_overrides=HTTPS_ENVIRON)
self.assertNotIn('X-Frame-Options', response.headers)
def testContentSecurityPolicyOptions(self):
self.talisman.content_security_policy['image-src'] = '*'
response = self.client.get('/', environ_overrides=HTTPS_ENVIRON)
csp = response.headers['Content-Security-Policy']
self.assertIn("default-src 'self';", csp)
self.assertIn("object-src \'none\';", csp)
self.assertIn("image-src *", csp)
self.talisman.content_security_policy['image-src'] = [
'\'self\'',
'example.com'
]
response = self.client.get('/', environ_overrides=HTTPS_ENVIRON)
csp = response.headers['Content-Security-Policy']
self.assertIn('default-src \'self\'', csp)
self.assertIn('image-src \'self\' example.com', csp)
# string policy
self.talisman.content_security_policy = 'default-src \'foo\' spam.eggs'
response = self.client.get('/', environ_overrides=HTTPS_ENVIRON)
self.assertEqual(response.headers['Content-Security-Policy'],
'default-src \'foo\' spam.eggs')
# no policy
self.talisman.content_security_policy = False
response = self.client.get('/', environ_overrides=HTTPS_ENVIRON)
self.assertNotIn('Content-Security-Policy', response.headers)
# string policy at initialization
app = flask.Flask(__name__)
Talisman(app, content_security_policy='default-src \'foo\' spam.eggs')
response = app.test_client().get('/', environ_overrides=HTTPS_ENVIRON)
self.assertIn(
'default-src \'foo\' spam.eggs',
response.headers['Content-Security-Policy']
)
# x-content-type-options disabled
app = flask.Flask(__name__)
Talisman(app, x_content_type_options=False)
response = app.test_client().get('/', environ_overrides=HTTPS_ENVIRON)
self.assertNotIn('X-Content-Type-Options', response.headers)
# x-xss-protection disabled
app = flask.Flask(__name__)
Talisman(app, x_xss_protection=False)
response = app.test_client().get('/', environ_overrides=HTTPS_ENVIRON)
self.assertNotIn('X-XSS-Protection', response.headers)
def testContentSecurityPolicyOptionsReport(self):
# report-only policy
self.talisman.content_security_policy_report_only = True
self.talisman.content_security_policy_report_uri = \
'https://example.com'
response = self.client.get('/', environ_overrides=HTTPS_ENVIRON)
self.assertIn('Content-Security-Policy-Report-Only', response.headers)
self.assertIn(
'report-uri',
response.headers['Content-Security-Policy-Report-Only']
)
self.assertNotIn('Content-Security-Policy', response.headers)
override_report_uri = 'https://report-uri.io/'
self.talisman.content_security_policy = {
'report-uri': override_report_uri,
}
response = self.client.get('/', environ_overrides=HTTPS_ENVIRON)
self.assertIn(
'Content-Security-Policy-Report-Only', response.headers)
self.assertIn(
override_report_uri,
response.headers['Content-Security-Policy-Report-Only']
)
# exception on missing report-uri when report-only
self.assertRaises(ValueError, Talisman, self.app,
content_security_policy_report_only=True)
def testContentSecurityPolicyNonce(self):
self.talisman.content_security_policy['script-src'] = "'self'"
self.talisman.content_security_policy['style-src'] = "example.com"
self.talisman.content_security_policy_nonce_in = ['script-src']
with self.app.test_client() as client:
response = client.get('/with_nonce',
environ_overrides=HTTPS_ENVIRON)
csp = response.headers['Content-Security-Policy']
self.assertIn(
"script-src 'self' 'nonce-{}'".format(flask.request.csp_nonce),
csp
)
self.assertNotIn(
"style-src 'self'",
csp
)
self.assertNotIn(
"style-src example.com 'nonce-{}'".format(flask.request.csp_nonce),
csp
)
self.assertIn(
"style-src example.com",
csp
)
self.assertIn(
flask.request.csp_nonce,
response.data.decode("utf-8")
)
self.assertEqual(len(flask.request.csp_nonce), NONCE_LENGTH)
def testDecorator(self):
@self.app.route('/nocsp')
@self.talisman(content_security_policy=None)
def nocsp():
return 'Hello, world'
response = self.client.get('/nocsp', environ_overrides=HTTPS_ENVIRON)
self.assertNotIn('Content-Security-Policy', response.headers)
self.assertEqual(response.headers['X-Frame-Options'], 'SAMEORIGIN')
def testDecoratorForceHttps(self):
@self.app.route('/noforcehttps')
@self.talisman(force_https=False)
def noforcehttps():
return 'Hello, world'
response = self.client.get('/noforcehttps')
self.assertEqual(response.status_code, 200)
def testForceFileSave(self):
self.talisman.force_file_save = True
response = self.client.get('/', environ_overrides=HTTPS_ENVIRON)
self.assertIn('X-Download-Options', response.headers)
self.assertEqual(response.headers['X-Download-Options'], 'noopen')
def testBadEndpoint(self):
response = self.client.get('/bad_endpoint')
self.assertEqual(response.status_code, 302)
response = self.client.get('/bad_endpoint',
headers={'X-Forwarded-Proto': 'https'})
self.assertEqual(response.status_code, 404)
def testFeaturePolicy(self):
self.talisman.feature_policy['geolocation'] = '\'none\''
response = self.client.get('/', environ_overrides=HTTPS_ENVIRON)
feature_policy = response.headers['Feature-Policy']
self.assertIn('geolocation \'none\'', feature_policy)
self.talisman.feature_policy['fullscreen'] = '\'self\' example.com'
response = self.client.get('/', environ_overrides=HTTPS_ENVIRON)
feature_policy = response.headers['Feature-Policy']
self.assertIn('fullscreen \'self\' example.com', feature_policy)
# string policy at initialization
app = flask.Flask(__name__)
Talisman(app, feature_policy='vibrate \'none\'')
response = app.test_client().get('/', environ_overrides=HTTPS_ENVIRON)
self.assertIn('vibrate \'none\'', response.headers['Feature-Policy'])
def testPermissionsPolicy(self):
self.talisman.permissions_policy['geolocation'] = '()'
response = self.client.get('/', environ_overrides=HTTPS_ENVIRON)
permissions_policy = response.headers['Permissions-Policy']
self.assertIn('browsing-topics=()', permissions_policy)
self.assertIn('geolocation=()', permissions_policy)
self.talisman.permissions_policy['geolocation'] = '()'
self.talisman.permissions_policy['fullscreen'] = '(self, "https://example.com")'
response = self.client.get('/', environ_overrides=HTTPS_ENVIRON)
permissions_policy = response.headers['Permissions-Policy']
self.assertIn('browsing-topics=()', permissions_policy)
self.assertIn('geolocation=(), fullscreen=(self, "https://example.com")', permissions_policy)
# no policy
self.talisman.permissions_policy = {}
response = self.client.get('/', environ_overrides=HTTPS_ENVIRON)
permissions_policy = response.headers.get('Permissions-Policy')
self.assertEqual(None, permissions_policy)
# string policy at initialization
app = flask.Flask(__name__)
Talisman(app, permissions_policy='vibrate=(), geolocation=()')
response = app.test_client().get('/', environ_overrides=HTTPS_ENVIRON)
self.assertIn('vibrate=(), geolocation=()', response.headers['Permissions-Policy'])
def testDocumentPolicy(self):
self.talisman.document_policy['oversized-images'] = '?0'
response = self.client.get('/', environ_overrides=HTTPS_ENVIRON)
document_policy = response.headers['Document-Policy']
self.assertIn('oversized-images=?0', document_policy)
self.talisman.document_policy['oversized-images'] = '?0'
self.talisman.document_policy['document-write'] = '?0'
response = self.client.get('/', environ_overrides=HTTPS_ENVIRON)
document_policy = response.headers['Document-Policy']
self.assertIn('oversized-images=?0, document-write=?0', document_policy)
# string policy at initialization
app = flask.Flask(__name__)
Talisman(app, document_policy='oversized-images=?0, document-write=?0')
response = app.test_client().get('/', environ_overrides=HTTPS_ENVIRON)
self.assertIn('oversized-images=?0, document-write=?0', response.headers['Document-Policy'])

View File

@@ -0,0 +1 @@
pip

View File

@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View File

@@ -0,0 +1,50 @@
Metadata-Version: 2.1
Name: mfrc522
Version: 0.0.7
Summary: A library to integrate the MFRC522 RFID readers with the Raspberry Pi
Home-page: https://github.com/pimylifeup/MFRC522-python
Author: Pi My Life Up
Author-email: support@pimylifeup.com
License: UNKNOWN
Platform: UNKNOWN
Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
Classifier: Operating System :: POSIX :: Linux
Classifier: Topic :: System :: Hardware
Description-Content-Type: text/markdown
Requires-Dist: RPi.GPIO
Requires-Dist: spidev
# mfrc522
A python library to read/write RFID tags via the budget MFRC522 RFID module.
This code was published in relation to a [blog post](https://pimylifeup.com/raspberry-pi-rfid-rc522/) and you can find out more about how to hook up your MFRC reader to a Raspberry Pi there.
## Installation
Until the package is on PyPi, clone this repository and run `python setup.py install` in the top level directory.
## Example Code
The following code will read a tag from the MFRC522
```python
from time import sleep
import sys
from mfrc522 import SimpleMFRC522
reader = SimpleMFRC522()
try:
while True:
print("Hold a tag near the reader")
id, text = reader.read()
print("ID: %s\nText: %s" % (id,text))
sleep(5)
except KeyboardInterrupt:
GPIO.cleanup()
raise
```

View File

@@ -0,0 +1,13 @@
mfrc522-0.0.7.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
mfrc522-0.0.7.dist-info/LICENSE,sha256=OXLcl0T2SZ8Pmy2_dmlvKuetivmyPd5m1q-Gyd-zaYY,35149
mfrc522-0.0.7.dist-info/METADATA,sha256=DuR2cXr2dvuE-x9cZPmmVLUNe97m_kaxsMVDvSbfRns,1438
mfrc522-0.0.7.dist-info/RECORD,,
mfrc522-0.0.7.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
mfrc522-0.0.7.dist-info/WHEEL,sha256=U88EhGIw8Sj2_phqajeu_EAi3RAo8-C6zV3REsWbWbs,92
mfrc522-0.0.7.dist-info/top_level.txt,sha256=nifp5B2xtRnqBNpnzPn0QYkfXdzBkdnE0XYoBNOHT0M,8
mfrc522/MFRC522.py,sha256=BAQ0z1mfv3FOm1d0mSXl6dL-a6GC40hkBR4MvAHQcmU,12560
mfrc522/SimpleMFRC522.py,sha256=-Ebpgq4Gpb_r6eOwokU5Xpj8zLdYSmGpHKs4su1LIQc,2823
mfrc522/__init__.py,sha256=uLENBHNbvgZJUf8Spyno2Ru55zHVhzMWR-TuXuj8n4U,88
mfrc522/__pycache__/MFRC522.cpython-311.pyc,,
mfrc522/__pycache__/SimpleMFRC522.cpython-311.pyc,,
mfrc522/__pycache__/__init__.cpython-311.pyc,,

View File

@@ -0,0 +1,5 @@
Wheel-Version: 1.0
Generator: bdist_wheel (0.33.1)
Root-Is-Purelib: true
Tag: py3-none-any

View File

@@ -0,0 +1 @@
mfrc522

View File

@@ -0,0 +1,425 @@
#!/usr/bin/env python
# -*- coding: utf8 -*-
#
# Copyright 2014,2018 Mario Gomez <mario.gomez@teubi.co>
#
# This file is part of MFRC522-Python
# MFRC522-Python is a simple Python implementation for
# the MFRC522 NFC Card Reader for the Raspberry Pi.
#
# MFRC522-Python is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# MFRC522-Python is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with MFRC522-Python. If not, see <http://www.gnu.org/licenses/>.
#
import RPi.GPIO as GPIO
import spidev
import signal
import time
import logging
class MFRC522:
MAX_LEN = 16
PCD_IDLE = 0x00
PCD_AUTHENT = 0x0E
PCD_RECEIVE = 0x08
PCD_TRANSMIT = 0x04
PCD_TRANSCEIVE = 0x0C
PCD_RESETPHASE = 0x0F
PCD_CALCCRC = 0x03
PICC_REQIDL = 0x26
PICC_REQALL = 0x52
PICC_ANTICOLL = 0x93
PICC_SElECTTAG = 0x93
PICC_AUTHENT1A = 0x60
PICC_AUTHENT1B = 0x61
PICC_READ = 0x30
PICC_WRITE = 0xA0
PICC_DECREMENT = 0xC0
PICC_INCREMENT = 0xC1
PICC_RESTORE = 0xC2
PICC_TRANSFER = 0xB0
PICC_HALT = 0x50
MI_OK = 0
MI_NOTAGERR = 1
MI_ERR = 2
Reserved00 = 0x00
CommandReg = 0x01
CommIEnReg = 0x02
DivlEnReg = 0x03
CommIrqReg = 0x04
DivIrqReg = 0x05
ErrorReg = 0x06
Status1Reg = 0x07
Status2Reg = 0x08
FIFODataReg = 0x09
FIFOLevelReg = 0x0A
WaterLevelReg = 0x0B
ControlReg = 0x0C
BitFramingReg = 0x0D
CollReg = 0x0E
Reserved01 = 0x0F
Reserved10 = 0x10
ModeReg = 0x11
TxModeReg = 0x12
RxModeReg = 0x13
TxControlReg = 0x14
TxAutoReg = 0x15
TxSelReg = 0x16
RxSelReg = 0x17
RxThresholdReg = 0x18
DemodReg = 0x19
Reserved11 = 0x1A
Reserved12 = 0x1B
MifareReg = 0x1C
Reserved13 = 0x1D
Reserved14 = 0x1E
SerialSpeedReg = 0x1F
Reserved20 = 0x20
CRCResultRegM = 0x21
CRCResultRegL = 0x22
Reserved21 = 0x23
ModWidthReg = 0x24
Reserved22 = 0x25
RFCfgReg = 0x26
GsNReg = 0x27
CWGsPReg = 0x28
ModGsPReg = 0x29
TModeReg = 0x2A
TPrescalerReg = 0x2B
TReloadRegH = 0x2C
TReloadRegL = 0x2D
TCounterValueRegH = 0x2E
TCounterValueRegL = 0x2F
Reserved30 = 0x30
TestSel1Reg = 0x31
TestSel2Reg = 0x32
TestPinEnReg = 0x33
TestPinValueReg = 0x34
TestBusReg = 0x35
AutoTestReg = 0x36
VersionReg = 0x37
AnalogTestReg = 0x38
TestDAC1Reg = 0x39
TestDAC2Reg = 0x3A
TestADCReg = 0x3B
Reserved31 = 0x3C
Reserved32 = 0x3D
Reserved33 = 0x3E
Reserved34 = 0x3F
serNum = []
def __init__(self, bus=0, device=0, spd=1000000, pin_mode=10, pin_rst=-1, debugLevel='WARNING'):
self.spi = spidev.SpiDev()
self.spi.open(bus, device)
self.spi.max_speed_hz = spd
self.logger = logging.getLogger('mfrc522Logger')
self.logger.addHandler(logging.StreamHandler())
level = logging.getLevelName(debugLevel)
self.logger.setLevel(level)
gpioMode = GPIO.getmode()
if gpioMode is None:
GPIO.setmode(pin_mode)
else:
pin_mode = gpioMode
if pin_rst == -1:
if pin_mode == 11:
pin_rst = 15
else:
pin_rst = 22
GPIO.setup(pin_rst, GPIO.OUT)
GPIO.output(pin_rst, 1)
self.MFRC522_Init()
def MFRC522_Reset(self):
self.Write_MFRC522(self.CommandReg, self.PCD_RESETPHASE)
def Write_MFRC522(self, addr, val):
val = self.spi.xfer2([(addr << 1) & 0x7E, val])
def Read_MFRC522(self, addr):
val = self.spi.xfer2([((addr << 1) & 0x7E) | 0x80, 0])
return val[1]
def Close_MFRC522(self):
self.spi.close()
GPIO.cleanup()
def SetBitMask(self, reg, mask):
tmp = self.Read_MFRC522(reg)
self.Write_MFRC522(reg, tmp | mask)
def ClearBitMask(self, reg, mask):
tmp = self.Read_MFRC522(reg)
self.Write_MFRC522(reg, tmp & (~mask))
def AntennaOn(self):
temp = self.Read_MFRC522(self.TxControlReg)
if (~(temp & 0x03)):
self.SetBitMask(self.TxControlReg, 0x03)
def AntennaOff(self):
self.ClearBitMask(self.TxControlReg, 0x03)
def MFRC522_ToCard(self, command, sendData):
backData = []
backLen = 0
status = self.MI_ERR
irqEn = 0x00
waitIRq = 0x00
lastBits = None
n = 0
if command == self.PCD_AUTHENT:
irqEn = 0x12
waitIRq = 0x10
if command == self.PCD_TRANSCEIVE:
irqEn = 0x77
waitIRq = 0x30
self.Write_MFRC522(self.CommIEnReg, irqEn | 0x80)
self.ClearBitMask(self.CommIrqReg, 0x80)
self.SetBitMask(self.FIFOLevelReg, 0x80)
self.Write_MFRC522(self.CommandReg, self.PCD_IDLE)
for i in range(len(sendData)):
self.Write_MFRC522(self.FIFODataReg, sendData[i])
self.Write_MFRC522(self.CommandReg, command)
if command == self.PCD_TRANSCEIVE:
self.SetBitMask(self.BitFramingReg, 0x80)
i = 2000
while True:
n = self.Read_MFRC522(self.CommIrqReg)
i -= 1
if ~((i != 0) and ~(n & 0x01) and ~(n & waitIRq)):
break
self.ClearBitMask(self.BitFramingReg, 0x80)
if i != 0:
if (self.Read_MFRC522(self.ErrorReg) & 0x1B) == 0x00:
status = self.MI_OK
if n & irqEn & 0x01:
status = self.MI_NOTAGERR
if command == self.PCD_TRANSCEIVE:
n = self.Read_MFRC522(self.FIFOLevelReg)
lastBits = self.Read_MFRC522(self.ControlReg) & 0x07
if lastBits != 0:
backLen = (n - 1) * 8 + lastBits
else:
backLen = n * 8
if n == 0:
n = 1
if n > self.MAX_LEN:
n = self.MAX_LEN
for i in range(n):
backData.append(self.Read_MFRC522(self.FIFODataReg))
else:
status = self.MI_ERR
return (status, backData, backLen)
def MFRC522_Request(self, reqMode):
status = None
backBits = None
TagType = []
self.Write_MFRC522(self.BitFramingReg, 0x07)
TagType.append(reqMode)
(status, backData, backBits) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, TagType)
if ((status != self.MI_OK) | (backBits != 0x10)):
status = self.MI_ERR
return (status, backBits)
def MFRC522_Anticoll(self):
backData = []
serNumCheck = 0
serNum = []
self.Write_MFRC522(self.BitFramingReg, 0x00)
serNum.append(self.PICC_ANTICOLL)
serNum.append(0x20)
(status, backData, backBits) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, serNum)
if (status == self.MI_OK):
i = 0
if len(backData) == 5:
for i in range(4):
serNumCheck = serNumCheck ^ backData[i]
if serNumCheck != backData[4]:
status = self.MI_ERR
else:
status = self.MI_ERR
return (status, backData)
def CalulateCRC(self, pIndata):
self.ClearBitMask(self.DivIrqReg, 0x04)
self.SetBitMask(self.FIFOLevelReg, 0x80)
for i in range(len(pIndata)):
self.Write_MFRC522(self.FIFODataReg, pIndata[i])
self.Write_MFRC522(self.CommandReg, self.PCD_CALCCRC)
i = 0xFF
while True:
n = self.Read_MFRC522(self.DivIrqReg)
i -= 1
if not ((i != 0) and not (n & 0x04)):
break
pOutData = []
pOutData.append(self.Read_MFRC522(self.CRCResultRegL))
pOutData.append(self.Read_MFRC522(self.CRCResultRegM))
return pOutData
def MFRC522_SelectTag(self, serNum):
backData = []
buf = []
buf.append(self.PICC_SElECTTAG)
buf.append(0x70)
for i in range(5):
buf.append(serNum[i])
pOut = self.CalulateCRC(buf)
buf.append(pOut[0])
buf.append(pOut[1])
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, buf)
if (status == self.MI_OK) and (backLen == 0x18):
self.logger.debug("Size: " + str(backData[0]))
return backData[0]
else:
return 0
def MFRC522_Auth(self, authMode, BlockAddr, Sectorkey, serNum):
buff = []
# First byte should be the authMode (A or B)
buff.append(authMode)
# Second byte is the trailerBlock (usually 7)
buff.append(BlockAddr)
# Now we need to append the authKey which usually is 6 bytes of 0xFF
for i in range(len(Sectorkey)):
buff.append(Sectorkey[i])
# Next we append the first 4 bytes of the UID
for i in range(4):
buff.append(serNum[i])
# Now we start the authentication itself
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_AUTHENT, buff)
# Check if an error occurred
if not (status == self.MI_OK):
self.logger.error("AUTH ERROR!!")
if not (self.Read_MFRC522(self.Status2Reg) & 0x08) != 0:
self.logger.error("AUTH ERROR(status2reg & 0x08) != 0")
# Return the status
return status
def MFRC522_StopCrypto1(self):
self.ClearBitMask(self.Status2Reg, 0x08)
def MFRC522_Read(self, blockAddr):
recvData = []
recvData.append(self.PICC_READ)
recvData.append(blockAddr)
pOut = self.CalulateCRC(recvData)
recvData.append(pOut[0])
recvData.append(pOut[1])
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, recvData)
if not (status == self.MI_OK):
self.logger.error("Error while reading!")
if len(backData) == 16:
self.logger.debug("Sector " + str(blockAddr) + " " + str(backData))
return backData
else:
return None
def MFRC522_Write(self, blockAddr, writeData):
buff = []
buff.append(self.PICC_WRITE)
buff.append(blockAddr)
crc = self.CalulateCRC(buff)
buff.append(crc[0])
buff.append(crc[1])
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, buff)
if not (status == self.MI_OK) or not (backLen == 4) or not ((backData[0] & 0x0F) == 0x0A):
status = self.MI_ERR
self.logger.debug("%s backdata &0x0F == 0x0A %s" % (backLen, backData[0] & 0x0F))
if status == self.MI_OK:
buf = []
for i in range(16):
buf.append(writeData[i])
crc = self.CalulateCRC(buf)
buf.append(crc[0])
buf.append(crc[1])
(status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, buf)
if not (status == self.MI_OK) or not (backLen == 4) or not ((backData[0] & 0x0F) == 0x0A):
self.logger.error("Error while writing")
if status == self.MI_OK:
self.logger.debug("Data written")
def MFRC522_DumpClassic1K(self, key, uid):
for i in range(64):
status = self.MFRC522_Auth(self.PICC_AUTHENT1A, i, key, uid)
# Check if authenticated
if status == self.MI_OK:
self.MFRC522_Read(i)
else:
self.logger.error("Authentication error")
def MFRC522_Init(self):
self.MFRC522_Reset()
self.Write_MFRC522(self.TModeReg, 0x8D)
self.Write_MFRC522(self.TPrescalerReg, 0x3E)
self.Write_MFRC522(self.TReloadRegL, 30)
self.Write_MFRC522(self.TReloadRegH, 0)
self.Write_MFRC522(self.TxAutoReg, 0x40)
self.Write_MFRC522(self.ModeReg, 0x3D)
self.AntennaOn()

View File

@@ -0,0 +1,90 @@
# Code by Simon Monk https://github.com/simonmonk/
from . import MFRC522
import RPi.GPIO as GPIO
class SimpleMFRC522:
READER = None
KEY = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF]
BLOCK_ADDRS = [8, 9, 10]
def __init__(self):
self.READER = MFRC522()
def read(self):
id, text = self.read_no_block()
while not id:
id, text = self.read_no_block()
return id, text
def read_id(self):
id = self.read_id_no_block()
while not id:
id = self.read_id_no_block()
return id
def read_id_no_block(self):
(status, TagType) = self.READER.MFRC522_Request(self.READER.PICC_REQIDL)
if status != self.READER.MI_OK:
return None
(status, uid) = self.READER.MFRC522_Anticoll()
if status != self.READER.MI_OK:
return None
return self.uid_to_num(uid)
def read_no_block(self):
(status, TagType) = self.READER.MFRC522_Request(self.READER.PICC_REQIDL)
if status != self.READER.MI_OK:
return None, None
(status, uid) = self.READER.MFRC522_Anticoll()
if status != self.READER.MI_OK:
return None, None
id = self.uid_to_num(uid)
self.READER.MFRC522_SelectTag(uid)
status = self.READER.MFRC522_Auth(self.READER.PICC_AUTHENT1A, 11, self.KEY, uid)
data = []
text_read = ''
if status == self.READER.MI_OK:
for block_num in self.BLOCK_ADDRS:
block = self.READER.MFRC522_Read(block_num)
if block:
data += block
if data:
text_read = ''.join(chr(i) for i in data)
self.READER.MFRC522_StopCrypto1()
return id, text_read
def write(self, text):
id, text_in = self.write_no_block(text)
while not id:
id, text_in = self.write_no_block(text)
return id, text_in
def write_no_block(self, text):
(status, TagType) = self.READER.MFRC522_Request(self.READER.PICC_REQIDL)
if status != self.READER.MI_OK:
return None, None
(status, uid) = self.READER.MFRC522_Anticoll()
if status != self.READER.MI_OK:
return None, None
id = self.uid_to_num(uid)
self.READER.MFRC522_SelectTag(uid)
status = self.READER.MFRC522_Auth(self.READER.PICC_AUTHENT1A, 11, self.KEY, uid)
self.READER.MFRC522_Read(11)
if status == self.READER.MI_OK:
data = bytearray()
data.extend(bytearray(text.ljust(len(self.BLOCK_ADDRS) * 16).encode('ascii')))
i = 0
for block_num in self.BLOCK_ADDRS:
self.READER.MFRC522_Write(block_num, data[(i*16):(i+1)*16])
i += 1
self.READER.MFRC522_StopCrypto1()
return id, text[0:(len(self.BLOCK_ADDRS) * 16)]
def uid_to_num(self, uid):
n = 0
for i in range(0, 5):
n = n * 256 + uid[i]
return n

View File

@@ -0,0 +1,4 @@
from .MFRC522 import MFRC522
from .SimpleMFRC522 import SimpleMFRC522
name = "mfrc522"

View File

@@ -0,0 +1 @@
pip

View File

@@ -0,0 +1,276 @@
Metadata-Version: 2.4
Name: spidev
Version: 3.8
Summary: Python bindings for Linux SPI access through spidev
Home-page: http://github.com/doceme/py-spidev
Author: Volker Thoms
Author-email: unconnected@gmx.de
Maintainer: Stephen Caudle
Maintainer-email: scaudle@doceme.com
License: MIT
Classifier: Development Status :: 5 - Production/Stable
Classifier: Operating System :: POSIX :: Linux
Classifier: License :: OSI Approved :: MIT License
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 2.6
Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Software Development
Classifier: Topic :: System :: Hardware
Classifier: Topic :: System :: Hardware :: Hardware Drivers
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: license
Dynamic: license-file
Dynamic: maintainer
Dynamic: maintainer-email
Dynamic: summary
Python Spidev
=============
This project contains a python module for interfacing with SPI devices from user space via the spidev linux kernel driver.
All code is MIT licensed unless explicitly stated otherwise.
Usage
-----
```python
import spidev
spi = spidev.SpiDev()
spi.open_path(spidev_devicefile_path)
to_send = [0x01, 0x02, 0x03]
spi.xfer(to_send)
```
Settings
--------
```python
import spidev
spi = spidev.SpiDev()
spi.open_path("/dev/spidev0.0")
# Settings (for example)
spi.max_speed_hz = 5000
spi.mode = 0b01
...
```
* `bits_per_word`
* `cshigh`
* `loop` - Set the "SPI_LOOP" flag to enable loopback mode
* `no_cs` - Set the "SPI_NO_CS" flag to disable use of the chip select (although the driver may still own the CS pin)
* `lsbfirst`
* `max_speed_hz`
* `mode` - SPI mode as two bit pattern of clock polarity and phase [CPOL|CPHA], min: 0b00 = 0, max: 0b11 = 3
* `threewire` - SI/SO signals shared
* `read0` - Read 0 bytes after transfer to lower CS if cshigh == True
Methods
-------
open_path(filesystem_path)
Connects to the specified SPI device special file, following symbolic links if
appropriate (see note on deterministic SPI bus numbering in the Linux kernel
below for why this can be advantageous in some configurations).
open(bus, device)
Equivalent to calling `open_path("/dev/spidev<bus>.<device>")`. n.b. **Either**
`open_path` or `open` should be used.
readbytes(n)
Read n bytes from SPI device.
writebytes(list of values)
Writes a list of values to SPI device.
writebytes2(list of values)
Similar to `writebytes` but accepts arbitrary large lists.
If list size exceeds buffer size (which is read from `/sys/module/spidev/parameters/bufsiz`),
data will be split into smaller chunks and sent in multiple operations.
Also, `writebytes2` understands [buffer protocol](https://docs.python.org/3/c-api/buffer.html)
so it can accept numpy byte arrays for example without need to convert them with `tolist()` first.
This offers much better performance where you need to transfer frames to SPI-connected displays for instance.
xfer(list of values[, speed_hz, delay_usec, bits_per_word])
Performs an SPI transaction. Chip-select should be released and reactivated between blocks.
Delay specifies the delay in usec between blocks.
xfer2(list of values[, speed_hz, delay_usec, bits_per_word])
Performs an SPI transaction. Chip-select should be held active between blocks.
xfer3(list of values[, speed_hz, delay_usec, bits_per_word])
Similar to `xfer2` but accepts arbitrary large lists.
If list size exceeds buffer size (which is read from `/sys/module/spidev/parameters/bufsiz`),
data will be split into smaller chunks and sent in multiple operations.
close()
Disconnects from the SPI device.
The Linux kernel and SPI bus numbering and the role of udev
-----------------------------------------------------------
### Summary
If your code may interact with an SPI controller which is attached to the
system via the USB or PCI buses, **or** if you are maintaining a product which
is likely to change SoCs **or upgrade kernels** during its lifetime, then you
should consider using one or more udev rules to create symlinks to the SPI
controller spidev, and then use `open_path`, to open the device file via the
symlink in your code.
Consider allowing the end-user to configure their choice of full spidev path -
for example with the use of a command line argument to your Python script, or
an entry in a configuration file which your code reads and parses.
Additional udev actions can also set the ownership and file access permissions
on the spidev device node file (to increase the security of the system). In
some instances, udev rules may also be needed to ensure that spidev device
nodes are created in the first place (by triggering the Linux `spidev` driver
to "bind" to an underlying SPI controller).
### Detailed Information
This section provides an overview of the Linux APIs which this extension uses.
**If your software might be used on systems with non-deterministic SPI bus
numbering**, then using the `open_path` method can allow those maintaining the
system to use mechanisms such as `udev` to create stable symbolic links to the
SPI device for the correct physical SPI bus.
See the example udev rule file `99-local-spi-example-udev.rules`.
This Python extension communicates with SPI devices by using the 'spidev'
[Linux kernel SPI userspace
API](https://www.kernel.org/doc/html/next/spi/spidev.html).
'spidev' in turn communicates with SPI bus controller hardware using the
kernel's internal SPI APIs and hardware device drivers.
If the system is configured to expose a particular SPI device to user space
(i.e. when an SPI device is "bound" to the spidev driver), then the spidev
driver registers this device with the kernel, and exposes its Linux kernel SPI
bus number and SPI chip select number to user space in the form of a POSIX
"character device" special file.
A user space program (usually 'udev') listens for kernel device creation
events, and creates a file system "device node" for user space software to
interact with. By convention, for spidev, the device nodes are named
/dev/spidev<bus>.<device> is (where the *bus* is the Linux kernel's internal
SPI bus number (see below) and the *device* number corresponds to the SPI
controller "chip select" output pin that is connected to the SPI *device* 'chip
select' input pin.
The Linux kernel **may assign SPI bus numbers to a system's SPI controllers in
a non-deterministic way.** In some hardware configurations, the SPI bus number
of a particular hardware peripheral is:
- Not guaranteed to remain constant between different Linux kernel versions.
- Not guaranteed to remain constant between successive boots of the same kernel
(due to race conditions during boot-time hardware enumeration, or dynamic
kernel module loading).
- Not guaranteed to match the hardware manufacturer's SPI bus numbering scheme.
In the case of SPI controllers which are themselves connected to the system via
buses that are subject to hot-plug (such as USB, Thunderbolt, or PCI), the
SPI bus number should usually be expected to be non-deterministic.
The supported Linux mechanism which allows user space software to identify the
correct hardware, it to compose "udev rules" which create stable symbolic links
to device files. For example, most Linux distributions automatically create
symbolic links to allow identification of block storage devices e.g. see the
output of `ls -alR /dev/disk`.
`99-local-spi-example-udev.rules` included with py-spidev includes example udev
rules for creating stable symlink device paths (for use with `open_path`).
e.g. the following Python code could be used to communicate with an SPI device
attached to chip-select line 0 of an individual FTDI FT232H USB to SPI adapter
which has the USB serial number "1A8FG636":
```
#!/usr/bin/env python3
import spidev
spi = spidev.SpiDev()
spi.open_path("/dev/spi/by-path/usb-sernum-1A8FG636-cs-0")
# TODO: Useful stuff here
spi.close()
```
In the more general case, the example udev file should be modified as
appropriate to your needs, renamed to something descriptive of the purpose
and/or project, and placed in `/etc/udev/rules.d/` (or `/lib/udev/rules.d/` in
the case of rules files included with operating system packages).
Changelog
---------
3.8
====
* Added open_path method to accommodate dynamic SPI bus number allocation
3.7
===
* Fixed installation deprecation warning
3.6
====
* Added read0 flag to enable reading 0 bytes after transfer to lower CS when cshigh == True
3.5
====
* Fixed memory leaks
3.4
=====
* Changed license to MIT
3.0.1
=====
* Fixed README.md and CHANGELOG.md formatting, hopefully
3.0
===
* Memset fix recommended by Dougie Lawson
* Fixes for Kernel 3.15+ from https://github.com/chrillomat/py-spidev
* Fixes for Python 3/2 compatibility.
* Added subclassing support - https://github.com/doceme/py-spidev/issues/10
2.0
===
Code sourced from http://elk.informatik.fh-augsburg.de/da/da-49/trees/pyap7k/lang/py-spi
and modified.
Pre 2.0
=======
spimodule.c originally uathored by Volker Thoms, 2009.

View File

@@ -0,0 +1,7 @@
spidev-3.8.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
spidev-3.8.dist-info/METADATA,sha256=B98zilX1SKoe_rOFghsGyaV852GHoQyWpmF52GGiaIc,9262
spidev-3.8.dist-info/RECORD,,
spidev-3.8.dist-info/WHEEL,sha256=kOE5YCW3k8HyUKo2VIIfZUnbnbVy91mH1mbQOEtImFE,104
spidev-3.8.dist-info/licenses/LICENSE,sha256=UQEpvIF0wPqB-m1lNpHRvV01VffziXnsRbX8W7_1N3s,1092
spidev-3.8.dist-info/top_level.txt,sha256=44pvfbj3ltXTNIZtsGBpy8p3g-DJtpS2CZDMFrXY-es,7
spidev.cpython-311-x86_64-linux-gnu.so,sha256=56ng5Hz1d3c9RGEsz1N1QNEWZKD_cFaVv4blWfd-dn4,92528

View File

@@ -0,0 +1,5 @@
Wheel-Version: 1.0
Generator: setuptools (82.0.1)
Root-Is-Purelib: false
Tag: cp311-cp311-linux_x86_64

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2019 Stephen Caudle <stephen@caudle.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1 @@
spidev