Last active
August 26, 2021 03:26
-
-
Save Pranit-Harekar/97840a9cbcf7bb3c55154275efb3772e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import Foundation | |
| import BrightFutures | |
| import Result | |
| import CocoaAsyncSocket | |
| // "CocoaAsyncSocket" is a socket library | |
| // Ref: https://github.com/robbiehanson/CocoaAsyncSocket | |
| class DCDirectTerminalDetector: NSObject, GCDAsyncUdpSocketDelegate { | |
| static let queue = DispatchQueue( | |
| label: "com.app.DCDirectTerminalDetector", attributes: [] | |
| ) | |
| var socket: GCDAsyncUdpSocket! | |
| let broadcastPort: UInt16 = 9001 | |
| let broadcastHost: String = "255.255.255.255" | |
| let broadcastTimeout = 5.0 | |
| override init() { | |
| super.init() | |
| socket = GCDAsyncUdpSocket( | |
| delegate: self, | |
| delegateQueue: DCDirectTerminalDetector.queue | |
| ) | |
| } | |
| func broadcastMessage() { | |
| do { | |
| try socket.bind(toPort: broadcastPort) | |
| try socket.enableBroadcast(true) | |
| try socket.beginReceiving() | |
| // The one on the label- | |
| // IPSN: 3201141914844303 | |
| // IPSN: 3011087720077752 | |
| // The one on the device- | |
| // S/N: 183567303261086003685327 | |
| // S/N: 210787313031070220075924 | |
| let data = "Who has 3011087720077752".data(using: .utf8)! | |
| socket.send(data, toHost: broadcastHost, port: broadcastPort, withTimeout: broadcastTimeout, tag: 0) | |
| } catch { | |
| print("Failed to send message \(error)") | |
| } | |
| } | |
| // MARK:- GCDAsyncUdpSocketDelegate | |
| func udpSocket(_ sock: GCDAsyncUdpSocket, didReceive data: Data, fromAddress address: Data, withFilterContext filterContext: Any?) { | |
| let parsedData = String(data: data, encoding: .utf8) | |
| let parsedAddress = String(data: address, encoding: .utf8) | |
| Log.debug("parsedData \(String(describing: parsedData))") // Output- parsedData Optional("Who has 3011087720077752") | |
| Log.debug("parsedAddress \(String(describing: parsedAddress))") // Output- parsedAddress nil | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment