<# LogiSwitch.ps1 - switch Logitech keyboard + mouse to another Easy-Switch channel at once. Uses the HID++ 2.0 "Change Host" feature (0x1814), the same command Logi Flow sends. Works over Bluetooth and Unifying/Bolt receivers. No admin rights, no internet, no file sharing. Optional clipboard sync (text, off by default): this PC dials out to the Mac on TCP 51888, encrypted. .\LogiSwitch.ps1 -List # read-only: devices, channel count, active channel .\LogiSwitch.ps1 -Channel 2 # send all supported devices to channel 2 (1-based) .\LogiSwitch.ps1 -Channel 2 -Name K860,"MX Vertical" # only devices whose name matches .\LogiSwitch.ps1 -Watch -Edge Right -Channel 2 # background: push cursor against right edge -> switch .\LogiSwitch.ps1 -Watch -Edge Right -Channel 2 -DryRun # test edge detection without switching #> param( [switch]$List, [int]$Channel = 0, [string[]]$Name, [switch]$Watch, [ValidateSet('Right','Left')][string]$Edge = 'Right', [int]$DwellMs = 50, [switch]$DryRun, [int]$MaxSeconds = 0, [double]$RefreshMinutes = 3, [switch]$Fast, # with -Channel: use remembered devices instead of the slow search # Clipboard sync (off unless asked for). This PC only ever dials OUT to the Mac, so no # firewall change is needed. Everything is encrypted with the shared pairing code. [switch]$ClipboardSync, [string]$PeerHost = '', [int]$PeerPort = 51888 ) $cs = @' using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.Win32.SafeHandles; public class LogiDev { public string LongPath; public string ShortPath; public string Name; public byte DevIdx; public byte ChangeHostIdx; public int HostCount; public int CurrentHost; public string Transport; } class Conn : IDisposable { public FileStream L, S; List streams = new List(); List> tasks = new List>(); List bufs = new List(); public Conn(FileStream l, FileStream s) { L = l; S = s; Add(l); if (s != null) Add(s); } void Add(FileStream f) { streams.Add(f); bufs.Add(null); tasks.Add(null); Arm(streams.Count - 1); } void Arm(int i) { bufs[i] = new byte[streams[i] == S ? 7 : 20]; tasks[i] = streams[i].ReadAsync(bufs[i], 0, bufs[i].Length); } // Returns next incoming report from any collection, or null on timeout. Pending reads stay armed. public byte[] Next(int ms) { int i = Task.WaitAny(tasks.ToArray(), Math.Max(1, ms)); if (i < 0) return null; var b = bufs[i]; Arm(i); return b; } public void Dispose() { foreach (var f in streams) f.Dispose(); } } public static class LogiHid { [StructLayout(LayoutKind.Sequential)] struct HIDD_ATTRIBUTES { public int Size; public ushort VendorID; public ushort ProductID; public ushort Version; } [StructLayout(LayoutKind.Sequential)] struct HIDP_CAPS { public ushort Usage, UsagePage, InputReportByteLength, OutputReportByteLength, FeatureReportByteLength; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 27)] public ushort[] Reserved; } [StructLayout(LayoutKind.Sequential)] struct SP_DEVICE_INTERFACE_DATA { public int cbSize; public Guid InterfaceClassGuid; public int Flags; public IntPtr Reserved; } [DllImport("hid.dll")] static extern void HidD_GetHidGuid(out Guid g); [DllImport("hid.dll")] static extern bool HidD_GetAttributes(SafeFileHandle h, ref HIDD_ATTRIBUTES a); [DllImport("hid.dll")] static extern bool HidD_GetPreparsedData(SafeFileHandle h, out IntPtr p); [DllImport("hid.dll")] static extern bool HidD_FreePreparsedData(IntPtr p); [DllImport("hid.dll")] static extern int HidP_GetCaps(IntPtr p, out HIDP_CAPS c); [DllImport("setupapi.dll", CharSet = CharSet.Unicode)] static extern IntPtr SetupDiGetClassDevs(ref Guid g, IntPtr e, IntPtr w, int f); [DllImport("setupapi.dll")] static extern bool SetupDiEnumDeviceInterfaces(IntPtr s, IntPtr i, ref Guid g, int idx, ref SP_DEVICE_INTERFACE_DATA d); [DllImport("setupapi.dll", CharSet = CharSet.Unicode)] static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr s, ref SP_DEVICE_INTERFACE_DATA d, IntPtr det, int size, out int req, IntPtr info); [DllImport("setupapi.dll")] static extern bool SetupDiDestroyDeviceInfoList(IntPtr s); [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] static extern SafeFileHandle CreateFile(string n, uint acc, uint share, IntPtr sec, uint disp, uint flags, IntPtr t); const byte SW = 0x0B; public static List Log = new List(); class Iface { public string Path; public ushort Pid, Page, Usage; } static List Enumerate() { var res = new List(); Guid g; HidD_GetHidGuid(out g); IntPtr set = SetupDiGetClassDevs(ref g, IntPtr.Zero, IntPtr.Zero, 0x12); var d = new SP_DEVICE_INTERFACE_DATA(); d.cbSize = Marshal.SizeOf(d); for (int i = 0; SetupDiEnumDeviceInterfaces(set, IntPtr.Zero, ref g, i, ref d); i++) { int req; SetupDiGetDeviceInterfaceDetail(set, ref d, IntPtr.Zero, 0, out req, IntPtr.Zero); IntPtr buf = Marshal.AllocHGlobal(req); Marshal.WriteInt32(buf, IntPtr.Size == 8 ? 8 : 6); if (SetupDiGetDeviceInterfaceDetail(set, ref d, buf, req, out req, IntPtr.Zero)) { string path = Marshal.PtrToStringUni(new IntPtr(buf.ToInt64() + 4)); if (path.ToLowerInvariant().Contains("046d")) { using (var h = CreateFile(path, 0, 3, IntPtr.Zero, 3, 0, IntPtr.Zero)) { if (!h.IsInvalid) { var a = new HIDD_ATTRIBUTES(); a.Size = Marshal.SizeOf(a); IntPtr pp; HIDP_CAPS c; if (HidD_GetAttributes(h, ref a) && a.VendorID == 0x046D && HidD_GetPreparsedData(h, out pp)) { HidP_GetCaps(pp, out c); HidD_FreePreparsedData(pp); res.Add(new Iface { Path = path, Pid = a.ProductID, Page = c.UsagePage, Usage = c.Usage }); } } } } } Marshal.FreeHGlobal(buf); } SetupDiDestroyDeviceInfoList(set); return res; } internal static FileStream OpenStream(string path, int len) { if (path == null) return null; var h = CreateFile(path, 0xC0000000, 3, IntPtr.Zero, 3, 0x40000000, IntPtr.Zero); if (h.IsInvalid) return null; return new FileStream(h, FileAccess.ReadWrite, len, true); } static Conn Open(string longPath, string shortPath) { var l = OpenStream(longPath, 20); if (l == null) return null; return new Conn(l, OpenStream(shortPath, 7)); } // Long HID++ 2.0 request; returns 16 param bytes, or null on error/timeout. static byte[] Request(Conn c, byte dev, byte feat, byte fn, byte[] p, int timeoutMs) { var msg = new byte[20]; msg[0] = 0x11; msg[1] = dev; msg[2] = feat; msg[3] = (byte)((fn << 4) | SW); if (p != null) Array.Copy(p, 0, msg, 4, Math.Min(p.Length, 16)); c.L.Write(msg, 0, 20); c.L.Flush(); var deadline = DateTime.UtcNow.AddMilliseconds(timeoutMs); while (DateTime.UtcNow < deadline) { var rb = c.Next((int)(deadline - DateTime.UtcNow).TotalMilliseconds); if (rb == null) return null; if (rb[1] != dev) continue; if (rb[2] == 0x8F || (rb[0] == 0x11 && rb[2] == 0xFF && rb[3] == feat)) return null; // device absent / error if (rb[0] == 0x11 && rb[2] == feat && rb[3] == msg[3]) { var r = new byte[16]; Array.Copy(rb, 4, r, 0, 16); return r; } } return null; } static byte GetFeatureIndex(Conn c, byte dev, ushort id) { var r = Request(c, dev, 0x00, 0, new byte[] { (byte)(id >> 8), (byte)id }, 1500); return r == null ? (byte)0 : r[0]; } static string GetName(Conn c, byte dev) { byte idx = GetFeatureIndex(c, dev, 0x0005); if (idx == 0) return null; var r = Request(c, dev, idx, 0, null, 1000); if (r == null) return null; int len = r[0]; var sb = new StringBuilder(); while (sb.Length < len) { var ch = Request(c, dev, idx, 1, new byte[] { (byte)sb.Length }, 1000); if (ch == null) break; for (int i = 0; i < 16 && sb.Length < len; i++) sb.Append((char)ch[i]); } return sb.ToString().TrimEnd('\0'); } public static List Discover() { var found = new List(); var all = Enumerate(); foreach (var e in all) { bool ble = e.Page == 0xFF43 && e.Usage == 0x0202; bool rcv = e.Page == 0xFF00 && e.Usage == 0x0002; if (!ble && !rcv) continue; string shortPath = null; if (rcv) { shortPath = FindShortPath(e.Path, all); } Conn c = null; try { c = Open(e.Path, shortPath); if (c == null) { Log.Add("cannot open " + e.Pid.ToString("X4")); continue; } var idxs = ble ? new byte[] { 0xFF } : new byte[] { 1, 2, 3, 4, 5, 6 }; foreach (var dev in idxs) { byte ch = GetFeatureIndex(c, dev, 0x1814); if (ch == 0) continue; var info = Request(c, dev, ch, 0, null, 1500); if (info == null) continue; found.Add(new LogiDev { LongPath = e.Path, ShortPath = shortPath, DevIdx = dev, ChangeHostIdx = ch, HostCount = info[0], CurrentHost = info[1] + 1, Name = GetName(c, dev) ?? ("PID " + e.Pid.ToString("X4")), Transport = ble ? "Bluetooth" : "USB receiver " + e.Pid.ToString("X4") + " slot " + dev }); } } catch (Exception ex) { Log.Add(e.Pid.ToString("X4") + ": " + ex.Message); } finally { if (c != null) c.Dispose(); } } return found; } public static string Switch(LogiDev d, int channel) { FileStream l = null; try { l = OpenStream(d.LongPath, 20); if (l == null) return "not connected"; var msg = new byte[20]; msg[0] = 0x11; msg[1] = d.DevIdx; msg[2] = d.ChangeHostIdx; msg[3] = (byte)(0x10 | SW); msg[4] = (byte)(channel - 1); var t = l.WriteAsync(msg, 0, 20); if (!t.Wait(400)) return "no response (not connected?)"; return "sent"; } catch (Exception) { return "not connected"; } finally { if (l != null) l.Dispose(); } } // The receiver's short-report collection (where receiver errors and connect/disconnect notices arrive) // is a sibling interface of the long one: same path up to "&col", page 0xFF00 usage 0x0001. static readonly Dictionary shortPaths = new Dictionary(StringComparer.OrdinalIgnoreCase); static string FindShortPath(string longPath, List all) { int i = longPath.IndexOf("&col", StringComparison.OrdinalIgnoreCase); if (i < 0) return null; string prefix = longPath.Substring(0, i); foreach (var s in all ?? Enumerate()) if (s.Page == 0xFF00 && s.Usage == 0x0001 && s.Path.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) return s.Path; return null; } internal static string ShortPathFor(LogiDev d) { if (d.DevIdx == 0xFF) return null; // Bluetooth: no short collection needed if (!string.IsNullOrEmpty(d.ShortPath)) return d.ShortPath; string sp; lock (shortPaths) { if (shortPaths.TryGetValue(d.LongPath, out sp)) return sp; } sp = FindShortPath(d.LongPath, null); lock (shortPaths) { shortPaths[d.LongPath] = sp; } return sp; } static string Ok(int attempt) { return attempt > 1 ? "sent (attempt " + attempt + ")" : "sent"; } // Sends Change Host, then confirms the device really left (it no longer answers here). // A lost or undeliverable command is re-sent, up to 3 attempts. public static string SwitchConfirmed(LogiDev d, int channel) { string last = ""; for (int attempt = 1; attempt <= 3; attempt++) { Conn c = null; try { c = Open(d.LongPath, ShortPathFor(d)); if (c == null) return attempt == 1 ? "not connected" : Ok(attempt - 1); var msg = new byte[20]; msg[0] = 0x11; msg[1] = d.DevIdx; msg[2] = d.ChangeHostIdx; msg[3] = (byte)(0x10 | SW); msg[4] = (byte)(channel - 1); var t = c.L.WriteAsync(msg, 0, 20); if (!t.Wait(400)) return attempt == 1 ? "no response (not connected?)" : Ok(attempt - 1); // A receiver answers at once if it could not deliver the command (device asleep / out of range). bool rejected = false; var end = DateTime.UtcNow.AddMilliseconds(250); while (DateTime.UtcNow < end) { var rb = c.Next((int)(end - DateTime.UtcNow).TotalMilliseconds); if (rb == null) break; if (rb[1] != d.DevIdx) continue; if (rb[2] == 0x8F || (rb[0] == 0x11 && rb[2] == 0xFF)) { rejected = true; break; } } c.Dispose(); c = null; if (rejected) { last = "receiver could not deliver"; System.Threading.Thread.Sleep(300); continue; } // Confirm: if the device still answers on this PC, the switch did not happen. System.Threading.Thread.Sleep(600); c = Open(d.LongPath, ShortPathFor(d)); if (c == null) return Ok(attempt); var cc = c; var probe = Task.Run(() => Request(cc, d.DevIdx, 0x00, 0, new byte[] { 0x18, 0x14 }, 400)); bool stillHere = probe.Wait(900) && probe.Result != null; if (!stillHere) return Ok(attempt); last = "device still on this PC"; } catch (Exception ex) { last = ex.Message; } finally { if (c != null) c.Dispose(); } } return "FAILED after 3 attempts (" + last + ")"; } // Switch all devices at once, so a remembered device that is not here (e.g. home vs. work setup) adds no delay. public static string[] SwitchAll(LogiDev[] devs, int channel) { var tasks = new Task[devs.Length]; for (int i = 0; i < devs.Length; i++) { var d = devs[i]; tasks[i] = Task.Run(() => d.Name + " -> channel " + channel + ": " + (d.HostCount > 0 && channel > d.HostCount ? "skipped (only " + d.HostCount + " channels)" : SwitchConfirmed(d, channel))); } try { Task.WaitAll(tasks, 8000); } catch (AggregateException) { } var r = new string[devs.Length]; for (int i = 0; i < devs.Length; i++) r[i] = tasks[i].Status == TaskStatus.RanToCompletion ? tasks[i].Result : devs[i].Name + ": timed out"; return r; } public static LogiDev Make(string longPath, string name, byte devIdx, byte chIdx, int hosts, string transport) { return new LogiDev { LongPath = longPath, Name = name, DevIdx = devIdx, ChangeHostIdx = chIdx, HostCount = hosts, Transport = transport }; } } // "Keyboard leads, mouse follows": listens to the USB receiver of each keyboard. When the keyboard // leaves this PC (its Easy-Switch key was pressed), the receiver sends HID++ 1.0 notification 0x41 // with the "link not established" bit, and an event is queued for the watcher loop. public static class KeyboardFollow { static readonly System.Collections.Concurrent.ConcurrentQueue events = new System.Collections.Concurrent.ConcurrentQueue(); static readonly HashSet watching = new HashSet(); public static bool IsKeyboard(string name) { return Regex.IsMatch(name ?? "", "K\\d|Keys|Keyboard", RegexOptions.IgnoreCase); } public static string Take() { string e; return events.TryDequeue(out e) ? e : null; } public static void Watch(LogiDev[] devs) { foreach (var d in devs) { if (d == null || d.DevIdx == 0xFF || !IsKeyboard(d.Name)) continue; // Bluetooth keyboards: no disconnect signal on Windows string sp = LogiHid.ShortPathFor(d); if (sp == null) continue; string key = sp.ToLowerInvariant() + "|" + d.DevIdx; lock (watching) { if (!watching.Add(key)) continue; } var dev = d; var t = new System.Threading.Thread(() => Listen(sp, dev.DevIdx, dev.Name, key)); t.IsBackground = true; t.Start(); } } // The receiver reports the current link state as soon as we start listening; those first // notifications are not a key press, so they are ignored. static void Handle(byte[] r, byte devIdx, string name, DateTime started) { if (r == null || r.Length < 5 || r[0] != 0x10 || r[1] != devIdx || r[2] != 0x41) return; if ((DateTime.UtcNow - started).TotalMilliseconds < 3000) return; events.Enqueue(((r[4] & 0x40) != 0 ? "left:" : "back:") + name); } static void Listen(string shortPath, byte devIdx, string name, string key) { FileStream s = null; var started = DateTime.UtcNow; try { s = LogiHid.OpenStream(shortPath, 7); if (s == null) { events.Enqueue("info:cannot open the receiver for " + name); return; } events.Enqueue("info:mouse will follow keyboard " + name + " (receiver slot " + devIdx + ")"); Task pending = null; byte[] buf = null; Func next = ms => { if (pending == null) { buf = new byte[7]; pending = s.ReadAsync(buf, 0, 7); } if (!pending.Wait(ms)) return null; var r = buf; pending = null; return r; }; // Make sure the receiver reports connect/disconnect: HID++ 1.0 register 0x00, "wireless" flag (0x000100). s.Write(new byte[] { 0x10, 0xFF, 0x81, 0x00, 0, 0, 0 }, 0, 7); var end = DateTime.UtcNow.AddMilliseconds(1000); byte[] reg = null; while (DateTime.UtcNow < end) { var r = next((int)Math.Max(1, (end - DateTime.UtcNow).TotalMilliseconds)); if (r == null) break; if (r[1] == 0xFF && r[2] == 0x81 && r[3] == 0x00) { reg = r; break; } Handle(r, devIdx, name, started); } if (reg != null && (reg[5] & 0x01) == 0) { s.Write(new byte[] { 0x10, 0xFF, 0x80, 0x00, reg[4], (byte)(reg[5] | 0x01), reg[6] }, 0, 7); events.Enqueue("info:enabled connect/disconnect notifications on the receiver"); } while (true) { var r = next(-1); if (r == null) break; Handle(r, devIdx, name, started); } } catch (Exception ex) { events.Enqueue("info:stopped following " + name + " (" + ex.Message + ")"); } finally { if (s != null) s.Dispose(); lock (watching) { watching.Remove(key); } } } } '@ if (-not ('LogiHid' -as [type])) { Add-Type -TypeDefinition $cs -Language CSharp } if ($Watch) { if ($Channel -lt 1) { $Channel = 2 } Add-Type -AssemblyName System.Windows.Forms, System.Drawing if (-not ('LogiCursor' -as [type])) { Add-Type -TypeDefinition @' using System; using System.Runtime.InteropServices; public static class LogiCursor { [StructLayout(LayoutKind.Sequential)] public struct POINT { public int X, Y; } [DllImport("user32.dll")] public static extern bool GetCursorPos(out POINT p); [DllImport("user32.dll")] public static extern bool SetCursorPos(int x, int y); [DllImport("user32.dll")] public static extern short GetAsyncKeyState(int vk); public static bool AnyButtonDown() { return (GetAsyncKeyState(1) & 0x8000) != 0 || (GetAsyncKeyState(2) & 0x8000) != 0 || (GetAsyncKeyState(4) & 0x8000) != 0; } [StructLayout(LayoutKind.Sequential)] struct LASTINPUTINFO { public uint cbSize; public uint dwTime; } [DllImport("user32.dll")] static extern bool GetLastInputInfo(ref LASTINPUTINFO i); // Seconds since the last keyboard/mouse input on this PC. public static double IdleSeconds() { var i = new LASTINPUTINFO(); i.cbSize = (uint)Marshal.SizeOf(i); if (!GetLastInputInfo(ref i)) return 0; return unchecked((uint)Environment.TickCount - i.dwTime) / 1000.0; } // Changes every time anything puts something new on the clipboard. Cheap to read. [DllImport("user32.dll")] public static extern uint GetClipboardSequenceNumber(); } '@ } if (-not ('ClipSync' -as [type])) { Add-Type -TypeDefinition @' using System; using System.Collections.Concurrent; using System.IO; using System.Net.Sockets; using System.Security.Cryptography; using System.Text; using System.Threading; // Clipboard sync client. This PC dials OUT to the Mac and keeps one connection open; the Mac // replies down the same socket, so nothing ever has to connect IN to this PC. // Every message: [4-byte length][16-byte IV][AES-256-CBC ciphertext][32-byte HMAC-SHA256]. // Plaintext: [1 type][8-byte unix ms][payload]. Keys come from the shared pairing code. public static class ClipSync { const int MaxMessage = 12 * 1024 * 1024; static Thread worker; static volatile bool running; static string host; static int port; static byte[] encKey, macKey; static NetworkStream stream; static readonly object sendLock = new object(); static readonly ConcurrentQueue incoming = new ConcurrentQueue(); static readonly ConcurrentQueue info = new ConcurrentQueue(); public static volatile string Status = "off"; public static volatile int Connects = 0; // counts successful connections, so the script can send what waited static long connectedTicks; // Seconds the current connection has been up (0 if none). The Mac drops a connection with a wrong // pairing code at once, so one that has lasted a couple of seconds was accepted. public static double ConnectedSeconds() { return Status == "connected" ? (DateTime.UtcNow.Ticks - Interlocked.Read(ref connectedTicks)) / 1e7 : 0; } static bool rejectLogged; // ---- pairing code (Crockford base32, 16 characters, shown in groups of 4) ---- const string Alphabet = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"; public static string NewCode() { var b = new byte[16]; using (var r = RandomNumberGenerator.Create()) r.GetBytes(b); var sb = new StringBuilder(); for (int i = 0; i < 16; i++) { if (i > 0 && i % 4 == 0) sb.Append('-'); sb.Append(Alphabet[b[i] % 32]); } return sb.ToString(); } // Accepts the code however it was typed: lower case, no dashes, O/0 and I/1 mixed up. public static string Normalize(string code) { var sb = new StringBuilder(); foreach (char raw in (code ?? "").ToUpperInvariant()) { char c = raw; if (c == 'I' || c == 'L') c = '1'; else if (c == 'O') c = '0'; else if (c == 'U') c = 'V'; if (Alphabet.IndexOf(c) >= 0) sb.Append(c); } return sb.ToString(); } public static bool CodeLooksValid(string code) { return Normalize(code).Length == 16; } static void SetKeys(string code) { byte[] master; using (var k = new Rfc2898DeriveBytes(Normalize(code), Encoding.ASCII.GetBytes("logiswitch-clipboard-v1"), 200000, HashAlgorithmName.SHA256)) master = k.GetBytes(32); using (var m = new HMACSHA256(master)) encKey = m.ComputeHash(Encoding.ASCII.GetBytes("enc")); using (var m = new HMACSHA256(master)) macKey = m.ComputeHash(Encoding.ASCII.GetBytes("mac")); } // ---- framing ---- static void PutInt32(byte[] dst, int offset, int value) { dst[offset] = (byte)(value >> 24); dst[offset + 1] = (byte)(value >> 16); dst[offset + 2] = (byte)(value >> 8); dst[offset + 3] = (byte)value; } static byte[] Seal(byte type, byte[] payload) { var plain = new byte[9 + payload.Length]; plain[0] = type; long ms = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); for (int i = 0; i < 8; i++) plain[1 + i] = (byte)(ms >> (8 * (7 - i))); Buffer.BlockCopy(payload, 0, plain, 9, payload.Length); var iv = new byte[16]; using (var r = RandomNumberGenerator.Create()) r.GetBytes(iv); byte[] ct; using (var aes = new AesCryptoServiceProvider()) { aes.KeySize = 256; aes.Key = encKey; aes.IV = iv; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; using (var e = aes.CreateEncryptor()) ct = e.TransformFinalBlock(plain, 0, plain.Length); } var body = new byte[16 + ct.Length + 32]; Buffer.BlockCopy(iv, 0, body, 0, 16); Buffer.BlockCopy(ct, 0, body, 16, ct.Length); using (var h = new HMACSHA256(macKey)) { var tag = h.ComputeHash(body, 0, 16 + ct.Length); Buffer.BlockCopy(tag, 0, body, 16 + ct.Length, 32); } var frame = new byte[4 + body.Length]; PutInt32(frame, 0, body.Length); Buffer.BlockCopy(body, 0, frame, 4, body.Length); return frame; } static bool Open(byte[] body, out byte type, out byte[] payload) { type = 0; payload = null; if (body.Length < 16 + 16 + 32 || (body.Length - 48) % 16 != 0) return false; int ctLen = body.Length - 16 - 32; byte[] tag; using (var h = new HMACSHA256(macKey)) tag = h.ComputeHash(body, 0, 16 + ctLen); int diff = 0; for (int i = 0; i < 32; i++) diff |= tag[i] ^ body[16 + ctLen + i]; if (diff != 0) return false; // wrong code, or tampered with var iv = new byte[16]; Buffer.BlockCopy(body, 0, iv, 0, 16); byte[] plain; try { using (var aes = new AesCryptoServiceProvider()) { aes.KeySize = 256; aes.Key = encKey; aes.IV = iv; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; using (var d = aes.CreateDecryptor()) plain = d.TransformFinalBlock(body, 16, ctLen); } } catch { return false; } if (plain.Length < 9) return false; long ms = 0; for (int i = 0; i < 8; i++) ms = (ms << 8) | plain[1 + i]; if (Math.Abs(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - ms) > 120000) return false; // replay type = plain[0]; payload = new byte[plain.Length - 9]; Buffer.BlockCopy(plain, 9, payload, 0, payload.Length); return true; } // ---- connection ---- public static void Start(string h, int p, string code) { Stop(); host = h; port = p; SetKeys(code); running = true; worker = new Thread(Run); worker.IsBackground = true; worker.Start(); } public static void Stop() { running = false; lock (sendLock) { try { if (stream != null) stream.Close(); } catch { } stream = null; } Status = "off"; } public static byte[] TakeIncoming() { byte[] b; return incoming.TryDequeue(out b) ? b : null; } public static string TakeInfo() { string s; return info.TryDequeue(out s) ? s : null; } static void SendRaw(byte[] data) { lock (sendLock) { var s = stream; if (s == null) throw new IOException("not connected"); s.Write(data, 0, data.Length); s.Flush(); } } public static bool SendClipboard(byte[] payload) { try { SendRaw(Seal(0x10, payload)); return true; } catch { return false; } } static bool ReadExact(NetworkStream s, byte[] buf, int n) { int got = 0; while (got < n) { int r; try { r = s.Read(buf, got, n - got); } catch (IOException) { if (got == 0) return false; throw; } // idle timeout between messages if (r <= 0) throw new IOException("the Mac closed the connection"); got += r; } return true; } static void Run() { int backoff = 2000; bool announced = false; bool flapping = false; // connections keep being dropped at once (e.g. the pairing codes differ) while (running) { TcpClient c = null; DateTime connectedAt = DateTime.MinValue; try { c = new TcpClient(); var ar = c.BeginConnect(host, port, null, null); if (!ar.AsyncWaitHandle.WaitOne(4000)) throw new IOException("no answer from " + host + ":" + port); c.EndConnect(ar); c.NoDelay = true; var s = c.GetStream(); s.ReadTimeout = 20000; lock (sendLock) { stream = s; } SendRaw(Seal(0x01, Encoding.UTF8.GetBytes("windows"))); // no computer name is sent connectedAt = DateTime.UtcNow; Interlocked.Exchange(ref connectedTicks, connectedAt.Ticks); Status = "connected"; Connects++; if (!flapping) info.Enqueue("clipboard sync: connected to " + host + ":" + port); var head = new byte[4]; while (running) { if (!ReadExact(s, head, 4)) { // quiet for 20 s: send a keepalive SendRaw(Seal(0x02, new byte[0])); if (flapping) { flapping = false; info.Enqueue("clipboard sync: connected to " + host + ":" + port + " (the Mac accepted the pairing code)"); } continue; } int len = (head[0] << 24) | (head[1] << 16) | (head[2] << 8) | head[3]; if (len < 48 || len > MaxMessage) throw new IOException("unexpected data on the connection"); var body = new byte[len]; if (!ReadExact(s, body, len)) throw new IOException("message cut short"); byte type; byte[] payload; if (!Open(body, out type, out payload)) { if (!rejectLogged) info.Enqueue("ERROR: clipboard sync rejected a message (the two computers' pairing codes do not match, or a clock is more than 2 minutes off)"); rejectLogged = true; throw new IOException("security check failed"); } rejectLogged = false; if (flapping) { flapping = false; info.Enqueue("clipboard sync: connected to " + host + ":" + port + " (the Mac accepted the pairing code)"); } if (type == 0x10) incoming.Enqueue(payload); } } catch (Exception ex) { // A connection that lasted a while ended: start over. One dropped within seconds: keep backing // off (up to 30 s) and stay quiet, so a code mismatch does not fill the log. if (connectedAt != DateTime.MinValue) { if ((DateTime.UtcNow - connectedAt).TotalSeconds >= 10) { backoff = 2000; announced = false; flapping = false; } else flapping = true; } if (running) { Status = "waiting for the Mac"; if (!announced) { info.Enqueue("clipboard sync: " + ex.Message + " - retrying in the background"); announced = true; } } } finally { lock (sendLock) { stream = null; } try { if (c != null) c.Close(); } catch { } } for (int i = 0; i < backoff && running; i += 100) Thread.Sleep(100); if (backoff < 30000) backoff *= 2; } Status = "off"; } } '@ } $logDir = Join-Path $env:LOCALAPPDATA 'LogiSwitch' New-Item -ItemType Directory -Force $logDir | Out-Null $logFile = Join-Path $logDir 'watch.log' function Write-WatchLog($m) { $line = "{0:yyyy-MM-dd HH:mm:ss} {1}" -f (Get-Date), $m; $line; try { Add-Content -Path $logFile -Value $line } catch {} } $mutex = New-Object System.Threading.Mutex($false, 'Local\LogiSwitchEdgeWatcher') if (-not $mutex.WaitOne(0)) { "Another LogiSwitch watcher is already running."; return } # Device cache: remembered across runs so a switch never waits for discovery. $cacheFile = Join-Path $logDir 'devices.json' $cache = @() try { $saved = Get-Content $cacheFile -Raw -ErrorAction Stop | ConvertFrom-Json # PS 5.1 emits JSON arrays as one object; the variable lets foreach enumerate it foreach ($e in $saved) { $cache += [LogiHid]::Make($e.LongPath, $e.Name, [byte]$e.DevIdx, [byte]$e.ChangeHostIdx, [int]$e.HostCount, $e.Transport) } } catch {} foreach ($d in @([LogiHid]::Discover())) { $cache = @($cache | Where-Object { -not ($_.LongPath -eq $d.LongPath -and $_.DevIdx -eq $d.DevIdx) }) + $d } if ($Name) { $cache = @($cache | Where-Object { $n = $_.Name; @($Name | Where-Object { $n -like "*$_*" }).Count -gt 0 }) } $cache = @($cache | Sort-Object { $_.Name -match 'K\d|Keys|Keyboard' }) try { $cache | Select-Object LongPath, Name, DevIdx, ChangeHostIdx, HostCount, Transport | ConvertTo-Json -AsArray -ErrorAction Stop | Set-Content $cacheFile -Encoding utf8 } catch { ConvertTo-Json @($cache | Select-Object LongPath, Name, DevIdx, ChangeHostIdx, HostCount, Transport) | Set-Content $cacheFile -Encoding utf8 } Write-WatchLog ("watching {0} edge -> channel {1}; devices: {2}{3}" -f $Edge, $Channel, (($cache | ForEach-Object Name) -join ', '), $(if ($DryRun) { ' [DRY RUN]' } else { '' })) function Save-DeviceCache { try { ConvertTo-Json @($cache | Select-Object LongPath, Name, DevIdx, ChangeHostIdx, HostCount, Transport) | Set-Content $cacheFile -Encoding utf8 } catch {} } # Background re-discovery (separate runspace, so edge detection never pauses). $refreshEvery = [TimeSpan]::FromMinutes($RefreshMinutes); $nextRefresh = (Get-Date).Add($refreshEvery); $refresh = $null; $refreshHandle = $null $script:lastSwitch = [DateTime]::MinValue function Invoke-LogiSwitch([string]$why, [LogiDev[]]$devices = @($cache)) { if ($DryRun) { Write-WatchLog "$why -> would switch to channel $Channel"; return } if (-not $devices) { Write-WatchLog "ERROR: $why, but no Logitech devices are known yet (none detected on this PC since start-up)"; return } $script:lastSwitch = Get-Date Write-WatchLog "$why -> switching to channel $Channel" $results = @([LogiHid]::SwitchAll([LogiDev[]]@($devices), $Channel)) foreach ($line in $results) { Write-WatchLog $line } if (-not @($results | Where-Object { $_ -like '*: sent*' }).Count) { Write-WatchLog ("ERROR: switch to channel {0} reached no device ({1})" -f $Channel, ($results -join '; ')) } elseif (@($results | Where-Object { $_ -like '*FAILED*' }).Count) { Write-WatchLog ("ERROR: a device did not switch to channel {0} ({1})" -f $Channel, (($results | Where-Object { $_ -like '*FAILED*' }) -join '; ')) } } # "Whichever device you switch, the other follows": a device left this PC because its own # Easy-Switch button was pressed -> send the devices still here to the other computer. function Test-StillHere($d) { if ($d.DevIdx -ne 255) { return $true } $b = @($script:ble | Where-Object { $_.Name -eq $d.Name }) | Select-Object -First 1 if ($b) { return [bool]$b.Up } else { return $true } } function Invoke-Follow([string]$who) { if (((Get-Date) - $script:lastSwitch).TotalSeconds -lt 5) { Write-WatchLog "$who left (part of our own switch)"; return } $idle = [LogiCursor]::IdleSeconds() if ($idle -gt 60) { Write-WatchLog ("$who left while this PC was idle for {0:N0} s - treated as sleep/power-off, nothing follows" -f $idle); return } $others = @($cache | Where-Object { $_.Name -ne $who -and (Test-StillHere $_) }) if (-not $others) { Write-WatchLog "$who left; no other device here to follow it"; return } Invoke-LogiSwitch ("$who switched away -> {0} follow" -f (($others | ForEach-Object Name) -join ' + ')) $others } # Bluetooth devices: Windows reports their live connection state (WinRT), so a mouse or keyboard # switched away with its own Easy-Switch button is noticed within ~0.25 s. $script:ble = @(); $script:bleNames = ''; $script:asTask = $null; $script:lastBlePoll = [DateTime]::MinValue function Update-BleWatch { try { if (-not $script:asTask) { $null = [Windows.Devices.Enumeration.DeviceInformation, Windows.Devices.Enumeration, ContentType = WindowsRuntime] $null = [Windows.Devices.Bluetooth.BluetoothLEDevice, Windows.Devices.Bluetooth, ContentType = WindowsRuntime] Add-Type -AssemblyName System.Runtime.WindowsRuntime $script:asTask = ([System.WindowsRuntimeSystemExtensions].GetMethods() | Where-Object { $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation`1' })[0] } $await = { param($op, $t) $task = $script:asTask.MakeGenericMethod($t).Invoke($null, @($op)); [void]$task.Wait(5000); $task.Result } $sel = [Windows.Devices.Bluetooth.BluetoothLEDevice]::GetDeviceSelectorFromPairingState($true) $infos = & $await ([Windows.Devices.Enumeration.DeviceInformation]::FindAllAsync($sel)) ([Windows.Devices.Enumeration.DeviceInformationCollection]) $les = @(foreach ($di in $infos) { & $await ([Windows.Devices.Bluetooth.BluetoothLEDevice]::FromIdAsync($di.Id)) ([Windows.Devices.Bluetooth.BluetoothLEDevice]) }) $list = @() foreach ($d in @($cache | Where-Object { $_.DevIdx -eq 255 })) { $m = [regex]::Match($d.LongPath, '_([0-9a-f]{12})&col', 'IgnoreCase') if (-not $m.Success) { continue } $le = $les | Where-Object { $_ -and ('{0:x12}' -f $_.BluetoothAddress) -eq $m.Groups[1].Value.ToLower() } | Select-Object -First 1 if ($le) { $list += [pscustomobject]@{ Name = $d.Name; Le = $le; Up = ($le.ConnectionStatus -eq 'Connected') } } } $script:ble = $list $names = ($list | ForEach-Object Name) -join ', ' if ($names -ne $script:bleNames) { $script:bleNames = $names; if ($names) { Write-WatchLog "following Bluetooth devices: $names" } } } catch { Write-WatchLog "Bluetooth connection tracking unavailable: $($_.Exception.Message)" } } [KeyboardFollow]::Watch([LogiDev[]]@($cache)) Update-BleWatch # ---------------- clipboard sync (stage 1: plain text) ---------------- # Payload: [1 byte: number of formats] then, per format, [1 byte format][4-byte big-endian length][data]. # Format 1 = UTF-8 text. Later stages add 2 = HTML, 3 = RTF, 4 = PNG. $script:clipOn = $false; $script:clipSeq = 0; $script:lastClipPoll = [DateTime]::MinValue $script:lastClipText = $null # last text that went either way, so nothing is sent twice or echoed back $script:clipPending = $null # copied here while the Mac was unreachable; sent on the next connection $script:clipConnects = 0 $clipMaxBytes = 1MB function New-ClipPayload([string]$text) { $b = [Text.Encoding]::UTF8.GetBytes($text) $p = New-Object byte[] (6 + $b.Length) $p[0] = 1; $p[1] = 1 $p[2] = [byte](($b.Length -shr 24) -band 0xFF); $p[3] = [byte](($b.Length -shr 16) -band 0xFF) $p[4] = [byte](($b.Length -shr 8) -band 0xFF); $p[5] = [byte]($b.Length -band 0xFF) [Array]::Copy($b, 0, $p, 6, $b.Length) , $p } function Read-ClipPayload([byte[]]$p) { $out = @{} try { $i = 0; $count = $p[$i]; $i++ for ($n = 0; $n -lt $count; $n++) { $fmt = $p[$i]; $i++ $len = ([int]$p[$i] -shl 24) -bor ([int]$p[$i+1] -shl 16) -bor ([int]$p[$i+2] -shl 8) -bor [int]$p[$i+3]; $i += 4 if ($len -lt 0 -or ($i + $len) -gt $p.Length) { break } $d = New-Object byte[] $len; [Array]::Copy($p, $i, $d, 0, $len); $i += $len $out[[int]$fmt] = $d } } catch {} $out } # The clipboard can be locked by whatever app is using it, so every access gets a few tries. function Get-ClipText { for ($i = 0; $i -lt 6; $i++) { try { if ([System.Windows.Forms.Clipboard]::ContainsText()) { return [System.Windows.Forms.Clipboard]::GetText() } else { return $null } } catch { Start-Sleep -Milliseconds 25 } } $null } function Set-ClipText([string]$t) { for ($i = 0; $i -lt 6; $i++) { try { [System.Windows.Forms.Clipboard]::SetText($t); return $true } catch { Start-Sleep -Milliseconds 25 } } $false } if ($ClipboardSync -and [Threading.Thread]::CurrentThread.GetApartmentState() -ne 'STA') { Write-WatchLog 'ERROR: clipboard sync needs the watcher to run with -STA; it is off for this run' $ClipboardSync = $false } if ($ClipboardSync) { $codeFile = Join-Path $logDir 'clipboard-code.txt' $code = try { (Get-Content $codeFile -ErrorAction Stop | Where-Object { $_ -and -not $_.StartsWith('#') } | Select-Object -First 1).Trim() } catch { '' } if (-not $PeerHost) { Write-WatchLog 'ERROR: clipboard sync is on but no Mac address is set (icon menu > Clipboard sync > Set the Mac address)' } elseif (-not [ClipSync]::CodeLooksValid($code)) { Write-WatchLog 'ERROR: clipboard sync is on but the pairing code is missing or malformed (icon menu > Clipboard sync > Pairing code)' } else { [ClipSync]::Start($PeerHost, $PeerPort, $code) $script:clipOn = $true $script:clipSeq = [LogiCursor]::GetClipboardSequenceNumber() Write-WatchLog "clipboard sync: text, dialling out to ${PeerHost}:${PeerPort} (nothing connects in to this PC)" } } $since = $null; $armed = $false; $cooldownUntil = [DateTime]::MinValue; $start = Get-Date # Lines starting with "ERROR:" make the tray icon create a support report automatically. try { while ($true) { Start-Sleep -Milliseconds 20 if ($null -eq $refresh -and (Get-Date) -ge $nextRefresh) { $refresh = [powershell]::Create().AddScript({ [LogiHid]::Discover() }); $refreshHandle = $refresh.BeginInvoke() } if ($null -ne $refresh -and $refreshHandle.IsCompleted) { try { $known = @($cache | ForEach-Object Name) foreach ($d in @($refresh.EndInvoke($refreshHandle))) { if ($Name -and -not @($Name | Where-Object { $d.Name -like "*$_*" }).Count) { continue } $cache = @($cache | Where-Object { -not ($_.LongPath -eq $d.LongPath -and $_.DevIdx -eq $d.DevIdx) }) + $d if ($known -notcontains $d.Name) { Write-WatchLog "learned device: $($d.Name) ($($d.Transport))" } } $cache = @($cache | Sort-Object { $_.Name -match 'K\d|Keys|Keyboard' }); Save-DeviceCache [KeyboardFollow]::Watch([LogiDev[]]@($cache)) # follow keyboards that appeared since start-up Update-BleWatch } catch {} $refresh.Dispose(); $refresh = $null; $nextRefresh = (Get-Date).Add($refreshEvery) } if ($MaxSeconds -gt 0 -and ((Get-Date) - $start).TotalSeconds -ge $MaxSeconds) { break } for ($ev = [KeyboardFollow]::Take(); $ev; $ev = [KeyboardFollow]::Take()) { if ($ev -like 'left:*') { Invoke-Follow $ev.Substring(5) } elseif ($ev -like 'back:*') { Write-WatchLog "$($ev.Substring(5)) is back on this PC" } elseif ($ev -like 'info:*') { Write-WatchLog $ev.Substring(5) } } if ($script:clipOn -and ((Get-Date) - $script:lastClipPoll).TotalMilliseconds -ge 120) { $script:lastClipPoll = Get-Date for ($m = [ClipSync]::TakeInfo(); $m; $m = [ClipSync]::TakeInfo()) { Write-WatchLog $m } # Something arrived from the Mac: put it on this clipboard, and remember the resulting # sequence number so it is not immediately sent straight back. for ($inb = [ClipSync]::TakeIncoming(); $inb; $inb = [ClipSync]::TakeIncoming()) { $parts = Read-ClipPayload $inb if ($parts.ContainsKey(1)) { $txt = [Text.Encoding]::UTF8.GetString($parts[1]) if ($txt.Length -gt 0 -and $txt -cne $script:lastClipText -and (Set-ClipText $txt)) { $script:lastClipText = $txt $script:clipPending = $null # the Mac's newer text replaces what was waiting here $script:clipSeq = [LogiCursor]::GetClipboardSequenceNumber() Write-WatchLog ("clipboard: received {0} characters from the Mac" -f $txt.Length) } } } # Something was copied here: send it over. $seq = [LogiCursor]::GetClipboardSequenceNumber() if ($seq -ne $script:clipSeq) { $script:clipSeq = $seq $txt = Get-ClipText if ($txt -and $txt -cne $script:lastClipText) { $bytes = [Text.Encoding]::UTF8.GetByteCount($txt) if ($bytes -gt $clipMaxBytes) { $script:lastClipText = $txt; Write-WatchLog ("clipboard: {0:N0} KB copied here is too large to sync (limit {1:N0} KB)" -f ($bytes/1KB), ($clipMaxBytes/1KB)) } elseif ([ClipSync]::SendClipboard((New-ClipPayload $txt))) { $script:lastClipText = $txt; $script:clipPending = $null; Write-WatchLog ("clipboard: sent {0} characters to the Mac" -f $txt.Length) } else { $script:clipPending = $txt } # not connected: send it when the Mac is reachable again } } # Just (re)connected: send what was copied here while the Mac could not be reached, if it is still on the clipboard. $conn = [ClipSync]::Connects if ($conn -ne $script:clipConnects -and [ClipSync]::ConnectedSeconds() -ge 2) { $script:clipConnects = $conn $p = $script:clipPending if ($p) { $script:clipPending = $null if ($p -cne $script:lastClipText -and (Get-ClipText) -ceq $p) { if ([ClipSync]::SendClipboard((New-ClipPayload $p))) { $script:lastClipText = $p; Write-WatchLog ("clipboard: sent {0} characters to the Mac (copied while it was not reachable)" -f $p.Length) } else { $script:clipPending = $p } } } } } if ($script:ble -and ((Get-Date) - $script:lastBlePoll).TotalMilliseconds -ge 250) { $script:lastBlePoll = Get-Date foreach ($b in $script:ble) { $up = ($b.Le.ConnectionStatus -eq 'Connected') if ($b.Up -and -not $up) { $b.Up = $false; Invoke-Follow $b.Name } elseif ($up -and -not $b.Up) { $b.Up = $true; Write-WatchLog "$($b.Name) is back on this PC" } } } $now = Get-Date if ($now -lt $cooldownUntil -or [LogiCursor]::AnyButtonDown()) { $since = $null; continue } $p = New-Object LogiCursor+POINT; [void][LogiCursor]::GetCursorPos([ref]$p) $pt = New-Object System.Drawing.Point($p.X, $p.Y) $b = [System.Windows.Forms.Screen]::FromPoint($pt).Bounds $margin = [int]($b.Height * 0.1) $inMiddle = $p.Y -ge ($b.Top + $margin) -and $p.Y -le ($b.Bottom - $margin) if ($Edge -eq 'Right') { $atEdge = $p.X -ge ($b.Right - 1); $beyond = New-Object System.Drawing.Point(($b.Right + 1), $p.Y); $inward = $p.X - 150 } else { $atEdge = $p.X -le $b.Left; $beyond = New-Object System.Drawing.Point(($b.Left - 2), $p.Y); $inward = $p.X + 150 } $outer = $atEdge -and $inMiddle -and -not ([System.Windows.Forms.Screen]::AllScreens | Where-Object { $_.Bounds.Contains($beyond) }) # The cursor stays on the edge after a switch; re-arm only once it has left the edge, # so coming back to this computer never bounces the devices straight back. if (-not $outer) { $since = $null; $armed = $true; continue } if (-not $armed) { continue } if ($null -eq $since) { $since = $now; continue } if (($now - $since).TotalMilliseconds -lt $DwellMs) { continue } $since = $null; $armed = $false; $cooldownUntil = $now.AddSeconds(1) Invoke-LogiSwitch "edge hit at ($($p.X),$($p.Y))" } } catch { Write-WatchLog ("ERROR: watcher crashed: {0} (script line {1})" -f $_.Exception.Message, $_.InvocationInfo.ScriptLineNumber) [ClipSync]::Stop() exit 1 } [ClipSync]::Stop() $mutex.ReleaseMutex() return } $knownFile = Join-Path (Join-Path $env:LOCALAPPDATA 'LogiSwitch') 'devices.json' if ($Fast -and $Channel -gt 0 -and (Test-Path $knownFile)) { $saved = Get-Content $knownFile -Raw | ConvertFrom-Json $devs = @($saved | ForEach-Object { [LogiHid]::Make($_.LongPath, $_.Name, [byte]$_.DevIdx, [byte]$_.ChangeHostIdx, [int]$_.HostCount, $_.Transport) }) } else { $devs = [LogiHid]::Discover() } if ($Name) { $devs = @($devs | Where-Object { $n = $_.Name; @($Name | Where-Object { $n -like "*$_*" }).Count -gt 0 }) } if ($List -or $Channel -eq 0) { if (-not $devs) { "No connected Logitech device supports channel switching on this computer." } $devs | Select-Object Name, Transport, @{n='Channels';e={$_.HostCount}}, @{n='ActiveChannel';e={$_.CurrentHost}} | Format-Table -AutoSize [LogiHid]::Log | ForEach-Object { "note: $_" } return } if (-not $devs) { "No connected Logitech device answered; nothing switched. Move the mouse / press a key to wake them and retry."; [LogiHid]::Log | ForEach-Object { "note: $_" }; return } $already = @($devs | Where-Object { $_.CurrentHost -eq $Channel }) $already | ForEach-Object { "$($_.Name): already on channel $Channel" } $todo = @($devs | Where-Object { $_.CurrentHost -ne $Channel }) if ($todo) { [LogiHid]::SwitchAll([LogiDev[]]$todo, $Channel) }