]> mj.ucw.cz Git - misc.git/blob - ursaryd/nocturn.c
Ursary: Clients
[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/string.h>
18
19 #include <stdio.h>
20 #include <string.h>
21 #include <stdlib.h>
22 #include <sys/poll.h>
23
24 #include <libusb.h>
25
26 #include "ursaryd.h"
27
28 static libusb_context *usb_ctx;
29 static libusb_device_handle *usb_dev;
30
31 static struct main_file **usb_fds;
32
33 static int usb_fd_ready(struct main_file *f UNUSED)
34 {
35   DBG("USB: Handling events (ready on fd %d)", f->fd);
36   struct timeval tv = { 0, 0 };
37   int comp = 0;
38   int err = libusb_handle_events_timeout_completed(usb_ctx, &tv, &comp);
39   if (err < 0)
40     msg(L_ERROR, "libusb_handle_events: error %d", err);
41   return HOOK_IDLE;
42 }
43
44 static void usb_added_fd(int fd, short events, void *user_data UNUSED)
45 {
46   if (fd >= (int) GARY_SIZE(usb_fds))
47     GARY_RESIZE(usb_fds, fd + 1);
48
49   struct main_file *f = usb_fds[fd];
50   if (!f)
51     {
52       f = xmalloc_zero(sizeof(*f));
53       usb_fds[fd] = f;
54     }
55   else if (file_is_active(f))
56     {
57       DBG("USB: Releasing fd %d", fd);
58       file_del(f);
59     }
60
61   DBG("USB: Adding fd %d with event mask %u", fd, events);
62   f->fd = fd;
63   f->read_handler = (events & POLLIN) ? usb_fd_ready : NULL;
64   f->write_handler = (events & POLLOUT) ? usb_fd_ready : NULL;
65   file_add(f);
66 }
67
68 static void usb_removed_fd(int fd, void *user_data UNUSED)
69 {
70   DBG("USB: Releasing fd %d", fd);
71   ASSERT(fd < (int) GARY_SIZE(usb_fds));
72   struct main_file *f = usb_fds[fd];
73   ASSERT(f);
74   ASSERT(file_is_active(f));
75   file_del(f);
76 }
77
78 static const char noct_magic[4][9] = {
79   { 3, 0xb0, 0x00, 0x00 },
80   { 8, 0x28, 0x00, 0x2b, 0x4a, 0x2c, 0x00, 0x2e, 0x35 },
81   { 6, 0x2a, 0x02, 0x2c, 0x72, 0x2e, 0x30 },
82   { 2, 0x7f, 0x00 },
83 };
84
85 static void noct_read_done(struct libusb_transfer *xfer)
86 {
87   byte *pkt = xfer->buffer;
88   int len = xfer->actual_length;
89   DBG("USB: Read done: status %d, length %d", xfer->status, len);
90
91   if (xfer->status != LIBUSB_TRANSFER_COMPLETED)
92     {
93       msg(L_ERROR, "USB read failed with status %d, not submitting again", xfer->status);
94       return;
95     }
96
97 #ifdef LOCAL_DEBUG
98   char buf[256];
99   mem_to_hex(buf, pkt, len, ' ');
100   DBG("USB: Read <%s>", buf);
101 #endif
102
103   int i = 0;
104   while (i < len)
105     {
106       if (i + 3 > len)
107         {
108           msg(L_ERROR, "Unknown USB packet: length %d not divisible by 3", len);
109           break;
110         }
111       if (pkt[i] != 0xb0)
112         {
113           msg(L_ERROR, "Unknown USB packet: expected 0xb0 at position %d", i);
114           break;
115         }
116       int cmd = pkt[i+1];
117       int arg = pkt[i+2];
118       i += 3;
119       switch (cmd)
120         {
121         case 0x30:
122           // Unknown packet sent during init
123           continue;
124         case 0x40 ... 0x47:
125           if (arg < 0x80)
126             {
127               int r = cmd - 0x40;
128               int delta = (arg < 0x40 ? arg : arg - 0x80);
129               DBG("Noct: Rotary %d = %d", r, delta);
130               notify_rotary(r, delta);
131               continue;
132             }
133           break;
134         case 0x48:
135           if (arg < 0x80)
136             {
137               DBG("Noct: Slider value = %d", arg);
138               continue;
139             }
140           break;
141         case 0x49:
142           // Unknown packet, maybe least significant bit of slider
143           continue;
144         case 0x4a:
145           if (arg < 0x80)
146             {
147               int delta = (arg < 0x40 ? arg : arg - 0x80);
148               DBG("Noct: Center = %d", delta);
149               notify_rotary(8, delta);
150               continue;
151             }
152           break;
153         case 0x52:
154           if (arg == 0x00 || arg == 0x7f)
155             {
156               int state = !!arg;
157               DBG("Noct: Center touch = %d", state);
158               continue;
159             }
160           break;
161         case 0x53:
162           if (arg == 0x00 || arg == 0x7f)
163             {
164               int state = !!arg;
165               DBG("Noct: Slider touch = %d", state);
166               continue;
167             }
168           break;
169         case 0x60 ... 0x67:
170           if (arg == 0x00 || arg == 0x7f)
171             {
172               int r = cmd - 0x60;
173               int state = !!arg;
174               DBG("Noct: Rotary %d touch = %d", r, state);
175               continue;
176             }
177           break;
178         case 0x70 ... 0x7f:
179           if (arg == 0x00 || arg == 0x7f)
180             {
181               int b = cmd - 0x70;
182               int state = !!arg;
183               DBG("Noct: Button %d = %d", b, state);
184               notify_button(b, state);
185               continue;
186             }
187           break;
188         }
189       msg(L_ERROR, "Unknown USB packet: unrecognized cmd=%02x arg=%02x", cmd, arg);
190     }
191
192   int err;
193   if ((err = libusb_submit_transfer(xfer)) < 0)
194     die("Cannot submit transfer: error %d", err);
195 }
196
197 static void noct_read_init(void)
198 {
199   DBG("Noct: Read init");
200
201   struct libusb_transfer *xfer = libusb_alloc_transfer(0);
202   libusb_fill_interrupt_transfer(xfer, usb_dev, 0x81, xmalloc(8), 8, noct_read_done, NULL, 0);
203
204   int err;
205   if ((err = libusb_submit_transfer(xfer)) < 0)
206     die("Cannot submit transfer: error %d", err);
207 }
208
209 static byte noct_button_state[16];
210 static byte noct_ring_mode[8];          // RING_MODE_xxx
211 static byte noct_ring_val[9];
212
213 static uns noct_dirty_button;
214 static uns noct_dirty_ring_mode;
215 static uns noct_dirty_ring_val;
216
217 static struct libusb_transfer *noct_write_xfer;
218 static uns noct_write_pending;
219 static void noct_sched_write(void);
220
221 static void noct_write_done(struct libusb_transfer *xfer)
222 {
223   int len = xfer->actual_length;
224   DBG("USB: Write done: status %d, length %d", xfer->status, len);
225
226   if (xfer->status != LIBUSB_TRANSFER_COMPLETED)
227     {
228       msg(L_ERROR, "USB write failed with status %d", xfer->status);
229       // FIXME: Handle the error in a meaningful way
230       return;
231     }
232   if (len < xfer->length)
233     msg(L_ERROR, "USB partial write: %d out of %d", len, xfer->length);
234
235   noct_write_pending = 0;
236   noct_sched_write();
237 }
238
239 static void noct_do_write(uns cmd, uns arg)
240 {
241   DBG("USB: Submitting write %02x %02x", cmd, arg);
242   ASSERT(!noct_write_pending);
243   noct_write_pending = 1;
244
245   struct libusb_transfer *xfer = noct_write_xfer;
246   byte *pkt = xfer->buffer;
247   pkt[0] = cmd;
248   pkt[1] = arg;
249   xfer->length = 2;
250
251   int err;
252   if ((err = libusb_submit_transfer(xfer)) < 0)
253     die("Cannot submit transfer: error %d", err);
254 }
255
256 static void noct_sched_write(void)
257 {
258   if (noct_write_pending)
259     return;
260
261   if (noct_dirty_button)
262     {
263       int i = bit_ffs(noct_dirty_button);
264       noct_dirty_button ^= 1U << i;
265       noct_do_write(0x70 + i, noct_button_state[i]);
266     }
267   else if (noct_dirty_ring_mode)
268     {
269       int i = bit_ffs(noct_dirty_ring_mode);
270       noct_dirty_ring_mode ^= 1U << i;
271       noct_do_write(0x48 + i, noct_ring_mode[i] << 4);
272     }
273   else if (noct_dirty_ring_val)
274     {
275       int i = bit_ffs(noct_dirty_ring_val);
276       noct_dirty_ring_val ^= 1U << i;
277       if (i == 8)
278         noct_do_write(0x50 + i, noct_ring_val[i]);
279       else
280         noct_do_write(0x40 + i, noct_ring_val[i]);
281     }
282 }
283
284 void noct_set_ring(int ring, int mode, int val)
285 {
286   ASSERT(ring >= 0 && ring <= 8);
287   ASSERT(val >= 0 && val <= 0x7f);
288   ASSERT(mode >= 0 && mode <= 5);
289   ASSERT(ring < 8 || !mode);
290   if (noct_ring_mode[ring] != mode)
291     {
292       noct_ring_mode[ring] = mode;
293       noct_dirty_ring_mode |= 1U << ring;
294       noct_dirty_ring_val |= 1U << ring;        // HW needs to re-send the value
295     }
296   if (noct_ring_val[ring] != val)
297     {
298       noct_ring_val[ring] = val;
299       noct_dirty_ring_val |= 1U << ring;
300     }
301   noct_sched_write();
302 }
303
304 void noct_set_button(int button, int val)
305 {
306   ASSERT(button >= 0 && button < 16);
307   ASSERT(val == 0 || val == 1);
308   if (noct_button_state[button] != val)
309     {
310       noct_button_state[button] = val;
311       noct_dirty_button |= 1U << button;
312       noct_sched_write();
313     }
314 }
315
316 static void noct_write_init(void)
317 {
318   DBG("Noct: Write init");
319
320   noct_write_xfer = libusb_alloc_transfer(0);
321   libusb_fill_interrupt_transfer(noct_write_xfer, usb_dev, 0x02, xmalloc(8), 0, noct_write_done, NULL, 1000);
322
323 #if 0 // FIXME
324   noct_button_state[2] = 1;
325   noct_ring_mode[0] = 4;
326   noct_ring_val[0] = 0x40;
327 #endif
328
329   noct_dirty_button = 0xffff;
330   noct_dirty_ring_mode = 0xff;
331   noct_dirty_ring_val = 0x1ff;
332   noct_sched_write();
333 }
334
335 static struct main_timer noct_connect_timer;
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     die("libusb_open failed: error %d", err);
376
377   // There exist configurations 1 (high brightness) and 2 (power-save)
378   if ((err = libusb_set_configuration(usb_dev, 1)) < 0)
379     die("libusb_set_configuration: error %d", err);
380
381   if ((err = libusb_claim_interface(usb_dev, 0)) < 0)
382     die("libusb_claim_interface: error %d", err);
383
384   for (int i=0; i<4; i++)
385     {
386       int done;
387       if ((err = libusb_interrupt_transfer(usb_dev, 0x02, (byte *) noct_magic[i] + 1, noct_magic[i][0], &done, 5000)) < 0)
388         die("Cannot send init packets: error %d", err);
389       if (done != noct_magic[i][0])
390         die("Partial send of init packet: %d < %d", done, noct_magic[i][0]);
391     }
392
393 #if 0
394   byte xxx[] = { 0x7f, 0x01 };
395   int done;
396   libusb_interrupt_transfer(usb_dev, 0x02, xxx, 2, &done, 5000);
397 #endif
398
399   noct_read_init();
400   noct_write_init();
401   schedule_update();
402 }
403
404 bool noct_is_ready(void)
405 {
406   return !!usb_dev;     // FIXME
407 }
408
409 void noct_init(void)
410 {
411   int err;
412
413   // Initialize libusb
414   if ((err = libusb_init(&usb_ctx)) < 0)
415     die("libusb_init failed: error %d", err);
416   libusb_set_debug(usb_ctx, 3);
417
418   // Connect libusb to UCW mainloop
419
420   if (!libusb_pollfds_handle_timeouts(usb_ctx))
421     die("Unsupported version of libusb, please fix me");
422
423   GARY_INIT_ZERO(usb_fds, 0);
424   libusb_set_pollfd_notifiers(usb_ctx, usb_added_fd, usb_removed_fd, NULL);
425
426   const struct libusb_pollfd **fds = libusb_get_pollfds(usb_ctx);
427   ASSERT(fds);
428   for (int i=0; fds[i]; i++)
429     usb_added_fd(fds[i]->fd, fds[i]->events, NULL);
430   free(fds);
431
432   // Schedule search for the Nocturn
433   noct_connect_timer.handler = noct_connect;
434   timer_add_rel(&noct_connect_timer, 0);
435 }