]> mj.ucw.cz Git - ursary.git/blob - nocturn.c
12ea9c185ca83c5f343bda92001320344b28b137
[ursary.git] / 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 + i, 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 #if 0 // FIXME
329   noct_button_state[2] = 1;
330   noct_ring_mode[0] = 4;
331   noct_ring_val[0] = 0x40;
332 #endif
333
334   noct_dirty_button = 0xffff;
335   noct_dirty_ring_mode = 0xff;
336   noct_dirty_ring_val = 0x1ff;
337   noct_sched_write();
338 }
339
340 static struct main_timer noct_connect_timer;
341 static struct main_hook noct_error_hook;
342
343 static void noct_connect(struct main_timer *t)
344 {
345   timer_del(t);
346   msg(L_DEBUG, "Looking for Nocturn");
347   int err;
348
349   libusb_device **dev_list;
350   libusb_device *found_dev = NULL;
351   ssize_t len = libusb_get_device_list(usb_ctx, &dev_list);
352   for (ssize_t i=0; i < len; i++)
353     {
354       libusb_device *dev = dev_list[i];
355       struct libusb_device_descriptor desc;
356       if (libusb_get_device_descriptor(dev, &desc) >= 0 &&
357           desc.idVendor == 0x1235 &&
358           desc.idProduct == 0x000a)
359         {
360           msg(L_DEBUG, "Found device: bus %d, addr %d", libusb_get_bus_number(dev), libusb_get_device_address(dev));
361           if (found_dev)
362             {
363               msg(L_ERROR, "Multiple Nocturn devices found. Using the first one.");
364               break;
365             }
366           found_dev = libusb_ref_device(dev);
367         }
368     }
369   libusb_free_device_list(dev_list, 1);
370
371   if (!found_dev)
372     {
373       msg(L_INFO, "No Nocturn device found");
374       timer_add_rel(t, 5000);
375       return;
376     }
377
378   msg(L_DEBUG, "Initializing Nocturn");
379
380   if ((err = libusb_open(found_dev, &usb_dev)) < 0)
381     return noct_error(err, "libusb_open failed");
382
383   // There exist configurations 1 (high brightness) and 2 (power-save)
384   if ((err = libusb_set_configuration(usb_dev, 1)) < 0)
385     return noct_error(err, "libusb_set_configuration failed");
386
387   if ((err = libusb_claim_interface(usb_dev, 0)) < 0)
388     return noct_error(err, "libusb_claim_interface failed");
389   usb_iface_claimed = 1;
390
391   for (int i=0; i<4; i++)
392     {
393       int done;
394       if ((err = libusb_interrupt_transfer(usb_dev, 0x02, (byte *) noct_magic[i] + 1, noct_magic[i][0], &done, 5000)) < 0)
395         return noct_error(err, "Cannot send init packets");
396       if (done != noct_magic[i][0])
397         return noct_error(err, stk_printf("Partial send of init packet (%d < %d)", done, noct_magic[i][0]));
398     }
399
400 #if 0
401   byte xxx[] = { 0x7f, 0x01 };
402   int done;
403   libusb_interrupt_transfer(usb_dev, 0x02, xxx, 2, &done, 5000);
404 #endif
405
406   noct_read_init();
407   noct_write_init();
408   schedule_update();
409 }
410
411 static int noct_error_handler(struct main_hook *h)
412 {
413   DBG("Noct: Entered error handling hook");
414   hook_del(h);
415
416   if (usb_dev)
417     {
418       if (noct_read_xfer)
419         {
420           if (noct_read_pending)
421             {
422               DBG("Noct: Cancelling pending read");
423               libusb_cancel_transfer(noct_read_xfer);
424               noct_read_pending = 0;
425             }
426           DBG("Noct: Tearing down read xfer");
427           libusb_free_transfer(noct_read_xfer);
428           noct_read_xfer = NULL;
429         }
430       if (noct_write_xfer)
431         {
432           if (noct_write_pending)
433             {
434               DBG("Noct: Cancelling pending write");
435               libusb_cancel_transfer(noct_write_xfer);
436               noct_write_pending = 0;
437             }
438           DBG("Noct: Tearing down write xfer");
439           libusb_free_transfer(noct_write_xfer);
440           noct_write_xfer = NULL;
441         }
442       if (usb_iface_claimed)
443         {
444           DBG("Noct: Unclaiming interface");
445           libusb_release_interface(usb_dev, 0);
446           usb_iface_claimed = 0;
447         }
448       DBG("Noct: Resetting device");
449       libusb_reset_device(usb_dev);
450       libusb_close(usb_dev);
451       usb_dev = NULL;
452     }
453
454   DBG("Noct: Scheduling rescan after error");
455   timer_add_rel(&noct_connect_timer, 3000);
456
457   return HOOK_IDLE;
458 }
459
460 static void noct_error(int usb_err, char *text)
461 {
462   if (usb_err)
463     msg(L_ERROR, "Nocturn: %s: error %d (%s)", text, usb_err, libusb_error_name(usb_err));
464   else
465     msg(L_ERROR, "Nocturn: %s", text);
466
467   DBG("Noct: Scheduling error handling hook");
468   hook_add(&noct_error_hook);
469 }
470
471 bool noct_is_ready(void)
472 {
473   return !!usb_dev;     // FIXME
474 }
475
476 void noct_init(void)
477 {
478   int err;
479
480   // Initialize libusb
481   if ((err = libusb_init(&usb_ctx)) < 0)
482     die("libusb_init failed: error %d", err);
483   libusb_set_debug(usb_ctx, 3);
484
485   // Connect libusb to UCW mainloop
486
487   if (!libusb_pollfds_handle_timeouts(usb_ctx))
488     die("Unsupported version of libusb, please fix me");
489
490   GARY_INIT_ZERO(usb_fds, 0);
491   libusb_set_pollfd_notifiers(usb_ctx, usb_added_fd, usb_removed_fd, NULL);
492
493   const struct libusb_pollfd **fds = libusb_get_pollfds(usb_ctx);
494   ASSERT(fds);
495   for (int i=0; fds[i]; i++)
496     usb_added_fd(fds[i]->fd, fds[i]->events, NULL);
497   free(fds);
498
499   // Prepare error handling hook
500   noct_error_hook.handler = noct_error_handler;
501
502   // Schedule search for the Nocturn
503   noct_connect_timer.handler = noct_connect;
504   timer_add_rel(&noct_connect_timer, 0);
505 }