]> mj.ucw.cz Git - ursary.git/blob - nocturn.c
Added udev rules
[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 char noct_rotary_touched[10];
92 char noct_button_pressed[16];
93
94 static void noct_read_done(struct libusb_transfer *xfer)
95 {
96   byte *pkt = xfer->buffer;
97   int len = xfer->actual_length;
98   DBG("USB: Read done: status %d, length %d", xfer->status, len);
99   noct_read_pending = 0;
100
101   if (xfer->status != LIBUSB_TRANSFER_COMPLETED)
102     return noct_error(0, stk_printf("USB read failed with status %d", xfer->status));
103
104 #ifdef LOCAL_DEBUG
105   char buf[256];
106   mem_to_hex(buf, pkt, len, ' ');
107   DBG("USB: Read <%s>", buf);
108 #endif
109
110   int i = 0;
111   while (i < len)
112     {
113       if (i + 3 > len)
114         {
115           msg(L_ERROR, "Unknown USB packet: length %d not divisible by 3", len);
116           break;
117         }
118       if (pkt[i] != 0xb0)
119         {
120           msg(L_ERROR, "Unknown USB packet: expected 0xb0 at position %d", i);
121           break;
122         }
123       int cmd = pkt[i+1];
124       int arg = pkt[i+2];
125       i += 3;
126       switch (cmd)
127         {
128         case 0x30:
129           // Unknown packet sent during init
130           continue;
131         case 0x40 ... 0x47:
132           if (arg < 0x80)
133             {
134               int r = cmd - 0x40;
135               int delta = (arg < 0x40 ? arg : arg - 0x80);
136               DBG("Noct: Rotary %d = %d", r, delta);
137               notify_rotary(r, delta);
138               continue;
139             }
140           break;
141         case 0x48:
142           if (arg < 0x80)
143             {
144               DBG("Noct: Slider value = %d", arg);
145               notify_rotary(9, arg);
146               continue;
147             }
148           break;
149         case 0x49:
150           // Unknown packet, maybe least significant bit of slider
151           continue;
152         case 0x4a:
153           if (arg < 0x80)
154             {
155               int delta = (arg < 0x40 ? arg : arg - 0x80);
156               DBG("Noct: Center = %d", delta);
157               notify_rotary(8, delta);
158               continue;
159             }
160           break;
161         case 0x52:
162           if (arg == 0x00 || arg == 0x7f)
163             {
164               int state = !!arg;
165               DBG("Noct: Center touch = %d", state);
166               noct_rotary_touched[8] = state;
167               notify_touch(8, state);
168               continue;
169             }
170           break;
171         case 0x53:
172           if (arg == 0x00 || arg == 0x7f)
173             {
174               int state = !!arg;
175               DBG("Noct: Slider touch = %d", state);
176               noct_rotary_touched[9] = state;
177               notify_touch(9, state);
178               continue;
179             }
180           break;
181         case 0x60 ... 0x67:
182           if (arg == 0x00 || arg == 0x7f)
183             {
184               int r = cmd - 0x60;
185               int state = !!arg;
186               DBG("Noct: Rotary %d touch = %d", r, state);
187               noct_rotary_touched[r] = state;
188               notify_touch(r, state);
189               continue;
190             }
191           break;
192         case 0x70 ... 0x7f:
193           if (arg == 0x00 || arg == 0x7f)
194             {
195               int b = cmd - 0x70;
196               int state = !!arg;
197               DBG("Noct: Button %d = %d", b, state);
198               noct_button_pressed[b] = state;
199               notify_button(b, state);
200               continue;
201             }
202           break;
203         }
204       msg(L_ERROR, "Unknown USB packet: unrecognized cmd=%02x arg=%02x", cmd, arg);
205     }
206
207   int err;
208   if ((err = libusb_submit_transfer(xfer)) < 0)
209     noct_error(err, "Cannot submit transfer");
210   else
211     noct_read_pending = 1;
212 }
213
214 static void noct_read_init(void)
215 {
216   DBG("Noct: Read init");
217
218   noct_read_xfer = libusb_alloc_transfer(0);
219   libusb_fill_interrupt_transfer(noct_read_xfer, usb_dev, 0x81, xmalloc(8), 8, noct_read_done, NULL, 0);
220
221   int err;
222   if ((err = libusb_submit_transfer(noct_read_xfer)) < 0)
223     noct_error(err, "Cannot submit transfer");
224   else
225     noct_read_pending = 1;
226 }
227
228 static byte noct_button_light[16];
229 static byte noct_ring_mode[8];          // RING_MODE_xxx
230 static byte noct_ring_val[9];
231
232 static uint noct_dirty_button;
233 static uint noct_dirty_ring_mode;
234 static uint noct_dirty_ring_val;
235
236 static struct libusb_transfer *noct_write_xfer;
237 static bool noct_write_pending;
238 static void noct_sched_write(void);
239
240 static void noct_write_done(struct libusb_transfer *xfer)
241 {
242   int len = xfer->actual_length;
243   DBG("USB: Write done: status %d, length %d", xfer->status, len);
244
245   if (xfer->status != LIBUSB_TRANSFER_COMPLETED)
246     return noct_error(0, stk_printf("USB write failed with status %d", xfer->status));
247   if (len < xfer->length)
248     msg(L_ERROR, "USB partial write: %d out of %d", len, xfer->length);
249
250   noct_write_pending = 0;
251   noct_sched_write();
252 }
253
254 static void noct_do_write(uint cmd, uint arg)
255 {
256   DBG("USB: Submitting write %02x %02x", cmd, arg);
257   ASSERT(!noct_write_pending);
258   noct_write_pending = 1;
259
260   struct libusb_transfer *xfer = noct_write_xfer;
261   byte *pkt = xfer->buffer;
262   pkt[0] = cmd;
263   pkt[1] = arg;
264   xfer->length = 2;
265
266   int err;
267   if ((err = libusb_submit_transfer(xfer)) < 0)
268     noct_error(err, "Cannot submit transfer");
269 }
270
271 static void noct_sched_write(void)
272 {
273   if (!usb_dev || noct_write_pending)
274     return;
275
276   if (noct_dirty_button)
277     {
278       int i = bit_ffs(noct_dirty_button);
279       noct_dirty_button ^= 1U << i;
280       noct_do_write(0x70 + i, noct_button_light[i]);
281     }
282   else if (noct_dirty_ring_mode)
283     {
284       int i = bit_ffs(noct_dirty_ring_mode);
285       noct_dirty_ring_mode ^= 1U << i;
286       noct_do_write(0x48 + i, noct_ring_mode[i] << 4);
287     }
288   else if (noct_dirty_ring_val)
289     {
290       int i = bit_ffs(noct_dirty_ring_val);
291       noct_dirty_ring_val ^= 1U << i;
292       if (i == 8)
293         noct_do_write(0x50, noct_ring_val[i]);
294       else
295         noct_do_write(0x40 + i, noct_ring_val[i]);
296     }
297 }
298
299 void noct_set_ring(int ring, int mode, int val)
300 {
301   ASSERT(ring >= 0 && ring <= 8);
302   ASSERT(val >= 0 && val <= 0x7f);
303   ASSERT(mode >= 0 && mode <= 5);
304   ASSERT(ring < 8 || !mode);
305   if (noct_ring_mode[ring] != mode)
306     {
307       noct_ring_mode[ring] = mode;
308       noct_dirty_ring_mode |= 1U << ring;
309       noct_dirty_ring_val |= 1U << ring;        // HW needs to re-send the value
310     }
311   if (noct_ring_val[ring] != val)
312     {
313       noct_ring_val[ring] = val;
314       noct_dirty_ring_val |= 1U << ring;
315     }
316   noct_sched_write();
317 }
318
319 void noct_set_button(int button, int val)
320 {
321   ASSERT(button >= 0 && button < 16);
322   ASSERT(val == 0 || val == 1);
323   if (noct_button_light[button] != val)
324     {
325       noct_button_light[button] = val;
326       noct_dirty_button |= 1U << button;
327       noct_sched_write();
328     }
329 }
330
331 void noct_clear(void)
332 {
333   for (int i=0; i<=8; i++)
334     noct_set_ring(i, RING_MODE_LEFT, 0);
335   for (int i=0; i<16; i++)
336     noct_set_button(i, 0);
337 }
338
339 static void noct_write_init(void)
340 {
341   DBG("Noct: Write init");
342
343   noct_write_xfer = libusb_alloc_transfer(0);
344   libusb_fill_interrupt_transfer(noct_write_xfer, usb_dev, 0x02, xmalloc(8), 0, noct_write_done, NULL, 1000);
345
346   bzero(noct_button_pressed, sizeof(noct_button_pressed));
347   bzero(noct_rotary_touched, sizeof(noct_rotary_touched));
348   noct_dirty_button = 0xffff;
349   noct_dirty_ring_mode = 0xff;
350   noct_dirty_ring_val = 0x1ff;
351   noct_sched_write();
352 }
353
354 static struct main_timer noct_connect_timer;
355 static struct main_hook noct_error_hook;
356
357 static void noct_connect(struct main_timer *t)
358 {
359   timer_del(t);
360   msg(L_DEBUG, "Looking for Nocturn");
361   int err;
362
363   libusb_device **dev_list;
364   libusb_device *found_dev = NULL;
365   ssize_t len = libusb_get_device_list(usb_ctx, &dev_list);
366   for (ssize_t i=0; i < len; i++)
367     {
368       libusb_device *dev = dev_list[i];
369       struct libusb_device_descriptor desc;
370       if (libusb_get_device_descriptor(dev, &desc) >= 0 &&
371           desc.idVendor == 0x1235 &&
372           desc.idProduct == 0x000a)
373         {
374           msg(L_INFO, "Nocturn found at bus %d, addr %d", libusb_get_bus_number(dev), libusb_get_device_address(dev));
375           if (found_dev)
376             {
377               msg(L_ERROR, "Multiple Nocturn devices found. Using the first one.");
378               break;
379             }
380           found_dev = libusb_ref_device(dev);
381         }
382     }
383   libusb_free_device_list(dev_list, 1);
384
385   if (!found_dev)
386     {
387       msg(L_INFO, "No Nocturn device found");
388       timer_add_rel(t, 5000);
389       return;
390     }
391
392   DBG("Initializing Nocturn");
393
394   if ((err = libusb_open(found_dev, &usb_dev)) < 0)
395     return noct_error(err, "libusb_open failed");
396
397   // There exist configurations 1 (high brightness) and 2 (power-save)
398   if ((err = libusb_set_configuration(usb_dev, 2)) < 0)
399     return noct_error(err, "libusb_set_configuration failed");
400
401   if ((err = libusb_claim_interface(usb_dev, 0)) < 0)
402     return noct_error(err, "libusb_claim_interface failed");
403   usb_iface_claimed = 1;
404
405   for (int i=0; i<4; i++)
406     {
407       int done;
408       if ((err = libusb_interrupt_transfer(usb_dev, 0x02, (byte *) noct_magic[i] + 1, noct_magic[i][0], &done, 5000)) < 0)
409         return noct_error(err, "Cannot send init packets");
410       if (done != noct_magic[i][0])
411         return noct_error(err, stk_printf("Partial send of init packet (%d < %d)", done, noct_magic[i][0]));
412     }
413
414   noct_read_init();
415   noct_write_init();
416   schedule_update();
417 }
418
419 static int noct_error_handler(struct main_hook *h)
420 {
421   DBG("Noct: Entered error handling hook");
422   hook_del(h);
423
424   if (usb_dev)
425     {
426       if (noct_read_xfer)
427         {
428           if (noct_read_pending)
429             {
430               DBG("Noct: Cancelling pending read");
431               libusb_cancel_transfer(noct_read_xfer);
432               noct_read_pending = 0;
433             }
434           DBG("Noct: Tearing down read xfer");
435           xfree(noct_read_xfer->buffer);
436           libusb_free_transfer(noct_read_xfer);
437           noct_read_xfer = NULL;
438         }
439       if (noct_write_xfer)
440         {
441           if (noct_write_pending)
442             {
443               DBG("Noct: Cancelling pending write");
444               libusb_cancel_transfer(noct_write_xfer);
445               noct_write_pending = 0;
446             }
447           DBG("Noct: Tearing down write xfer");
448           xfree(noct_write_xfer->buffer);
449           libusb_free_transfer(noct_write_xfer);
450           noct_write_xfer = NULL;
451         }
452       if (usb_iface_claimed)
453         {
454           DBG("Noct: Unclaiming interface");
455           libusb_release_interface(usb_dev, 0);
456           usb_iface_claimed = 0;
457         }
458       DBG("Noct: Resetting device");
459       libusb_reset_device(usb_dev);
460       libusb_close(usb_dev);
461       usb_dev = NULL;
462     }
463
464   DBG("Noct: Scheduling rescan after error");
465   timer_add_rel(&noct_connect_timer, 3000);
466
467   return HOOK_IDLE;
468 }
469
470 static void noct_error(int usb_err, char *text)
471 {
472   if (usb_err)
473     msg(L_ERROR, "Nocturn: %s: error %d (%s)", text, usb_err, libusb_error_name(usb_err));
474   else
475     msg(L_ERROR, "Nocturn: %s", text);
476
477   DBG("Noct: Scheduling error handling hook");
478   hook_add(&noct_error_hook);
479 }
480
481 bool noct_is_ready(void)
482 {
483   return !!usb_dev;
484 }
485
486 void noct_init(void)
487 {
488   int err;
489
490   // Initialize libusb
491   if ((err = libusb_init(&usb_ctx)) < 0)
492     die("libusb_init failed: error %d", err);
493   libusb_set_debug(usb_ctx, 3);
494
495   // Connect libusb to UCW mainloop
496
497   if (!libusb_pollfds_handle_timeouts(usb_ctx))
498     die("Unsupported version of libusb, please fix me");
499
500   GARY_INIT_ZERO(usb_fds, 0);
501   libusb_set_pollfd_notifiers(usb_ctx, usb_added_fd, usb_removed_fd, NULL);
502
503   const struct libusb_pollfd **fds = libusb_get_pollfds(usb_ctx);
504   ASSERT(fds);
505   for (int i=0; fds[i]; i++)
506     usb_added_fd(fds[i]->fd, fds[i]->events, NULL);
507   free(fds);
508
509   // Prepare error handling hook
510   noct_error_hook.handler = noct_error_handler;
511
512   // Schedule search for the Nocturn
513   noct_connect_timer.handler = noct_connect;
514   timer_add_rel(&noct_connect_timer, 100);
515 }