|
| 1 | +/* |
| 2 | + * Copyright (c) 2025 Moddable Tech, Inc. |
| 3 | + * |
| 4 | + * This file is part of the Moddable SDK. |
| 5 | + * |
| 6 | + * This work is licensed under the |
| 7 | + * Creative Commons Attribution 4.0 International License. |
| 8 | + * To view a copy of this license, visit |
| 9 | + * <http://creativecommons.org/licenses/by/4.0>. |
| 10 | + * or send a letter to Creative Commons, PO Box 1866, |
| 11 | + * Mountain View, CA 94042, USA. |
| 12 | + * |
| 13 | + */ |
| 14 | + |
| 15 | +import Timer from "timer"; |
| 16 | + |
| 17 | +const mdns = new (device.network.mdns.io)(device.network.mdns); |
| 18 | + |
| 19 | +const claim = mdns.claim({ |
| 20 | + host: "a-server", |
| 21 | + onReady() { |
| 22 | + trace(`a-server claimed\n`); |
| 23 | + }, |
| 24 | + onError() { |
| 25 | + trace("couldn't claim a-server\n"); |
| 26 | + } |
| 27 | +}); |
| 28 | + |
| 29 | +const ad = mdns.advertise({ |
| 30 | + serviceType: "_http._tcp", |
| 31 | + instanceName: "419 Web Server", |
| 32 | + host: "a-server", |
| 33 | + port: 8080, |
| 34 | + txt: new Map([ |
| 35 | + ["home", "/index.html"] |
| 36 | + ]), |
| 37 | + onError(error) { |
| 38 | + trace("advertise failed\n"); |
| 39 | + } |
| 40 | +}); |
| 41 | +ad.counter = 0; |
| 42 | + |
| 43 | +Timer.repeat(() => { |
| 44 | + ad.updateTXT(new Map([ |
| 45 | + ["home", "/index.html"], |
| 46 | + ["counter", (++ad.counter).toString()], |
| 47 | + ])); |
| 48 | +}, 1000) |
| 49 | + |
| 50 | +mdns.discover({ |
| 51 | + serviceType: "_airplay._tcp", |
| 52 | + onFound(service) { |
| 53 | + trace(`Found: "${service.name}" on ${service.host} @ ${service.address}:${service.port}\n`); |
| 54 | + this.history ??= new Map; |
| 55 | + const txt = service.txt ?? new Map; |
| 56 | + this.history.set(service.host, txt); |
| 57 | + for (const [key, value] of txt) |
| 58 | + trace(` ${key}:${value}\n`); |
| 59 | + }, |
| 60 | + onUpdate(service) { |
| 61 | + trace(`Update: ${service.name}\n`); |
| 62 | + |
| 63 | + const previous = this.history.get(service.host); |
| 64 | + const txt = service.txt ?? new Map; |
| 65 | + this.history.set(service.host, txt); |
| 66 | + |
| 67 | + for (const [key, value] of previous) { |
| 68 | + if (!txt.has(key)) |
| 69 | + trace(` removed ${key}:${value}\n`); |
| 70 | + } |
| 71 | + for (const [key, value] of txt) { |
| 72 | + if (!previous.has(key)) |
| 73 | + trace(` added ${key}:${value}\n`); |
| 74 | + } |
| 75 | + for (const [key, value] of txt) { |
| 76 | + if (previous.has(key) && (previous.get(key) !== txt.get(key))) |
| 77 | + trace(` changed ${key} from ${previous.get(key)} to ${txt.get(key)}\n`); |
| 78 | + } |
| 79 | + }, |
| 80 | + onLost(service) { |
| 81 | + trace(`Lost: ${service.name}\n`); |
| 82 | + this.history.delete(service.host); |
| 83 | + }, |
| 84 | + onError(error) { |
| 85 | + trace(`failed\n`); |
| 86 | + } |
| 87 | +}); |
0 commit comments