#!/usr/bin/env python3
"""
Parse Saleae Logic Analyzer digital channels to extract RFID data
"""
import struct
import sys

def parse_digital_bin(filename):
    """Parse a Saleae digital channel binary file"""
    transitions = []
    
    with open(filename, 'rb') as f:
        # Saleae digital files contain time stamps and state changes
        # Format: each transition is 8 bytes (timestamp) + state info
        data = f.read()
        
        # Try to parse as simple state transitions
        i = 0
        while i < len(data):
            if i + 8 <= len(data):
                # Read 8-byte timestamp (little-endian double)
                timestamp = struct.unpack('<d', data[i:i+8])[0]
                # The next byte might be the state
                if i + 9 <= len(data):
                    state = data[i+8]
                    transitions.append((timestamp, state))
                    i += 9
                else:
                    break
            else:
                break
    
    return transitions

def extract_bytes_from_transitions(transitions, sample_rate=25000000):
    """Extract byte data from digital transitions"""
    bytes_found = []
    
    # Look for patterns that might be data bytes
    # Typically SPI or serial communication will have regular transitions
    
    if len(transitions) < 8:
        return []
    
    # Try to extract bytes from the transitions
    current_byte = 0
    bit_count = 0
    
    for i in range(1, len(transitions)):
        prev_time, prev_state = transitions[i-1]
        curr_time, curr_state = transitions[i]
        
        # If state is 1, add to byte
        if curr_state & 1:
            current_byte |= (1 << bit_count)
        
        bit_count += 1
        
        if bit_count == 8:
            bytes_found.append(current_byte)
            current_byte = 0
            bit_count = 0
    
    return bytes_found

def main():
    channels = []
    
    for i in range(4):
        filename = f"extracted/digital-{i}.bin"
        print(f"[*] Parsing {filename}...")
        
        try:
            transitions = parse_digital_bin(filename)
            print(f"    Found {len(transitions)} transitions")
            
            if transitions:
                print(f"    First few transitions:")
                for j, (time, state) in enumerate(transitions[:10]):
                    print(f"      {j}: time={time:.10f}s, state={state}")
                
                # Try to extract bytes
                extracted_bytes = extract_bytes_from_transitions(transitions)
                if extracted_bytes:
                    print(f"    Extracted {len(extracted_bytes)} bytes:")
                    hex_str = ' '.join(f'{b:02x}' for b in extracted_bytes[:64])
                    print(f"      {hex_str}")
                
            channels.append(transitions)
        except Exception as e:
            print(f"    Error: {e}")
    
    # Try to decode as SPI or I2C
    print("\n[*] Analyzing protocol...")
    
    # Common RFID protocols use SPI
    # Look for patterns in the data
    
if __name__ == "__main__":
    main()
