Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ All three implement the same protocols and features:
| TV | Status |
|---|---|
| **Xiaomi Mi TV `MiTV-AXSO0`** (Android TV 9, PatchWall) | ✅ Tested with the macOS app. The mobile apps use the same protocol and have so far been tested against a mock TV |
| **Xiaomi Mi TV `MiTV-MOOR2`** (Android TV 11, no MiLink) | ✅ Tested with the macOS app, through the Android TV remote service ([#4](https://github.com/EndLess728/MiTV-Remote/issues/4)): pairing, navigation, volume, media keys and typing work. Input source opens Settings; recent apps isn't available |
| **Xiaomi Mi TV `MiTV-MOOR2`** (Android TV 11, no MiLink) | ✅ Tested with the macOS app, through the Android TV remote service ([#4](https://github.com/EndLess728/MiTV-Remote/issues/4)): pairing, navigation, volume, media keys, typing and switching HDMI inputs work. Recent apps isn't available |
| Other Mi TVs on Android TV with PatchWall | Expected to work, not tested |
| Xiaomi TVs on Google TV | Expected to work through the Android TV remote service, not tested |

Expand All @@ -51,8 +51,8 @@ The apps try MiLink first and fall back to the Android TV remote service, and re

**Over the Android TV remote service**, the TV only acts on a limited set of keys, the same ones the Google TV app can send:

- **Input source**: there's no input key, so the button opens the TV's **Settings**, where the inputs are. (Tried on the MOOR2: TV, HDMI 1–4, Guide and F1–F12 keys don't open the input menu.)
- **Recent apps**: not available; the button is greyed out.
- **Input source**: there's no input key, so the button opens a picker that switches straight to **HDMI 1, 2 or 3**, or opens **Settings** for the full list of inputs. The switch is a TV-input link (`content://android.media.tv/passthrough/…`) sent as an app-link request, with the input IDs MediaTek-based Mi TVs use. The input menu itself can't be opened this way: the service only passes plain links, and drops the connection on `intent:` links.
- **Recent apps**: not available, so the button is greyed out. The service can't deliver the recent-apps key (the TV's `virtual-remote.kl`, which the service types through, has no entry for it), and recents is part of the system UI, so there's no link to open it either. Hold or double-press Home, All apps, Menu and hold OK were all tried on the MOOR2.
- **macOS**: the pairing key is kept in your login keychain. After installing a new version, macOS may ask once for your password to let Mi Remote use it; choose **Always Allow** to keep the pairing.

**Check your TV** (it must be on the same Wi-Fi as your computer):
Expand Down
6 changes: 6 additions & 0 deletions apps/macos/Sources/MiRemote/ATVProtocol.swift
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,12 @@ enum RemoteMessage {
Proto.bytes(10, Proto.int(1, Int64(code)) + Proto.int(2, direction.rawValue))
}

/// Asks the TV to open a link (RemoteAppLinkLaunchRequest): a deep link, a TV-input link such
/// as content://android.media.tv/passthrough/<input id>, or possibly an intent: URI.
static func appLink(_ link: String) -> [UInt8] {
Proto.bytes(90, Proto.string(1, link))
}

/// Puts `text` into the focused text field on the TV, cursor after it. The counters echo the
/// TV's latest (0 before it has sent any), as the Google TV app and other clients do.
static func imeBatchEdit(imeCounter: Int32, fieldCounter: Int32, text: String) -> [UInt8] {
Expand Down
6 changes: 6 additions & 0 deletions apps/macos/Sources/MiRemote/RemoteClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -610,6 +610,12 @@ final class RemoteClient: ObservableObject {
/// Single press: DOWN followed by UP.
func press(_ key: AndroidKey) { press(code: key.rawValue) }

/// Android TV Remote: asks the TV to open `link` (see `RemoteMessage.appLink`).
func openLink(_ link: String) {
guard state == .connected, phase == .atv else { return }
sendDelimited(RemoteMessage.appLink(link))
}

func press(code: Int32, meta: Int32 = 0) {
if phase == .atv {
if let code = Self.atvKey(for: code) { sendAtvKey(code) }
Expand Down
102 changes: 98 additions & 4 deletions apps/macos/Sources/MiRemote/RemoteView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ struct RemoteView: View {
@StateObject private var discovery = TVDiscovery()
@AppStorage("tvHost") private var savedHost = ""
@State private var showConnect = false
/// Over Android TV Remote there's no input-source key; this picker switches inputs by link.
@State private var showInputs = false
@State private var text = ""
@FocusState private var remoteFocused: Bool
@FocusState private var textFocused: Bool
Expand Down Expand Up @@ -89,6 +91,15 @@ struct RemoteView: View {
.overlay(RoundedRectangle(cornerRadius: 14, style: .continuous).stroke(Palette.bodyEdge))
.padding(14)
}
} else if showInputs {
ZStack {
Color.black.opacity(0.55)
.onTapGesture { showInputs = false }
InputSourceSheet(client: client) { showInputs = false }
.background(RoundedRectangle(cornerRadius: 14, style: .continuous).fill(Palette.body))
.overlay(RoundedRectangle(cornerRadius: 14, style: .continuous).stroke(Palette.bodyEdge))
.padding(14)
}
} else if client.state == .pairing {
// Android TVs without MiLink need a one-time code shown on the TV.
ZStack {
Expand Down Expand Up @@ -146,9 +157,8 @@ struct RemoteView: View {
HStack {
RoundKey(symbol: "power", tint: Palette.power, help: "Power (P)") { client.press(.power) }
Spacer()
RoundKey(symbol: "rectangle.on.rectangle",
help: client.tvProtocol == .atv ? "Input source (opens Settings: this TV has no input key over Wi-Fi)" : "Input source") {
client.press(.tvInput)
RoundKey(symbol: "rectangle.on.rectangle", help: "Input source") {
if client.tvProtocol == .atv { showInputs = true } else { client.press(.tvInput) }
}
Spacer()
RoundKey(symbol: "square.stack",
Expand Down Expand Up @@ -249,7 +259,7 @@ struct RemoteView: View {
// MARK: Keyboard

private func handleKey(_ press: KeyPress) -> KeyPress.Result {
if textFocused || press.modifiers.contains(.command) || client.state == .pairing { return .ignored }
if textFocused || press.modifiers.contains(.command) || client.state == .pairing || showInputs { return .ignored }
switch press.key {
case .upArrow: client.press(.dpadUp)
case .downArrow: client.press(.dpadDown)
Expand Down Expand Up @@ -637,3 +647,87 @@ struct PairSheet: View {
}
}


// MARK: - Input source (Android TV Remote)

/// Inputs reachable over the Android TV remote service, which has no input-source key (#6). The
/// TV's Live TV app switches inputs on TV-input passthrough links, sent as app-link requests.
/// Opening the input menu itself by link doesn't work: the service drops the connection on
/// intent: links (tested on a MiTV-MOOR2).
enum InputSourceOption: CaseIterable, Identifiable {
case hdmi1
case hdmi2
case hdmi3
case settings

var id: Self { self }

var title: String {
switch self {
case .hdmi1: return "HDMI 1"
case .hdmi2: return "HDMI 2"
case .hdmi3: return "HDMI 3"
case .settings: return "Settings"
}
}

/// The passthrough link for an HDMI input. MediaTek-based Mi TVs name HDMI port n's input
/// HW(n+3) in their TV input service. Nil for Settings, which is a key.
var link: String? {
switch self {
case .hdmi1: return Self.passthrough("HW4")
case .hdmi2: return Self.passthrough("HW5")
case .hdmi3: return Self.passthrough("HW6")
case .settings: return nil
}
}

private static func passthrough(_ hardwareId: String) -> String {
"content://android.media.tv/passthrough/com.mediatek.tvinput%2F.hdmi.HDMIInputService%2F\(hardwareId)"
}
}

/// Input picker for TVs on the Android TV remote service. Closes once an input is chosen.
struct InputSourceSheet: View {
@ObservedObject var client: RemoteClient
var onClose: () -> Void

var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Input source")
.font(.headline)
LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 6), count: 3), spacing: 6) {
ForEach(InputSourceOption.allCases.filter { $0 != .settings }) { option in
choice(option)
}
}
choice(.settings)
Text("Settings has the full list of inputs.")
.font(.caption)
.foregroundStyle(.secondary)
HStack {
Spacer()
Button("Cancel", action: onClose)
.keyboardShortcut(.cancelAction)
}
}
.padding(18)
}

private func choice(_ option: InputSourceOption) -> some View {
Button {
if let link = option.link {
client.openLink(link)
} else {
client.press(.settings)
}
onClose()
} label: {
Text(option.title)
.font(.system(size: 12, weight: .semibold))
.lineLimit(1)
.frame(maxWidth: .infinity, minHeight: 32)
}
.buttonStyle(KeyStyle(shape: RoundedRectangle(cornerRadius: 8, style: .continuous), fill: Palette.key))
}
}
1 change: 1 addition & 0 deletions apps/macos/Tests/MiRemoteTests/ATVProtocolTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ final class ATVProtocolTests: XCTestCase {
XCTAssertEqual(RemoteMessage.imeBatchEdit(imeCounter: 3, fieldCounter: 7, text: "héllo"), [170, 1, 22, 8, 3, 16, 7, 26, 16, 8, 1, 18, 12, 8, 5, 16, 5, 26, 6, 104, 195, 169, 108, 108, 111])
XCTAssertEqual(RemoteMessage.configure(features: 615), [10, 50, 8, 231, 4, 18, 45, 10, 9, 77, 105, 32, 82, 101, 109, 111, 116, 101, 18, 9, 77, 105, 32, 82, 101, 109, 111, 116, 101, 24, 1, 34, 1, 49, 42, 9, 97, 116, 118, 114, 101, 109, 111, 116, 101, 50, 5, 49, 46, 48, 46, 48])
XCTAssertEqual(RemoteMessage.wantedFeatures, 615)
XCTAssertEqual(RemoteMessage.appLink("content://x"), [210, 5, 13, 10, 11, 99, 111, 110, 116, 101, 110, 116, 58, 47, 47, 120])
}

func testParsesRemoteMessages() throws {
Expand Down
7 changes: 7 additions & 0 deletions apps/macos/Tests/MiRemoteTests/FakeTVTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,13 @@ final class FakeTVTests: XCTestCase {
((try? String(contentsOfFile: keysFile, encoding: .utf8)) ?? "").contains("text 0 0 6 Hello!")
}

// Links reach the TV as app-link launch requests.
client.openLink(InputSourceOption.hdmi1.link!)
try await waitUntil("the TV to receive the link", client: client) {
((try? String(contentsOfFile: keysFile, encoding: .utf8)) ?? "")
.contains("link \(InputSourceOption.hdmi1.link!)")
}

// Reconnecting reuses the pairing: straight to connected, no new code.
client.disconnect()
try? FileManager.default.removeItem(atPath: codeFile)
Expand Down
5 changes: 5 additions & 0 deletions apps/macos/Tests/fake_tv.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,11 @@ def handle_remote(conn: SSL.Connection, args: argparse.Namespace) -> None:
session.send(ping)
elif msg.HasField("remote_ping_response"):
log("remote: ping answered", msg.remote_ping_response.val1)
elif msg.HasField("remote_app_link_launch_request"):
link = msg.remote_app_link_launch_request.app_link
log("remote: open link", link)
with open(args.keys_file, "a") as f:
f.write(f"link {link}\n")
elif msg.HasField("remote_ime_batch_edit"):
edit = msg.remote_ime_batch_edit
for info in edit.edit_info:
Expand Down
99 changes: 97 additions & 2 deletions apps/mobile/src/app/index.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
import React, { useEffect, useState } from 'react';
import { AppState, Pressable, Text, TextInput, useWindowDimensions, View } from 'react-native';
import {
AppState,
Modal,
Pressable,
Text,
TextInput,
useWindowDimensions,
View,
} from 'react-native';
import { KeyboardStickyView } from 'react-native-keyboard-controller';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { StyleSheet, useUnistyles } from 'react-native-unistyles';
import { Ionicons } from '@react-native-vector-icons/ionicons';
import { router, usePathname } from 'expo-router';

import { hdmiInputLink } from '@/atv/messages';
import { DPad } from '@/components/remote/DPad';
import { RemoteKey } from '@/components/remote/RemoteKey';
import { Rocker } from '@/components/remote/Rocker';
Expand Down Expand Up @@ -63,6 +72,52 @@ function StatusHeader() {
);
}

/**
* Input picker for TVs on the Android TV remote service, which has no input-source key (#6):
* HDMI inputs switch by passthrough link; Settings lists every input. Closes once one is chosen.
*/
function InputPicker({ visible, onClose }: { visible: boolean; onClose: () => void }) {
const t = useTranslate();
const choose = (action: () => void) => {
tapFeedback();
action();
onClose();
};

return (
<Modal transparent animationType="fade" visible={visible} onRequestClose={onClose}>
<Pressable style={styles.pickerBackdrop} onPress={onClose}>
<Pressable style={styles.picker}>
<Text style={[TextStyles.bodySemiBold, styles.title]}>{t('inputs.title')}</Text>
<View style={styles.pickerRow}>
{[1, 2, 3].map((port) => (
<Pressable
key={port}
accessibilityRole="button"
style={({ pressed }) => styles.pickerChoice(pressed)}
onPress={() => choose(() => remote.openLink(hdmiInputLink(port)))}
>
<Text style={[TextStyles.bodySemiBold, styles.title]}>HDMI {port}</Text>
</Pressable>
))}
</View>
<Pressable
accessibilityRole="button"
style={({ pressed }) => styles.pickerChoice(pressed)}
onPress={() => choose(() => remote.press('settings'))}
>
<Text style={[TextStyles.bodySemiBold, styles.title]}>{t('inputs.settings')}</Text>
</Pressable>
<Text style={[TextStyles.caption, styles.subtitle]}>{t('inputs.settings_hint')}</Text>
<Pressable accessibilityRole="button" style={styles.pickerCancel} onPress={onClose}>
<Text style={[TextStyles.bodySemiBold, styles.subtitle]}>{t('inputs.cancel')}</Text>
</Pressable>
</Pressable>
</Pressable>
</Modal>
);
}

function TypeBar() {
const { theme } = useUnistyles();
const t = useTranslate();
Expand Down Expand Up @@ -111,6 +166,7 @@ export default function RemoteScreen(): React.JSX.Element {
const status = useConnectionStore((s) => s.status);
// The Android TV Remote service has no recent-apps key (see atvKey in the client).
const atv = useConnectionStore((s) => s.protocol === 'atv');
const [showInputs, setShowInputs] = useState(false);
const pathname = usePathname();

// Android TVs without MiLink need a one-time pairing code; ask for it when the client does.
Expand Down Expand Up @@ -151,7 +207,12 @@ export default function RemoteScreen(): React.JSX.Element {
keyName="power"
variant="power"
/>
<RemoteKey accessibilityLabel={t('remote.input')} icon="tv-outline" keyName="tvInput" />
<RemoteKey
accessibilityLabel={t('remote.input')}
icon="tv-outline"
keyName="tvInput"
onPress={atv ? () => setShowInputs(true) : undefined}
/>
<RemoteKey
accessibilityLabel={t('remote.apps')}
disabled={atv}
Expand Down Expand Up @@ -246,6 +307,8 @@ export default function RemoteScreen(): React.JSX.Element {

{/* Rides above the keyboard so the text stays visible while typing. The bar sits
insets.bottom + 8 (screen) + 16 (body) above the screen edge; keep an 8pt gap. */}
<InputPicker visible={showInputs} onClose={() => setShowInputs(false)} />

<KeyboardStickyView offset={{ opened: insets.bottom + ms(16) }}>
<TypeBar />
</KeyboardStickyView>
Expand All @@ -255,6 +318,38 @@ export default function RemoteScreen(): React.JSX.Element {
}

const styles = StyleSheet.create((theme, rt) => ({
pickerBackdrop: {
flex: 1,
justifyContent: 'center',
padding: ms(24),
backgroundColor: 'rgba(0,0,0,0.55)',
},
picker: {
width: '100%',
maxWidth: 420,
alignSelf: 'center',
gap: ms(10),
padding: ms(18),
borderRadius: ms(18),
backgroundColor: theme.colors.remoteBody,
},
pickerRow: {
flexDirection: 'row',
gap: ms(8),
},
pickerChoice: (pressed: boolean) => ({
flex: 1,
height: ms(46),
borderRadius: ms(12),
alignItems: 'center',
justifyContent: 'center',
backgroundColor: pressed ? theme.colors.remoteKeyPressed : theme.colors.remoteKey,
}),
pickerCancel: {
alignSelf: 'flex-end',
paddingVertical: ms(6),
paddingHorizontal: ms(8),
},
screen: {
flex: 1,
backgroundColor: theme.colors.remoteScreen,
Expand Down
8 changes: 8 additions & 0 deletions apps/mobile/src/atv/__tests__/atv.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ import {
} from '../__fixtures__/vectors';
import { certificate, rsaPublicKey, subjectPublicKeyInfo, tbsCertificate } from '../der';
import {
appLink,
Direction,
hdmiInputLink,
imeBatchEdit,
keyInject,
normalizeCode,
Expand Down Expand Up @@ -143,6 +145,12 @@ describe('remote messages', () => {
expect(remoteSetActive(615)).toEqual(PB.setActive615);
expect(imeBatchEdit(3, 7, 'héllo')).toEqual(PB.imeHello);
expect(remoteConfigure(615)).toEqual(PB.configure615);
expect(appLink('content://x')).toEqual([
210, 5, 13, 10, 11, 99, 111, 110, 116, 101, 110, 116, 58, 47, 47, 120,
]);
expect(hdmiInputLink(1)).toBe(
'content://android.media.tv/passthrough/com.mediatek.tvinput%2F.hdmi.HDMIInputService%2FHW4',
);
});

it('parses incoming messages', () => {
Expand Down
Loading
Loading