chakokuのブログ(rev4)

テック・コミック・ごくまれにチャリ

Swift NWConnectionGroupのサンプル

MulticastでEchonetLite (GET / 自ノードインスタンスリスト) 投げて機器からUnicast(自ノードインスタンスリスト)で戻ってくるパケットを受け取るサンプル。このソースでは受信できない、(Multicastで受け取る実装になっているから)

import Foundation
import Network

var EL_HEADER:[UInt8] = [0x10, 0x81]
var EL_TID:[UInt8] = [0x00, 0x00]
var EOJ_CONTROLLER:[UInt8] = [0x05, 0xff, 0x01]
var EOJ_NODEPROFILE:[UInt8] = [0x0e, 0xf0, 0x01]

let ESV_GETI:UInt8 = 0x60
let ESV_GETC:UInt8 = 0x61
let ESV_GET:UInt8 = 0x62
let ESV_INFREQ:UInt8 = 0x63
let ESV_SETGET:UInt8 = 0x6E
let EPC_INSLSTNTFPROP:UInt8 = 0xD5
let EPC_INSLIST:UInt8 = 0xD6
let EPC_STATE:UInt8 = 0x80

func device_scan(){

guard let multicast = try? NWMulticastGroup(for:
    [ .hostPort(host: "224.0.23.0", port: 3610)], disableUnicast: false)
    else { fatalError("error in Muticast") }

let group = NWConnectionGroup(with: multicast, using: .udp)

group.setReceiveHandler(maximumMessageSize: 1024, rejectOversizedMessages: true) { (message, content, isComplete) in
    print("Received message from \(String(describing: message.remoteEndpoint))")
    //let message = String(data: content, encoding: .utf8)
    //let message = Data(content, encoding: .utf8)
    print(content)
    //let sendContent = Data("ack".utf8)
    //message.reply(content: sendContent)
}
group.stateUpdateHandler = { (newState) in
    print("Group entered state \(String(describing: newState))")
    switch newState {
    case .ready:
        print("ready")

        var msg:[UInt8] = EL_HEADER + EL_TID + EOJ_CONTROLLER + EOJ_NODEPROFILE
        //msg.append(contentsOf:[ESV_INFREQ, 0x01, EPC_INSLSTNTFPROP, 0x00])
        msg.append(contentsOf:[ESV_GET, 0x01, EPC_INSLIST, 0x00])
        let groupSendContent = Data(msg)  // .data(using: .utf8)

        print("send...UDP")
        group.send(content: groupSendContent) { (error)  in
            print("Send complete with error \(String(describing: error))")
        }
    case .waiting(let error):
        print("waiting")
        print(error)
    case .setup:
        print("setup")
    case .cancelled:
        print("cancelled")
    case .failed:
        print("failed")
    //case .preparing:
    //    print("preparing")
    default:
        print("default")
    }
}
let queue = DispatchQueue(label: "ExampleNetwork")
//print(group.isUnicastDisabled)
group.start(queue: queue)
//group.start(queue: .main)
sleep(10)
group.cancel()
sleep(5)
print("bye")
}

device_scan()