zeroconf #6738
|
Add the zeroconf package to implement mDNS functionality |
Replies: 1 comment
|
InstallationJust add [project]
dependencies = ["flet", "zeroconf"]
[tool.flet.android]
dependencies = ["pyjnius"]
[tool.flet.android.permission]
"android.permission.CHANGE_WIFI_MULTICAST_STATE" = true
"android.permission.ACCESS_NETWORK_STATE" = true
[tool.flet.ios.info]
NSLocalNetworkUsageDescription = "Finds and announces services on your local network."
NSBonjourServices = ["_demo._tcp"] # list every service type you browse( Minimal exampleRegisters a service and browses for that type, so it always discovers at least itself and the list is never empty: import os, socket
import flet as ft
def main(page: ft.Page):
page.title = "mDNS demo"
found = ft.ListView(expand=True)
page.add(ft.Text("Discovered _demo._tcp services:", weight=ft.FontWeight.BOLD), found)
if page.platform == ft.PagePlatform.ANDROID:
# Wi-Fi chipsets drop incoming multicast unless the app holds a MulticastLock —
# without this, zeroconf can send but hears (almost) nothing. Keep the lock
# referenced for the app's lifetime; release it when you stop discovery.
from jnius import autoclass
Context = autoclass("android.content.Context")
activity = autoclass(os.getenv("MAIN_ACTIVITY_HOST_CLASS_NAME")).mActivity
wifi = activity.getApplicationContext().getSystemService(Context.WIFI_SERVICE)
page.data = lock = wifi.createMulticastLock("zeroconf")
lock.acquire()
from zeroconf import ServiceBrowser, ServiceInfo, ServiceStateChange, Zeroconf
def on_change(zeroconf, service_type, name, state_change, **kwargs):
if state_change is ServiceStateChange.Added:
found.controls.append(ft.Text(name))
page.update()
zc = Zeroconf()
zc.register_service(ServiceInfo(
"_demo._tcp.local.", "my-flet-app._demo._tcp.local.",
addresses=[socket.inet_aton("127.0.0.1")], port=8080,
))
ServiceBrowser(zc, "_demo._tcp.local.", handlers=[on_change])
ft.run(main)To be discoverable by other devices, advertise your device's real LAN address instead of Android notes
iOS notes
|
zeroconf0.150.0 is now supported on Android and iOS: https://pypi.flet.dev/zeroconfzeroconfgives your Flet app mDNS service discovery and advertising (the protocol behind AirPlay/Chromecast/HomeAssistant device discovery) — find services on the local Wi-Fi, and/or announce your app so others can find it. Fully offline: it talks only to the local network, no internet needed.Installation
Just add
zeroconfto your dependencies. On Android you'll also want pyjnius (see why below):