// Fake Bluetooth controllers for the CYW4356 model. See btpeer.h. #include "btpeer.h" #include "../emu_state.h" #include #include #include #include namespace { constexpr int UART_D = 3; struct Peer { const char *name; uint8_t addr[6]; // little-endian, as HCI carries it uint8_t type; // the controller's own: 1 left Joy-Con, 2 right, 3 Pro bool needs_security; // answers "security block" until encrypted bool needs_bonding; // refuses Simple Pairing without bonding int8_t rssi; }; // Nintendo OUIs (98:B6:E9 and DC:68:EB), last three bytes made up. const Peer kPeers[] = { {"Pro Controller", {0x21, 0x43, 0x65, 0xE9, 0xB6, 0x98}, 3, true, true, -47}, {"Joy-Con (R)", {0x9A, 0xBC, 0xDE, 0xEB, 0x68, 0xDC}, 2, false, false, -61}, }; constexpr int kNPeers = sizeof(kPeers) / sizeof(kPeers[0]); const uint8_t kRadioAddr[6] = {0x10, 0x32, 0x54, 0xEB, 0x68, 0xDC}; // Bits of the 24-bit button field each controller cycles through. const uint8_t kBitsPro[] = {3, 2, 1, 0, 17, 16, 19, 18, 22, 6, 23, 7, 8, 9, 12, 13, 11, 10}; const uint8_t kBitsR[] = {3, 2, 1, 0, 6, 7, 9, 12, 10, 5, 4}; constexpr uint16_t kHandle = 0x0040; constexpr uint64_t kReportUs = 15000; // a report every 15 ms constexpr uint64_t kPressUs = 600000; // each button: 300 ms down, 300 up constexpr size_t kHostBacklog = 600; // the radio holds reports past this struct Pending { uint64_t due; int tag; // 1: inquiry traffic, cancelled with it std::vector bytes; }; struct Chan { uint16_t host_cid = 0; uint16_t peer_cid = 0; bool open = false, host_cfg = false, peer_cfg = false; }; struct State { std::vector q; int conn = -1; // index into kPeers bool encrypted = false; bool info_asked = false; Chan ch[2]; // HID control 0x11, interrupt 0x13 bool streaming = false, full = false; uint64_t stream_at = 0, next_report = 0; uint8_t timer = 0; uint8_t sig_id = 0x40; uint8_t last_auth_req = 0; } st; uint64_t now_us(EmuState *s) { return s->emu_usec; } void later(EmuState *s, uint64_t us, std::vector b, int tag = 0) { st.q.push_back({now_us(s) + us, tag, std::move(b)}); } std::vector event(uint8_t code, std::vector p) { std::vector b = {0x04, code, (uint8_t)p.size()}; b.insert(b.end(), p.begin(), p.end()); return b; } void put_addr(std::vector &v, const uint8_t *a) { v.insert(v.end(), a, a + 6); } std::vector cmd_complete(uint16_t op, std::vector ret) { std::vector p = {0x01, (uint8_t)op, (uint8_t)(op >> 8)}; p.insert(p.end(), ret.begin(), ret.end()); return event(0x0E, p); } std::vector cmd_status(uint16_t op, uint8_t status) { return event(0x0F, {status, 0x01, (uint8_t)op, (uint8_t)(op >> 8)}); } int peer_of(const uint8_t *addr) { for (int i = 0; i < kNPeers; i++) if (!memcmp(kPeers[i].addr, addr, 6)) return i; return -1; } // An L2CAP frame to the host, in one ACL packet. std::vector acl(uint16_t cid, const std::vector &d) { uint16_t hf = kHandle | 0x2000; uint16_t l2 = (uint16_t)d.size(), len = l2 + 4; std::vector b = {0x02, (uint8_t)hf, (uint8_t)(hf >> 8), (uint8_t)len, (uint8_t)(len >> 8), (uint8_t)l2, (uint8_t)(l2 >> 8), (uint8_t)cid, (uint8_t)(cid >> 8)}; b.insert(b.end(), d.begin(), d.end()); return b; } std::vector sig(uint8_t code, uint8_t id, std::vector d) { std::vector b = {code, id, (uint8_t)d.size(), (uint8_t)(d.size() >> 8)}; b.insert(b.end(), d.begin(), d.end()); return acl(0x0001, b); } void drop_link() { st.conn = -1; st.encrypted = st.info_asked = false; st.ch[0] = Chan{}; st.ch[1] = Chan{}; st.streaming = st.full = false; } // The buttons and sticks at time t into the stream. void input_now(uint64_t t, uint8_t *btn3, uint8_t *sticks6) { const Peer &p = kPeers[st.conn]; const uint8_t *bits = p.type == 3 ? kBitsPro : kBitsR; size_t nbits = p.type == 3 ? sizeof(kBitsPro) : sizeof(kBitsR); uint32_t b = 0; uint64_t step = t / kPressUs; if (t % kPressUs < kPressUs / 2) b = 1u << bits[step % nbits]; btn3[0] = (uint8_t)b; btn3[1] = (uint8_t)(b >> 8); btn3[2] = (uint8_t)(b >> 16); double a = (double)(t % 2000000) / 2000000.0 * 6.2831853; auto pack = [](uint8_t *o, double ang, bool on) { uint16_t x = on ? (uint16_t)(0x800 + 0x500 * cos(ang)) : 0x800; uint16_t y = on ? (uint16_t)(0x800 + 0x500 * sin(ang)) : 0x800; o[0] = (uint8_t)x; o[1] = (uint8_t)((x >> 8) | (y << 4)); o[2] = (uint8_t)(y >> 4); }; pack(sticks6, a, p.type != 2); // left stick: Pro and left Joy-Con pack(sticks6 + 3, -a, p.type != 1); // right stick: Pro and right Joy-Con } // Input report 0x21 (a subcommand's answer) or 0x30, on the input channel. std::vector report(uint8_t id, uint64_t t, const std::vector &reply) { std::vector r(1 + 49, 0); r[0] = 0xA1; // HID DATA, input r[1] = id; r[2] = st.timer++; r[3] = 0x8E; // battery full, powered by battery input_now(t, &r[4], &r[7]); r[13] = 0x00; // vibration for (size_t i = 0; i < reply.size() && 14 + i < r.size(); i++) r[14 + i] = reply[i]; return acl(st.ch[1].host_cid, r); } void hid_output(EmuState *s, const uint8_t *d, uint32_t n) { if (n < 12 || d[0] != 0xA2 || d[1] != 0x01) return; uint8_t sub = d[11]; uint64_t t = st.streaming ? now_us(s) - st.stream_at : 0; std::vector reply; switch (sub) { case 0x02: { // device info const Peer &p = kPeers[st.conn]; reply = {0x82, 0x02, 0x04, 0x21, p.type, 0x02}; for (int i = 5; i >= 0; i--) reply.push_back(p.addr[i]); reply.push_back(0x01); reply.push_back(0x01); break; } case 0x03: if (n > 12 && d[12] == 0x30) { st.full = true; printf("[btpeer] %s: full reports from now on\n", kPeers[st.conn].name); } reply = {0x80, 0x03}; break; default: reply = {0x80, sub}; break; } later(s, 8000, report(0x21, t, reply)); } void signal_in(EmuState *s, const uint8_t *d, uint32_t n) { while (n >= 4) { uint8_t code = d[0], id = d[1]; uint32_t len = d[2] | d[3] << 8; const uint8_t *p = d + 4; if (len > n - 4) return; switch (code) { case 0x02: { // Connection Request uint16_t psm = p[0] | p[1] << 8, scid = p[2] | p[3] << 8; int i = psm == 0x11 ? 0 : psm == 0x13 ? 1 : -1; if (i < 0) { later(s, 2000, sig(0x03, id, {0, 0, (uint8_t)scid, (uint8_t)(scid >> 8), 2, 0, 0, 0})); break; } if (kPeers[st.conn].needs_security && !st.encrypted) { printf("[btpeer] %s: PSM %02X before encryption, security block\n", kPeers[st.conn].name, psm); later(s, 2000, sig(0x03, id, {0, 0, (uint8_t)scid, (uint8_t)(scid >> 8), 3, 0, 0, 0})); break; } Chan &c = st.ch[i]; c = Chan{}; c.host_cid = scid; c.peer_cid = 0x0060 + i; c.open = true; later(s, 2000, sig(0x03, id, {(uint8_t)c.peer_cid, (uint8_t)(c.peer_cid >> 8), (uint8_t)scid, (uint8_t)(scid >> 8), 0, 0, 0, 0})); // Its own settings, MTU 672, as a controller sends them. later(s, 4000, sig(0x04, st.sig_id++, {(uint8_t)scid, (uint8_t)(scid >> 8), 0, 0, 0x01, 0x02, 0xA0, 0x02})); if (!st.info_asked) { st.info_asked = true; later(s, 3000, sig(0x0A, st.sig_id++, {0x02, 0x00})); } break; } case 0x04: { // the host's Configuration Request uint16_t dcid = p[0] | p[1] << 8; for (Chan &c : st.ch) if (c.open && c.peer_cid == dcid) { c.host_cfg = true; later(s, 2000, sig(0x05, id, {(uint8_t)c.host_cid, (uint8_t)(c.host_cid >> 8), 0, 0, 0, 0})); } break; } case 0x05: { // the host's answer to ours uint16_t scid = p[0] | p[1] << 8, res = p[4] | p[5] << 8; for (Chan &c : st.ch) if (c.open && c.peer_cid == scid && res == 0) c.peer_cfg = true; break; } case 0x0B: // Information Response printf("[btpeer] the host answered the information request (result %d)\n", len >= 4 ? p[2] | p[3] << 8 : -1); break; case 0x06: { // Disconnection Request later(s, 2000, sig(0x07, id, {p[0], p[1], p[2], p[3]})); break; } default: break; } d += 4 + len; n -= 4 + len; } Chan &intr = st.ch[1]; if (!st.streaming && st.ch[0].host_cfg && st.ch[0].peer_cfg && intr.host_cfg && intr.peer_cfg) { st.streaming = true; st.stream_at = now_us(s); st.next_report = now_us(s) + kReportUs; printf("[btpeer] %s: both HID channels open\n", kPeers[st.conn].name); } } } // namespace void btpeer_reset(EmuState *state) { (void)state; st.q.clear(); drop_link(); } bool btpeer_command(EmuState *s, uint16_t op, const uint8_t *p, uint32_t n) { switch (op) { case 0x1009: { // Read_BD_ADDR std::vector r = {0x00}; put_addr(r, kRadioAddr); later(s, 500, cmd_complete(op, r)); return true; } case 0x1003: // Read_Local_Supported_Features // Byte 6 bit 3: Secure Simple Pairing, as the CYW4356 has it. later(s, 500, cmd_complete(op, {0x00, 0xBF, 0xFE, 0x8F, 0xFE, 0xDB, 0xFF, 0x7B, 0x87})); return true; case 0x040D: { // PIN_Code_Request_Reply std::vector r = {0x00}; put_addr(r, p); later(s, 500, cmd_complete(op, r)); return true; } case 0x1005: // Read_Buffer_Size: 1021 x 8 ACL later(s, 500, cmd_complete(op, {0x00, 0xFD, 0x03, 0x40, 0x08, 0x00, 0x08, 0x00})); return true; case 0x0C01: case 0x0C56: case 0x0C45: case 0x0C13: case 0x0C24: case 0x0C1A: case 0x080F: // Write_Default_Link_Policy_Settings later(s, 500, cmd_complete(op, {0x00})); return true; case 0x0401: { // Inquiry later(s, 500, cmd_status(op, 0x00)); uint64_t len_us = (n >= 4 ? p[3] : 8) * 1280000ull; for (int i = 0; i < kNPeers; i++) { const Peer &pr = kPeers[i]; std::vector e = {0x01}; put_addr(e, pr.addr); e.insert(e.end(), {0x01, 0x00, 0x08, 0x25, 0x00, 0x34, 0x12, (uint8_t)pr.rssi}); later(s, 1500000ull + i * 1200000ull, event(0x22, e), 1); } later(s, len_us, event(0x01, {0x00}), 1); printf("[btpeer] inquiry started\n"); return true; } case 0x0402: { // Inquiry_Cancel std::vector keep; for (Pending &q : st.q) if (q.tag != 1) keep.push_back(std::move(q)); st.q.swap(keep); later(s, 500, cmd_complete(op, {0x00})); printf("[btpeer] inquiry cancelled\n"); return true; } case 0x0419: { // Remote_Name_Request later(s, 500, cmd_status(op, 0x00)); int i = n >= 6 ? peer_of(p) : -1; std::vector e = {(uint8_t)(i < 0 ? 0x04 : 0x00)}; put_addr(e, p); std::vector name(248, 0); if (i >= 0) memcpy(name.data(), kPeers[i].name, strlen(kPeers[i].name)); e.insert(e.end(), name.begin(), name.end()); later(s, i < 0 ? 5120000 : 300000, event(0x07, e)); return true; } case 0x0405: { // Create_Connection later(s, 500, cmd_status(op, 0x00)); int i = n >= 6 ? peer_of(p) : -1; std::vector e = {(uint8_t)(i < 0 ? 0x04 : 0x00), (uint8_t)kHandle, (uint8_t)(kHandle >> 8)}; put_addr(e, p); e.push_back(0x01); e.push_back(0x00); if (i >= 0) { drop_link(); st.conn = i; printf("[btpeer] %s: connected\n", kPeers[i].name); } later(s, i < 0 ? 5120000 : 600000, event(0x03, e)); return true; } case 0x0408: { // Create_Connection_Cancel std::vector r = {0x00}; put_addr(r, p); later(s, 500, cmd_complete(op, r)); return true; } case 0x0406: { // Disconnect later(s, 500, cmd_status(op, 0x00)); later(s, 50000, event(0x05, {0x00, (uint8_t)kHandle, (uint8_t)(kHandle >> 8), 0x16})); if (st.conn >= 0) printf("[btpeer] %s: the host disconnected\n", kPeers[st.conn].name); drop_link(); return true; } case 0x0411: // Authentication_Requested later(s, 500, cmd_status(op, 0x00)); if (st.conn >= 0) { std::vector e; put_addr(e, kPeers[st.conn].addr); later(s, 20000, event(0x17, e)); // Link Key Request } return true; case 0x040C: case 0x040B: { // Link key: none, or one std::vector r = {0x00}; put_addr(r, p); later(s, 500, cmd_complete(op, r)); if (st.conn < 0) return true; std::vector e; put_addr(e, kPeers[st.conn].addr); if (op == 0x040B) later(s, 30000, event(0x06, {0x00, (uint8_t)kHandle, (uint8_t)(kHandle >> 8)})); else later(s, 20000, event(0x31, e)); // IO Capability Request return true; } case 0x042B: { // IO_Capability_Request_Reply std::vector r = {0x00}; put_addr(r, p); later(s, 500, cmd_complete(op, r)); if (st.conn < 0) return true; const Peer &pr = kPeers[st.conn]; st.last_auth_req = n >= 9 ? p[8] : 0; std::vector e; put_addr(e, pr.addr); std::vector resp = e; resp.insert(resp.end(), {0x03, 0x00, (uint8_t)(pr.needs_bonding ? 0x04 : 0x00)}); later(s, 10000, event(0x32, resp)); // IO Capability Response if (pr.needs_bonding && !(st.last_auth_req & 0x06)) { printf("[btpeer] %s: refuses pairing without bonding\n", pr.name); std::vector spc = {0x05}; put_addr(spc, pr.addr); later(s, 30000, event(0x36, spc)); later(s, 35000, event(0x06, {0x05, (uint8_t)kHandle, (uint8_t)(kHandle >> 8)})); return true; } std::vector conf = e; conf.insert(conf.end(), {0x40, 0xE2, 0x01, 0x00}); later(s, 20000, event(0x33, conf)); // User Confirmation Request return true; } case 0x042C: { // User_Confirmation_Request_Reply std::vector r = {0x00}; put_addr(r, p); later(s, 500, cmd_complete(op, r)); if (st.conn < 0) return true; const Peer &pr = kPeers[st.conn]; std::vector spc = {0x00}; put_addr(spc, pr.addr); // The Pro Controller fails its first pairing of a run, as a real one // can, so a host's second try is exercised too. static int pro_pairings; if (pr.type == 3 && pro_pairings++ == 0) { printf("[btpeer] %s: first pairing fails (authentication failure)\n", pr.name); spc[0] = 0x05; later(s, 30000, event(0x36, spc)); later(s, 35000, event(0x06, {0x05, (uint8_t)kHandle, (uint8_t)(kHandle >> 8)})); return true; } later(s, 30000, event(0x36, spc)); // Simple Pairing Complete std::vector lk; put_addr(lk, pr.addr); for (int i = 0; i < 16; i++) lk.push_back((uint8_t)(0xA0 + i)); lk.push_back(0x04); // unauthenticated combination key if (st.last_auth_req & 0x06) later(s, 35000, event(0x18, lk)); // only kept when bonding later(s, 40000, event(0x06, {0x00, (uint8_t)kHandle, (uint8_t)(kHandle >> 8)})); printf("[btpeer] %s: paired (%s)\n", pr.name, (st.last_auth_req & 0x06) ? "bonding" : "no bonding"); return true; } case 0x0413: // Set_Connection_Encryption later(s, 500, cmd_status(op, 0x00)); if (st.conn >= 0) { st.encrypted = n >= 3 && p[2]; later(s, 20000, event(0x08, {0x00, (uint8_t)kHandle, (uint8_t)(kHandle >> 8), (uint8_t)(st.encrypted ? 1 : 0)})); } return true; case 0x040A: // Reject_Connection_Request later(s, 500, cmd_status(op, 0x00)); return true; case 0x040E: case 0x042F: { // PIN / passkey negative replies std::vector r = {0x00}; put_addr(r, p); later(s, 500, cmd_complete(op, r)); return true; } default: return false; } } void btpeer_acl(EmuState *s, const uint8_t *pkt, uint32_t n) { if (n < 8 || st.conn < 0) return; uint16_t hf = pkt[0] | pkt[1] << 8; if ((hf & 0x0FFF) != kHandle) return; // Every packet the host sends is acknowledged, as the radio does. later(s, 1000, event(0x13, {0x01, (uint8_t)kHandle, (uint8_t)(kHandle >> 8), 0x01, 0x00})); uint16_t l2 = pkt[4] | pkt[5] << 8, cid = pkt[6] | pkt[7] << 8; if (8u + l2 > n) return; const uint8_t *d = pkt + 8; if (cid == 0x0001) signal_in(s, d, l2); else if (cid == st.ch[1].peer_cid && st.ch[1].open) hid_output(s, d, l2); } void btpeer_tick(EmuState *s) { uint64_t now = now_us(s); auto &fifo = s->uart_rx_fifo[UART_D]; // What is due, oldest first. for (;;) { size_t best = st.q.size(); for (size_t i = 0; i < st.q.size(); i++) if (st.q[i].due <= now && (best == st.q.size() || st.q[i].due < st.q[best].due)) best = i; if (best == st.q.size()) break; for (uint8_t b : st.q[best].bytes) fifo.push_back(b); st.q.erase(st.q.begin() + best); } if (!st.streaming || st.conn < 0) return; // Reports. A host that does not read holds the radio up: past a backlog // the reports wait instead of piling up, as with flow control. while (st.next_report <= now) { if (fifo.size() > kHostBacklog) { st.next_report = now + kReportUs; break; } uint64_t t = st.next_report - st.stream_at; std::vector b; if (st.full) { b = report(0x30, t, {}); } else { // Before it is asked for full reports: the simple 0x3F one. std::vector r(1 + 12, 0); r[0] = 0xA1; r[1] = 0x3F; r[4] = 0x08; // hat centred b = acl(st.ch[1].host_cid, r); } for (uint8_t x : b) fifo.push_back(x); st.next_report += kReportUs; } }