]> mj.ucw.cz Git - misc.git/blob - ursaryd/nocturn.c
2e93f5c468c5bf36881d47f9fe05f67d925edd51
[misc.git] / ursaryd / nocturn.c
1 /*
2  *      Interface to Novation Nocturn
3  *
4  *      (c) 2014 Martin Mares <mj@ucw.cz>
5  *
6  *      Protocol reverse-engineered by De Wet van Niekerk <dewert@gmail.com>,
7  *      see https://github.com/dewert/nocturn-linux-midi for inspiration.
8  */
9
10 #undef LOCAL_DEBUG
11
12 #include <ucw/lib.h>
13 #include <ucw/bitops.h>
14 #include <ucw/clists.h>
15 #include <ucw/gary.h>
16 #include <ucw/mainloop.h>
17 #include <ucw/stkstring.h>
18 #include <ucw/string.h>
19
20 #include <stdio.h>
21 #include <string.h>
22 #include <stdlib.h>
23 #include <sys/poll.h>
24
25 #include <libusb.h>
26
27 #include "ursaryd.h"
28
29 static libusb_context *usb_ctx;
30 static libusb_device_handle *usb_dev;
31 static bool usb_iface_claimed;
32
33 static void noct_error(int usb_err, char *text);
34
35 static struct main_file **usb_fds;
36
37 static int usb_fd_ready(struct main_file *f UNUSED)
38 {
39   DBG("USB: Handling events (ready on fd %d)", f->fd);
40   struct timeval tv = { 0, 0 };
41   int comp = 0;
42   int err = libusb_handle_events_timeout_completed(usb_ctx, &tv, &comp);
43   if (err < 0)
44     msg(L_ERROR, "libusb_handle_events: error %d", err);
45   return HOOK_IDLE;
46 }
47
48 static void usb_added_fd(int fd, short events, void *user_data UNUSED)
49 {
50   if (fd >= (int) GARY_SIZE(usb_fds))
51     GARY_RESIZE(usb_fds, fd + 1);
52
53   struct main_file *f = usb_fds[fd];
54   if (!f)
55     {
56       f = xmalloc_zero(sizeof(*f));
57       usb_fds[fd] = f;
58     }
59   else if (file_is_active(f))
60     {
61       DBG("USB: Releasing fd %d", fd);
62       file_del(f);
63     }
64
65   DBG("USB: Adding fd %d with event mask %u", fd, events);
66   f->fd = fd;
67   f->read_handler = (events & POLLIN) ? usb_fd_ready : NULL;
68   f->write_handler = (events & POLLOUT) ? usb_fd_ready : NULL;
69   file_add(f);
70 }
71
72 static void usb_removed_fd(int fd, void *user_data UNUSED)
73 {
74   DBG("USB: Releasing fd %d", fd);
75   ASSERT(fd < (int) GARY_SIZE(usb_fds));
76   struct main_file *f = usb_fds[fd];
77   ASSERT(f);
78   ASSERT(file_is_active(f));
79   file_del(f);
80 }
81
82 static const char noct_magic[4][9] = {
83   { 3, 0xb0, 0x00, 0x00 },
84   { 8, 0x28, 0x00, 0x2b, 0x4a, 0x2c, 0x00, 0x2e, 0x35 },
85   { 6, 0x2a, 0x02, 0x2c, 0x72, 0x2e, 0x30 },
86   { 2, 0x7f, 0x00 },
87 };
88
89 static struct libusb_transfer *noct_read_xfer;
90 static bool noct_read_pending;
91
92 static void noct_read_done(struct libusb_transfer *xfer)
93 {
94   byte *pkt = xfer->buffer;
95   int len = xfer->actual_length;
96   DBG("USB: Read done: status %d, length %d", xfer->status, len);
97   noct_read_pending = 0;
98
99   if (xfer->status != LIBUSB_TRANSFER_COMPLETED)
100     return noct_error(0, stk_printf("USB read failed with status %d", xfer->status));
101
102 #ifdef LOCAL_DEBUG
103   char buf[256];
104   mem_to_hex(buf, pkt, len, ' ');
105   DBG("USB: Read <%s>", buf);
106 #endif
107
108   int i = 0;
109   while (i < len)
110     {
111       if (i + 3 > len)
112         {
113           msg(L_ERROR, "Unknown USB packet: length %d not divisible by 3", len);
114           break;
115         }
116       if (pkt[i] != 0xb0)
117         {
118           msg(L_ERROR, "Unknown USB packet: expected 0xb0 at position %d", i);
119           break;
120         }
121       int cmd = pkt[i+1];
122       int arg = pkt[i+2];
123       i += 3;
124       switch (cmd)
125         {
126         case 0x30:
127           // Unknown packet sent during init
128           continue;
129         case 0x40 ... 0x47:
130           if (arg < 0x80)
131             {
132               int r = cmd - 0x40;
133               int delta = (arg < 0x40 ? arg : arg - 0x80);
134               DBG("Noct: Rotary %d = %d", r, delta);
135               notify_rotary(r, delta);
136               continue;
137             }
138           break;
139         case 0x48:
140           if (arg < 0x80)
141             {
142               DBG("Noct: Slider value = %d", arg);
143               continue;
144             }
145           break;
146         case 0x49:
147           // Unknown packet, maybe least significant bit of slider
148           continue;
149         case 0x4a:
150           if (arg < 0x80)
151             {
152               int delta = (arg < 0x40 ? arg : arg - 0x80);
153               DBG("Noct: Center = %d", delta);
154               notify_rotary(8, delta);
155               continue;
156             }
157           break;
158         case 0x52:
159           if (arg == 0x00 || arg == 0x7f)
160             {
161               int state = !!arg;
162               DBG("Noct: Center touch = %d", state);
163               continue;
164             }
165           break;
166         case 0x53:
167           if (arg == 0x00 || arg == 0x7f)
168             {
169               int state = !!arg;
170               DBG("Noct: Slider touch = %d", state);
171               continue;
172             }
173           break;
174         case 0x60 ... 0x67:
175           if (arg == 0x00 || arg == 0x7f)
176             {
177               int r = cmd - 0x60;
178               int state = !!arg;
179               DBG("Noct: Rotary %d touch = %d", r, state);
180               continue;
181             }
182           break;
183         case 0x70 ... 0x7f:
184           if (arg == 0x00 || arg == 0x7f)
185             {
186               int b = cmd - 0x70;
187               int state = !!arg;
188               DBG("Noct: Button %d = %d", b, state);
189               notify_button(b, state);
190               continue;
191             }
192           break;
193         }
194       msg(L_ERROR, "Unknown USB packet: unrecognized cmd=%02x arg=%02x", cmd, arg);
195     }
196
197   int err;
198   if ((err = libusb_submit_transfer(xfer)) < 0)
199     noct_error(err, "Cannot submit transfer");
200   else
201     noct_read_pending = 1;
202 }
203
204 static void noct_read_init(void)
205 {
206   DBG("Noct: Read init");
207
208   noct_read_xfer = libusb_alloc_transfer(0);
209   libusb_fill_interrupt_transfer(noct_read_xfer, usb_dev, 0x81, xmalloc(8), 8, noct_read_done, NULL, 0);
210
211   int err;
212   if ((err = libusb_submit_transfer(noct_read_xfer)) < 0)
213     noct_error(err, "Cannot submit transfer");
214   else
215     noct_read_pending = 1;
216 }
217
218 static byte noct_button_state[16];
219 static byte noct_ring_mode[8];          // RING_MODE_xxx
220 static byte noct_ring_val[9];
221
222 static uns noct_dirty_button;
223 static uns noct_dirty_ring_mode;
224 static uns noct_dirty_ring_val;
225
226 static struct libusb_transfer *noct_write_xfer;
227 static bool noct_write_pending;
228 static void noct_sched_write(void);
229
230 static void noct_write_done(struct libusb_transfer *xfer)
231 {
232   int len = xfer->actual_length;
233   DBG("USB: Write done: status %d, length %d", xfer->status, len);
234
235   if (xfer->status != LIBUSB_TRANSFER_COMPLETED)
236     return noct_error(0, stk_printf("USB write failed with status %d", xfer->status));
237   if (len < xfer->length)
238     msg(L_ERROR, "USB partial write: %d out of %d", len, xfer->length);
239
240   noct_write_pending = 0;
241   noct_sched_write();
242 }
243
244 static void noct_do_write(uns cmd, uns arg)
245 {
246   DBG("USB: Submitting write %02x %02x", cmd, arg);
247   ASSERT(!noct_write_pending);
248   noct_write_pending = 1;
249
250   struct libusb_transfer *xfer = noct_write_xfer;
251   byte *pkt = xfer->buffer;
252   pkt[0] = cmd;
253   pkt[1] = arg;
254   xfer->length = 2;
255
256   int err;
257   if ((err = libusb_submit_transfer(xfer)) < 0)
258     noct_error(err, "Cannot submit transfer");
259 }
260
261 static void noct_sched_write(void)
262 {
263   if (noct_write_pending)
264     return;
265
266   if (noct_dirty_button)
267     {
268       int i = bit_ffs(noct_dirty_button);
269       noct_dirty_button ^= 1U << i;
270       noct_do_write(0x70 + i, noct_button_state[i]);
271     }
272   else if (noct_dirty_ring_mode)
273     {
274       int i = bit_ffs(noct_dirty_ring_mode);
275       noct_dirty_ring_mode ^= 1U << i;
276       noct_do_write(0x48 + i, noct_ring_mode[i] << 4);
277     }
278   else if (noct_dirty_ring_val)
279     {
280       int i = bit_ffs(noct_dirty_ring_val);
281       noct_dirty_ring_val ^= 1U << i;
282       if (i == 8)
283         noct_do_write(0x50, noct_ring_val[i]);
284       else
285         noct_do_write(0x40 + i, noct_ring_val[i]);
286     }
287 }
288
289 void noct_set_ring(int ring, int mode, int val)
290 {
291   ASSERT(ring >= 0 && ring <= 8);
292   ASSERT(val >= 0 && val <= 0x7f);
293   ASSERT(mode >= 0 && mode <= 5);
294   ASSERT(ring < 8 || !mode);
295   if (noct_ring_mode[ring] != mode)
296     {
297       noct_ring_mode[ring] = mode;
298       noct_dirty_ring_mode |= 1U << ring;
299       noct_dirty_ring_val |= 1U << ring;        // HW needs to re-send the value
300     }
301   if (noct_ring_val[ring] != val)
302     {
303       noct_ring_val[ring] = val;
304       noct_dirty_ring_val |= 1U << ring;
305     }
306   noct_sched_write();
307 }
308
309 void noct_set_button(int button, int val)
310 {
311   ASSERT(button >= 0 && button < 16);
312   ASSERT(val == 0 || val == 1);
313   if (noct_button_state[button] != val)
314     {
315       noct_button_state[button] = val;
316       noct_dirty_button |= 1U << button;
317       noct_sched_write();
318     }
319 }
320
321 static void noct_write_init(void)
322 {
323   DBG("Noct: Write init");
324
325   noct_write_xfer = libusb_alloc_transfer(0);
326   libusb_fill_interrupt_transfer(noct_write_xfer, usb_dev, 0x02, xmalloc(8), 0, noct_write_done, NULL, 1000);
327
328   noct_dirty_button = 0xffff;
329   noct_dirty_ring_mode = 0xff;
330   noct_dirty_ring_val = 0x1ff;
331   noct_sched_write();
332 }
333
334 static struct main_timer noct_connect_timer;
335 static struct main_hook noct_error_hook;
336
337 static void noct_connect(struct main_timer *t)
338 {
339   timer_del(t);
340   msg(L_DEBUG, "Looking for Nocturn");
341   int err;
342
343   libusb_device **dev_list;
344   libusb_device *found_dev = NULL;
345   ssize_t len = libusb_get_device_list(usb_ctx, &dev_list);
346   for (ssize_t i=0; i < len; i++)
347     {
348       libusb_device *dev = dev_list[i];
349       struct libusb_device_descriptor desc;
350       if (libusb_get_device_descriptor(dev, &desc) >= 0 &&
351           desc.idVendor == 0x1235 &&
352           desc.idProduct == 0x000a)
353         {
354           msg(L_DEBUG, "Found device: bus %d, addr %d", libusb_get_bus_number(dev), libusb_get_device_address(dev));
355           if (found_dev)
356             {
357               msg(L_ERROR, "Multiple Nocturn devices found. Using the first one.");
358               break;
359             }
360           found_dev = libusb_ref_device(dev);
361         }
362     }
363   libusb_free_device_list(dev_list, 1);
364
365   if (!found_dev)
366     {
367       msg(L_INFO, "No Nocturn device found");
368       timer_add_rel(t, 5000);
369       return;
370     }
371
372   msg(L_DEBUG, "Initializing Nocturn");
373
374   if ((err = libusb_open(found_dev, &usb_dev)) < 0)
375     return noct_error(err, "libusb_open failed");
376
377   // There exist configurations 1 (high brightness) and 2 (power-save)
378   if ((err = libusb_set_configuration(usb_dev, 2)) < 0)
379     return noct_error(err, "libusb_set_configuration failed");
380
381   if ((err = libusb_claim_interface(usb_dev, 0)) < 0)
382     return noct_error(err, "libusb_claim_interface failed");
383   usb_iface_claimed = 1;
384
385   for (int i=0; i<4; i++)
386     {
387       int done;
388       if ((err = libusb_interrupt_transfer(usb_dev, 0x02, (byte *) noct_magic[i] + 1, noct_magic[i][0], &done, 5000)) < 0)
389         return noct_error(err, "Cannot send init packets");
390       if (done != noct_magic[i][0])
391         return noct_error(err, stk_printf("Partial send of init packet (%d < %d)", done, noct_magic[i][0]));
392     }
393
394   noct_read_init();
395   noct_write_init();
396   schedule_update();
397 }
398
399 static int noct_error_handler(struct main_hook *h)
400 {
401   DBG("Noct: Entered error handling hook");
402   hook_del(h);
403
404   if (usb_dev)
405     {
406       if (noct_read_xfer)
407         {
408           if (noct_read_pending)
409             {
410               DBG("Noct: Cancelling pending read");
411               libusb_cancel_transfer(noct_read_xfer);
412               noct_read_pending = 0;
413             }
414           DBG("Noct: Tearing down read xfer");
415           xfree(noct_read_xfer->buffer);
416           libusb_free_transfer(noct_read_xfer);
417           noct_read_xfer = NULL;
418         }
419       if (noct_write_xfer)
420         {
421           if (noct_write_pending)
422             {
423               DBG("Noct: Cancelling pending write");
424               libusb_cancel_transfer(noct_write_xfer);
425               noct_write_pending = 0;
426             }
427           DBG("Noct: Tearing down write xfer");
428           xfree(noct_write_xfer->buffer);
429           libusb_free_transfer(noct_write_xfer);
430           noct_write_xfer = NULL;
431         }
432       if (usb_iface_claimed)
433         {
434           DBG("Noct: Unclaiming interface");
435           libusb_release_interface(usb_dev, 0);
436           usb_iface_claimed = 0;
437         }
438       DBG("Noct: Resetting device");
439       libusb_reset_device(usb_dev);
440       libusb_close(usb_dev);
441       usb_dev = NULL;
442     }
443
444   DBG("Noct: Scheduling rescan after error");
445   timer_add_rel(&noct_connect_timer, 3000);
446
447   return HOOK_IDLE;
448 }
449
450 static void noct_error(int usb_err, char *text)
451 {
452   if (usb_err)
453     msg(L_ERROR, "Nocturn: %s: error %d (%s)", text, usb_err, libusb_error_name(usb_err));
454   else
455     msg(L_ERROR, "Nocturn: %s", text);
456
457   DBG("Noct: Scheduling error handling hook");
458   hook_add(&noct_error_hook);
459 }
460
461 bool noct_is_ready(void)
462 {
463   return !!usb_dev;
464 }
465
466 void noct_init(void)
467 {
468   int err;
469
470   // Initialize libusb
471   if ((err = libusb_init(&usb_ctx)) < 0)
472     die("libusb_init failed: error %d", err);
473   libusb_set_debug(usb_ctx, 3);
474
475   // Connect libusb to UCW mainloop
476
477   if (!libusb_pollfds_handle_timeouts(usb_ctx))
478     die("Unsupported version of libusb, please fix me");
479
480   GARY_INIT_ZERO(usb_fds, 0);
481   libusb_set_pollfd_notifiers(usb_ctx, usb_added_fd, usb_removed_fd, NULL);
482
483   const struct libusb_pollfd **fds = libusb_get_pollfds(usb_ctx);
484   ASSERT(fds);
485   for (int i=0; fds[i]; i++)
486     usb_added_fd(fds[i]->fd, fds[i]->events, NULL);
487   free(fds);
488
489   // Prepare error handling hook
490   noct_error_hook.handler = noct_error_handler;
491
492   // Schedule search for the Nocturn
493   noct_connect_timer.handler = noct_connect;
494   timer_add_rel(&noct_connect_timer, 100);
495 }