Welcome to mirror list, hosted at ThFree Co, Russian Federation.

usb_hidapi.c « avrdude « src - github.com/prusa3d/PrusaSlicer.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 81e9c4abe80d821f2f4cfa9e10f88991b0915953 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
/*
 * avrdude - A Downloader/Uploader for AVR device programmers
 * Copyright (C) 2016 Joerg Wunsch
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

/* $Id$ */

/*
 * USB interface via libhidapi for avrdude.
 */

#include "ac_cfg.h"
#if defined(HAVE_LIBHIDAPI)


#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/time.h>
#include <wchar.h>

#include <hidapi/hidapi.h>

#include "avrdude.h"
#include "libavrdude.h"

#include "usbdevs.h"

#if defined(WIN32NATIVE)
/* someone has defined "interface" to "struct" in Cygwin */
#  undef interface
#endif

/*
 * The "baud" parameter is meaningless for USB devices, so we reuse it
 * to pass the desired USB device ID.
 */
static int usbhid_open(char * port, union pinfo pinfo, union filedescriptor *fd)
{
  hid_device *dev;
  char *serno, *cp2;
  size_t x;
  unsigned char usbbuf[USBDEV_MAX_XFER_3 + 1];

  if (fd->usb.max_xfer == 0)
    fd->usb.max_xfer = USBDEV_MAX_XFER_3;

  /*
   * The syntax for usb devices is defined as:
   *
   * -P usb[:serialnumber]
   *
   * See if we've got a serial number passed here.  The serial number
   * might contain colons which we remove below, and we compare it
   * right-to-left, so only the least significant nibbles need to be
   * specified.
   */
  if ((serno = strchr(port, ':')) != NULL)
    {
      /* first, drop all colons there if any */
      cp2 = ++serno;

      while ((cp2 = strchr(cp2, ':')) != NULL)
	{
	  x = strlen(cp2) - 1;
	  memmove(cp2, cp2 + 1, x);
	  cp2[x] = '\0';
	}

      if (strlen(serno) > 12)
	{
	  avrdude_message(MSG_INFO, "%s: usbhid_open(): invalid serial number \"%s\"\n",
                          progname, serno);
	  return -1;
	}

      wchar_t wserno[15];
      mbstowcs(wserno, serno, 15);
      size_t serlen = strlen(serno);

      /*
       * Now, try finding all devices matching VID:PID, and compare
       * their serial numbers against the requested one.
       */
      struct hid_device_info *list, *walk;
      list = hid_enumerate(pinfo.usbinfo.vid, pinfo.usbinfo.pid);
      if (list == NULL)
	return -1;

      walk = list;
      while (walk)
      {
	avrdude_message(MSG_NOTICE, "%s: usbhid_open(): Found %ls, serno: %ls\n",
			progname, walk->product_string, walk->serial_number);
	size_t slen = wcslen(walk->serial_number);
	if (slen >= serlen &&
	    wcscmp(walk->serial_number + slen - serlen, wserno) == 0)
          {
	    /* found matching serial number */
	    break;
          }
	avrdude_message(MSG_DEBUG, "%s: usbhid_open(): serial number doesn't match\n",
                          progname);
	walk = walk->next;
      }
      if (walk == NULL)
      {
	avrdude_message(MSG_INFO, "%s: usbhid_open(): No matching device found\n",
			progname);
	hid_free_enumeration(list);
	return -1;
      }
      avrdude_message(MSG_DEBUG, "%s: usbhid_open(): Opening path %s\n",
                      progname, walk->path);
      dev = hid_open_path(walk->path);
      hid_free_enumeration(list);
      if (dev == NULL)
      {
	avrdude_message(MSG_INFO,
			"%s: usbhid_open(): Found device, but hid_open_path() failed\n",
			progname);
	return -1;
      }
    }
  else
    {
      /*
       * No serial number requested, pass straight to hid_open()
       */
      dev = hid_open(pinfo.usbinfo.vid, pinfo.usbinfo.pid, NULL);
      if (dev == NULL)
      {
	avrdude_message(MSG_INFO, "%s: usbhid_open(): No device found\n",
			progname);
	return -1;
      }
    }

  fd->usb.handle = dev;

  /*
   * Try finding out the endpoint size.  Alas, libhidapi doesn't
   * provide us with an API function for that, nor for the report
   * descriptor (which also contains that information).
   *
   * Since the Atmel tools a very picky to only respond to incoming
   * packets that have full size, we need to know whether our device
   * handles 512-byte data (JTAGICE3 in CMSIS-DAP mode, or AtmelICE,
   * both on USB 2.0 connections), or 64-byte data only (both these on
   * USB 1.1 connections, or mEDBG devices).
   *
   * In order to find out, we send a CMSIS-DAP DAP_Info command
   * (0x00), with an ID of 0xFF (get maximum packet size).  In theory,
   * this gets us the desired information, but this suffers from a
   * chicken-and-egg problem: the request must be sent with a
   * full-sized packet lest the ICE won't answer.  Thus, we send a
   * 64-byte packet first, and if we don't get a timely reply,
   * complete that request by sending another 448 bytes, and hope it
   * will eventually reply.
   *
   * Note that libhidapi always requires a report ID as the first
   * byte.  If the target doesn't use report IDs (Atmel targets
   * don't), this first byte must be 0x00.  However, the length must
   * be incremented by one, as the report ID will be omitted by the
   * hidapi library.
   */
  if (pinfo.usbinfo.vid == USB_VENDOR_ATMEL)
    {
      avrdude_message(MSG_DEBUG, "%s: usbhid_open(): Probing for max. packet size\n",
		      progname);
      memset(usbbuf, 0, sizeof usbbuf);
      usbbuf[0] = 0;		/* no HID reports used */
      usbbuf[1] = 0;		/* DAP_Info */
      usbbuf[2] = 0xFF;		/* get max. packet size */

      hid_write(dev, usbbuf, 65);
      fd->usb.max_xfer = 64;	/* first guess */

      memset(usbbuf, 0, sizeof usbbuf);
      int res = hid_read_timeout(dev, usbbuf, 10 /* bytes */, 50 /* milliseconds */);
      if (res == 0) {
	/* no timely response, assume 512 byte size */
	hid_write(dev, usbbuf, (512 - 64) + 1);
	fd->usb.max_xfer = 512;
	res = hid_read_timeout(dev, usbbuf, 10, 50);
      }
      if (res <= 0) {
	avrdude_message(MSG_INFO, "%s: usbhid_open(): No response from device\n",
			progname);
	hid_close(dev);
	return -1;
      }
      if (usbbuf[0] != 0 || usbbuf[1] != 2) {
	avrdude_message(MSG_INFO,
			"%s: usbhid_open(): Unexpected reply to DAP_Info: 0x%02x 0x%02x\n",
			progname, usbbuf[0], usbbuf[1]);
      } else {
	fd->usb.max_xfer = usbbuf[2] + (usbbuf[3] << 8);
	avrdude_message(MSG_DEBUG,
			"%s: usbhid_open(): Setting max_xfer from DAP_Info response to %d\n",
			progname, fd->usb.max_xfer);
      }
    }
  if (fd->usb.max_xfer > USBDEV_MAX_XFER_3) {
    avrdude_message(MSG_INFO,
		    "%s: usbhid_open(): Unexpected max size %d, reducing to %d\n",
		    progname, fd->usb.max_xfer, USBDEV_MAX_XFER_3);
    fd->usb.max_xfer = USBDEV_MAX_XFER_3;
  }

  return 0;
}

static void usbhid_close(union filedescriptor *fd)
{
  hid_device *udev = (hid_device *)fd->usb.handle;

  if (udev == NULL)
    return;

  hid_close(udev);
}


static int usbhid_send(union filedescriptor *fd, const unsigned char *bp, size_t mlen)
{
  hid_device *udev = (hid_device *)fd->usb.handle;
  int rv;
  int i = mlen;
  const unsigned char * p = bp;
  unsigned char usbbuf[USBDEV_MAX_XFER_3 + 1];


  int tx_size;

  if (udev == NULL)
    return -1;

  tx_size = (mlen < USBDEV_MAX_XFER_3)? mlen: USBDEV_MAX_XFER_3;
  usbbuf[0] = 0;		/* no report ID used */
  memcpy(usbbuf + 1, bp, tx_size);
  rv = hid_write(udev, usbbuf, tx_size + 1);
  if (rv < 0) {
    avrdude_message(MSG_INFO, "%s: Failed to write %d bytes to USB\n",
		    progname, tx_size);
    return -1;
  }
  if (rv != tx_size + 1)
    avrdude_message(MSG_INFO, "%s: Short write to USB: %d bytes out of %d written\n",
		    progname, rv, tx_size + 1);

  if (verbose > 4)
  {
      avrdude_message(MSG_TRACE2, "%s: Sent: ", progname);

      while (i) {
        unsigned char c = *p;
        if (isprint(c)) {
          avrdude_message(MSG_TRACE2, "%c ", c);
        }
        else {
          avrdude_message(MSG_TRACE2, ". ");
        }
        avrdude_message(MSG_TRACE2, "[%02x] ", c);

        p++;
        i--;
      }
      avrdude_message(MSG_TRACE2, "\n");
  }
  return 0;
}

static int usbhid_recv(union filedescriptor *fd, unsigned char *buf, size_t nbytes)
{
  hid_device *udev = (hid_device *)fd->usb.handle;
  int i, rv;
  unsigned char * p = buf;

  if (udev == NULL)
    return -1;

  rv = i = hid_read_timeout(udev, buf, nbytes, 300);
  if (i != nbytes)
    avrdude_message(MSG_INFO,
		    "%s: Short read, read only %d out of %u bytes\n",
		    progname, i, nbytes);

  if (verbose > 4)
  {
      avrdude_message(MSG_TRACE2, "%s: Recv: ", progname);

      while (i) {
        unsigned char c = *p;
        if (isprint(c)) {
          avrdude_message(MSG_TRACE2, "%c ", c);
        }
        else {
          avrdude_message(MSG_TRACE2, ". ");
        }
        avrdude_message(MSG_TRACE2, "[%02x] ", c);

        p++;
        i--;
      }
      avrdude_message(MSG_TRACE2, "\n");
  }

  return rv;
}

static int usbhid_drain(union filedescriptor *fd, int display)
{
  /*
   * There is not much point in trying to flush any data
   * on an USB endpoint, as the endpoint is supposed to
   * start afresh after being configured from the host.
   *
   * As trying to flush the data here caused strange effects
   * in some situations (see
   * https://savannah.nongnu.org/bugs/index.php?43268 )
   * better avoid it.
   */

  return 0;
}

/*
 * Device descriptor.
 */
struct serial_device usbhid_serdev =
{
  .open = usbhid_open,
  .close = usbhid_close,
  .send = usbhid_send,
  .recv = usbhid_recv,
  .drain = usbhid_drain,
  .flags = SERDEV_FL_NONE,
};

#endif  /* HAVE_LIBHIDAPI */