import subprocess
import csv
import time

def get_wifi_signal():
    scan_output = subprocess.check_output(['sudo', 'iwlist', 'wlan0', 'scan']).decode('utf-8')
    return scan_output

def parse_signal_strength(scan_output):
    signal_strengths = []
    for line in scan_output.split('\n'):
        if "Signal level=" in line:
            strength = line.split("Signal level=")[1].split(" ")[0]
            signal_strengths.append(int(strength))
    return signal_strengths

def collect_data(file_path, location_id):
    with open(file_path, 'a', newline='') as csvfile:
        fieldnames = ['Location', 'SignalStrength']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        if csvfile.tell() == 0:
            writer.writeheader()
        scan_output = get_wifi_signal()
        signal_strengths = parse_signal_strength(scan_output)
        for strength in signal_strengths:
            writer.writerow({'Location': location_id, 'SignalStrength': strength})

# Example usage
location_id = 'Showcase1'  # Change to unique ID for each location
file_path = 'wifi_signals.csv'
while True:
    collect_data(file_path, location_id)
    time.sleep(60)  # Collect data every minute
