import cv2
from pyzbar import pyzbar
import sqlite3
import time
from twilio.rest import Client
# Twilio setup (replace with your info)
TWILIO_SID = 'your_sid'
TWILIO_TOKEN = 'your_token'
WHATSAPP_FROM = 'whatsapp:+14155238886'
WHATSAPP_TO = 'whatsapp:+1234567890'
client = Client(TWILIO_SID, TWILIO_TOKEN)
# Database setup
conn = sqlite3.connect('vehicle_movements.db')
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS movements (
id INTEGER PRIMARY KEY AUTOINCREMENT,
vehicle TEXT,
from_location TEXT,
to_location TEXT,
timestamp TEXT
)
''')
conn.commit()
# Keep track of vehicle locations
vehicles = {}
def send_whatsapp(msg):
try:
client.messages.create(body=msg, from_=WHATSAPP_FROM, to=WHATSAPP_TO)
print("WhatsApp message sent.")
except Exception as e:
print(f"Error: {e}")
def record_movement(vehicle, from_loc, to_loc):
timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
cursor.execute('INSERT INTO movements (vehicle, from_location, to_location, timestamp) VALUES (?, ?, ?, ?)',
(vehicle, from_loc, to_loc, timestamp))
conn.commit()
def scan_codes(frame):
decoded = pyzbar.decode(frame)
data_dict = {}
for obj in decoded:
text = obj.data.decode('utf-8')
if ':' in text:
key, val = text.split(':', 1)
data_dict[key.strip().upper()] = val.strip()
return data_dict
def main():
cap = cv2.VideoCapture(0)
print("Press 'q' to quit.")
while True:
ret, frame = cap.read()
if not ret:
break
data = scan_codes(frame)
# Detect vehicle
if 'VEHICLE' in data:
vehicle_id = data['VEHICLE']
# Initialize if new
if vehicle_id not in vehicles:
vehicles[vehicle_id] = None
print(f"Detected vehicle: {vehicle_id}")
# Detect location
if 'LOCATION' in data:
location = data['LOCATION']
# Update vehicle's current location
if 'vehicle_id' in locals():
prev_loc = vehicles.get(vehicle_id)
vehicles[vehicle_id] = location
if prev_loc and prev_loc != location:
# Record movement
record_movement(vehicle_id, prev_loc, location)
msg = f"Vehicle {vehicle_id} moved from {prev_loc} to {location}."
send_whatsapp(msg)
print(msg)
cv2.imshow('Scanner', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
conn.close()
if __name__ == "__main__":
main()