summaryrefslogtreecommitdiff
path: root/Radio/HW/AirSpy/AirSpy.swift
blob: 25f5b0b9a99ef9fddadd91ea07d626e52487a7cf (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
//
//  AirSpy.swift
//  PrySDR
//
//  Created by Jacky Jack on 25/10/2024.
//
import libairspy

enum AirspyHFError: Error {
    case InvalidDevice
}

/// Wrapper for libairspy library
class AirSpy {
    
    var dev:UnsafeMutablePointer<airspy_device_t>? = .allocate(capacity: 1)
    var sample_rates:[UInt32] = []
    
    init(serialno: UInt64) throws {
        let ret = airspy_open_sn(&dev, serialno)
        if (ret != AIRSPY_SUCCESS.rawValue) {
            throw AirspyHFError.InvalidDevice
        }
    }
    
    /// will open first device it can find
    init() throws  {
        let ret = airspy_open(&dev)
        if ret != AIRSPY_SUCCESS.rawValue {
            print("Couldnt open airspy device")
            throw AirspyHFError.InvalidDevice
        }
    }

    func getSampleRates() -> [UInt32] {
        if sample_rates.count == 0 {
            
            let nscount: UnsafeMutablePointer<UInt32> = .allocate(capacity: 1)
            ret = airspy_get_samplerates(dev, nscount, 0)
            
            let samplerates_buf:UnsafeMutableBufferPointer<UInt32> = .allocate(capacity: Int(nscount.pointee))
            let rawPointer = UnsafeMutablePointer<UInt32>?(samplerates_buf.baseAddress!)
            ret = airspy_get_samplerates(dev, rawPointer, nscount.pointee)
            
            sample_rates = []
            for i in 0..<Int(nscount.pointee) {
                sample_rates.append(samplerates_buf[i])
            }
        }
        return sample_rates
    }
    
    func setSampleRate(_ samplerate: UInt32 ) -> Int32 {
        return airspy_set_samplerate(dev, samplerate)
    }
    
    func rfBias(_ rfbias: UInt8) -> Int32 {
        return airspy_set_rf_bias(dev, rfbias)
    }
    
    func VGAGain(_ vgagain: UInt8) -> Int32 {
        return airspy_set_vga_gain(dev, vgagain)
    }
    
    func mixerGain(_ gain: UInt8) -> Int32 {
        return airspy_set_mixer_gain(dev, gain)
    }
    
    func lnaGain(_ gain: UInt8) -> Int32 {
        return airspy_set_lna_gain(dev, gain)
    }
    
    func startRx(_ callback: airspy_sample_block_cb_fn) -> Int32 {
        return airspy_start_rx(dev, callback, nil)
    }
    
    func stopRx() -> Int32 {
        return airspy_stop_rx(dev)
    }
    
    func setFrequency(_ freq: UInt32) -> Int32 {
        return airspy_set_freq(dev, freq)
    }
    
    func isStreaming() -> Int32 {
        return airspy_is_streaming(dev)
    }
    
    func close() -> Int32 {
        return airspy_close(dev)
    }
}