summaryrefslogtreecommitdiff
path: root/LearnMapKit/FlighState.swift
blob: a86a66031622d36f5304f6f7b499da52df571fda (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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
//
//  FlighState.swift
//  LearnMapKit
//
//  Created by Jacky Jack on 30/06/2024.
//

import Foundation
import Collections
import SwiftUI

class FlightTracker:  Identifiable {
    var last_time_seen: Int = 0
    var ICAOaddress = 0
    var ICAOName_avaliable = false
    //@Published var ICAOName = ""
    var ICAOName = ""
    var Position_avaliable = false
    @Published var long:Double = 0.0
    //var long:Double = 0.0
    @Published var lat:Double = 0.0
    //var lat:Double = 0.0
    var FromTo_avaliable = false
    var flightFrom:String = ""
    var flightTo:String = ""
    var id: String { String(ICAOaddress) }
    
    
    enum CodingKeys: String, CodingKey {
        case ICAOName
        case long
        case lat
    }
    
    func encode(to encoder: any Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(self.ICAOName, forKey: .ICAOName)
        try container.encode(self.long, forKey: .long)
        try container.encode(self.lat, forKey: .lat)
    }
}



class FlightState: ObservableObject {
    var timer: Timer?
    //default location currently for testing
    var fromFile: Bool = false
    var idx_flight:[Int:Int] = [:]
    @Published var flight:[FlightTracker] = []
    
    //configuration options
    var sourceFile = false
    var default_file_path = "/Users/jackyjack/Downloads/2024_05_27_raw_adsb.txt"
    var process_per_second = 120
    
    var sourceDump1090Server = true
    var dump1090address = "192.168.4.233"
    var dump1090port = 30002
    
    init() {
        print("Init")
        var count = 0
        
        //let ADSBtask = ADSBFileRunner(filename: "")
        
        //let adsb_net = ADSBNetRunner(address: dump1090address, port: dump1090port)
        
        //if sourceFile {
        //    startSourceFile()
        //}
        
        //if sourceDump1090Server {
        //    startDump1090()
        //}
    }
    
    init(filename: String) {
        fileMode(filepath: filename)
        startSourceFile()
    }
    
    init(hostname: String, port: Int) {
        networkMode(hostname: hostname, port: port)
        startDump1090()
    }
    
    func networkMode(hostname: String, port: Int) {
        print("network mode")
        self.dump1090address = hostname
        self.dump1090port = port
        self.sourceDump1090Server = true
        self.sourceFile = false
    }
    
    func networkMode(netconfig: Binding<NetworkConfigure>) {
        print("network mode")
        self.dump1090address = netconfig.servername.wrappedValue
        self.dump1090port = netconfig.serverport.wrappedValue
        self.sourceDump1090Server = true
        self.sourceFile = false
    }
    
    func fileMode(filepath: String) {
        print("file mode")
        self.default_file_path = filepath
        self.sourceFile = true
        self.sourceDump1090Server = false
    }
    
    func defaultMode() {
        print("default mode")
        self.sourceDump1090Server = true
        self.sourceFile = false
    }
    
    func defaultMode(hostname: String, port: Int) {
        print("default mode net")
        self.sourceDump1090Server = true
        self.dump1090address = hostname
        self.dump1090port = port
        self.sourceFile = false
    }
    
    func startSourceFile() {
        print("Start reading ADSB messages from \(self.default_file_path)")
        let adsb_file = ADSBFileRunner(filename: self.default_file_path)
        DispatchQueue.global(qos: .background).sync {
            print("Open file")
            adsb_file.openFile()
            adsb_file.readFile()
        }
        
        DispatchQueue.global(qos: .background).async {
            print("Start decoding data")
            adsb_file.decodeFromFile()
            print("Stop decoding data")
        }
        
        //once a second read some data from decoded queue
        timer = Timer.scheduledTimer(
            withTimeInterval: 1,
            repeats: true
        ) { _ in
            //get the 10 entries if there is
            if adsb_file.jobDone() {
                print("Decoding done let get some data \(adsb_file.getCount())")
                //if adsb_file
                if adsb_file.getCount() > self.process_per_second {
                    let data = adsb_file.getPlainData(self.process_per_second)
                    //print(data.getCount())
                    for _ in 0..<data.getCount() {
                        let nextTag = data.getNextTag()
                        if nextTag == DataStreamType.ADSB_ALTITUDE {
                            let _ = data.getAltitude()
#warning("Implement this")
                        } else if (nextTag == DataStreamType.ADSB_ICAO) {
                            let icao = data.getIcaoName()
                            print("Tag icao \(icao) count:\(data.icaoArray.count)")
                            self.addIcaoName(icao.address, icao.ICAOname)
                        } else if (nextTag == DataStreamType.ADSB_LOCATION) {
                            print("tag location")
                            let loc = data.getLocation()
                            self.addLocation(loc.address, loc.lat, loc.long)
                        }
                    }
                    
                } else {
                    print("Data stream is empty")
                }
            }
        }
    }
    
    func startDump1090() {
        print("Start reading ADSB messages from \(dump1090address):\(dump1090port)")
        //let ADSBClient = NetADSBDecoder(host: "192.168.4.201", port: 30002)
        //let ADSBClient = ADSBNetRunner(address: "192.168.4.201", port: 30002)
        let ADSBClient = ADSBNetRunner(address: dump1090address, port: dump1090port)
        timer = Timer.scheduledTimer(
            withTimeInterval: 1,
            repeats: true
        ) { _ in
            //print("Timer drain queue")
            //print("\(ADSBClient.msgarray.message_array.count)")
            /*if ADSBClient.msgarray.message_array.count > 0 {
                print(ADSBClient.msgarray.message_array.count)
                for i in 0..<ADSBClient.msgarray.message_array.count {
                    print(ADSBClient.msgarray.message_array.popLast()!,terminator: "")
                }
            }*/
            if ADSBClient.adsb_tag_stream.getCount() > 0 {
                //print("Process onse a second")
                for _ in 0..<ADSBClient.adsb_tag_stream.getCount() {
                    let nextTag = ADSBClient.adsb_tag_stream.getNextTag()
                    if nextTag == DataStreamType.ADSB_ALTITUDE {
                        let _ = ADSBClient.adsb_tag_stream.getAltitude()
#warning("Implement this")
                    } else if (nextTag == DataStreamType.ADSB_ICAO) {
                        let icao = ADSBClient.adsb_tag_stream.getIcaoName()
                        print("Tag icao \(icao) count:\(ADSBClient.adsb_tag_stream.icaoArray.count)")
                        self.addIcaoName(icao.address, icao.ICAOname)
                    } else if (nextTag == DataStreamType.ADSB_LOCATION) {
                        print("Tag location")
                        let loc = ADSBClient.adsb_tag_stream.getLocation()
                        self.addLocation(loc.address, loc.lat, loc.long)
                    }
                }
            }
        }
        /*
        DispatchQueue.global(qos: .background).async {
            do {
                try ADSBClient.start()
            } catch let error {
                print("Error: \(error.localizedDescription)")
                ADSBClient.stop()
            }
        }*/
        do {
            print("Start")
            try ADSBClient.start()
        } catch let error {
            print("Error: \(error.localizedDescription)")
            ADSBClient.stop()
        }
    }
    
    func run() {
        print("run")
        if self.sourceFile {
            startSourceFile()
        } else if self.sourceDump1090Server {
            startDump1090()
        }
    }
    
    func addLocation(_ address: Int, _ lat: Double, _ long: Double) {
        /*
        //usign as dictionary
        if flight[address] == nil {
            flight[address] = FlightTracker()
            flight[address]?.last_time_seen = Int(Date().timeIntervalSince1970)
            flight[address]?.Position_avaliable = true
            flight[address]?.lat = lat
            flight[address]?.long = long
            print("new location")
            return
        } else {
            if let f = flight[address] {
                f.last_time_seen = Int(Date().timeIntervalSince1970)
                f.Position_avaliable = true
                f.lat = lat
                f.long = long
                if f.ICAOName_avaliable {
                    print("Update location name: \(f.ICAOName) lat:\(f.lat) long:\(f.long)")
                } else {
                    print("Update location addr: \(address) lat:\(f.lat) long:\(f.long)")
                }
                return
            }
            
        }*/
        //using as array
        /*
        if self.idx_flight[address] == nil {
            let f = FlightTracker()
            f.ICAOaddress = address
            f.last_time_seen = Int(Date().timeIntervalSince1970)
            f.Position_avaliable = true
            f.lat = lat
            f.long = long
            flight.append(f)
            print(idx_flight[address])
            idx_flight[address] = flight.count-1
            print("add new location \(address) ")
        } else {
            if let idx = idx_flight[address] {
                let f = flight[idx]
                f.last_time_seen = Int(Date().timeIntervalSince1970)
                f.Position_avaliable = true
                f.lat = lat
                f.long = long
                if f.ICAOName_avaliable {
                    print("Update location name: \(f.ICAOName) lat:\(f.lat) long:\(f.long)")
                } else {
                    print("Update location addr: \(address) lat:\(f.lat) long:\(f.long)")
                }
                return
            }
        }*/
        if self.idx_flight[address] == nil {
            let f = FlightTracker()
            f.ICAOaddress = address
            f.last_time_seen = Int(Date().timeIntervalSince1970)
            f.Position_avaliable = true
            f.lat = lat
            f.long = long
            flight.append(f)
            //print(idx_flight[address])
            idx_flight[address] = flight.count-1
            print("add new location \(address) ")
        } else {
            if let idx = idx_flight[address] {
                print("Flights loc \(flight.count)")
                let f = flight[idx]
                f.last_time_seen = Int(Date().timeIntervalSince1970)
                f.Position_avaliable = true
                f.lat = lat
                f.long = long
                if f.ICAOName_avaliable {
                    print("Update location name: \(f.ICAOName) lat:\(f.lat) long:\(f.long)")
                } else {
                    print("Update location addr: \(address) lat:\(f.lat) long:\(f.long)")
                }
                flight.append(f)
                return
            }
        }
        //using as List
        //print("No update?")
    }
    
    func addIcaoName(_ address: Int, _ icaoname: String) {
        /*
        if flight[address] == nil {
            flight[address] = FlightTracker()
            flight[address]?.last_time_seen = Int(Date().timeIntervalSince1970)
            flight[address]?.ICAOName_avaliable = true
            flight[address]?.ICAOName = icaoname
            print("new flight name added \(icaoname)")
            return
        } else {
            if let f = flight[address] {
                f.last_time_seen = Int(Date().timeIntervalSince1970)
                if  f.ICAOName_avaliable == false {
                    f.ICAOName_avaliable = true
                    f.ICAOName = icaoname
                    print("flight timestamp updated")
                    return
                }
            }
        }*/
        if idx_flight[address] == nil {
            let f = FlightTracker()
            f.ICAOaddress = address
            f.last_time_seen = Int(Date().timeIntervalSince1970)
            f.ICAOName_avaliable = true
            f.ICAOName = icaoname
            flight.append(f)
            idx_flight[address] = flight.count-1
        } else {
            if let idx = idx_flight[address] {
                print("Flights \(flight.count)")
                //let f = flight[idx]
                /*f.last_time_seen = Int(Date().timeIntervalSince1970)
                if  f.ICAOName_avaliable == false {
                    f.ICAOName_avaliable = true
                    f.ICAOName = icaoname
                    print("flight timestamp updated")
                    return
                }*/
            }
        }
        print("icao name")
    }
    
    func addNewFlight() {
        
    }
    
    //loop over and if expired then remove
    func removeExpiredFlight() {
        /*
        for (address,el) in self.flight {
            //if on the map more then 1 minute
            if el.last_time_seen+60 < Int(Date().timeIntervalSince1970) {
                self.flight.removeValue(forKey: address)
            }
        }
        */
    }
}