-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMacCAN_IOUsbKit.c
More file actions
2392 lines (2220 loc) · 100 KB
/
MacCAN_IOUsbKit.c
File metadata and controls
2392 lines (2220 loc) · 100 KB
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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* SPDX-License-Identifier: BSD-2-Clause OR GPL-3.0-or-later */
/*
* MacCAN - macOS User-Space Driver for USB-to-CAN Interfaces
*
* Copyright (c) 2012-2023 Uwe Vogt, UV Software, Berlin (info@mac-can.com)
* All rights reserved.
*
* This file is part of MacCAN-Core.
*
* MacCAN-Core is dual-licensed under the BSD 2-Clause "Simplified" License and
* under the GNU General Public License v3.0 (or any later version).
* You can choose between one of them if you use this file.
*
* BSD 2-Clause "Simplified" License:
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* MacCAN-Core IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF MacCAN-Core, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* GNU General Public License v3.0 or later:
* MacCAN-Core 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 3 of the License, or
* (at your option) any later version.
*
* MacCAN-Core 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 MacCAN-Core. If not, see <http://www.gnu.org/licenses/>.
*/
#include "MacCAN_IOUsbKit.h"
#include "MacCAN_Devices.h"
#include "MacCAN_Debug.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <unistd.h>
#include <pthread.h>
#include <inttypes.h>
#include <mach/mach.h>
#include <mach/clock.h>
#include <IOKit/IOKitLib.h>
#include <IOKit/IOKitKeys.h>
#include <IOKit/IOMessage.h>
#include <IOKit/IOCFPlugIn.h>
#include <IOKit/IOReturn.h>
#include <IOKit/IOTypes.h>
#include <IOKit/usb/IOUSBLib.h>
#include <IOKit/usb/USBSpec.h>
#include <IOKit/usb/USB.h>
#include <CoreFoundation/CFRunLoop.h>
#include <CoreFoundation/CFDictionary.h>
#include <CoreFoundation/CFNumber.h>
#include <CoreFoundation/CFBase.h>
#include <CoreFoundation/CFPlugInCOM.h>
#define VERSION_MAJOR 0
#define VERSION_MINOR 5
#define VERSION_PATCH 0
#define SVN_REVISION "$Rev$"
/*#define OPTION_MACCAN_MULTICHANNEL 0 !* set globally: 0 = only one channel on multi-channel devices */
/*#define OPTION_MACCAN_PIPE_TIMEOUT 0 !* set globally: 0 = do not use xxxPipeTO variant (e.g. macOS < 10.15) */
/*#define OPTION_MACCAN_PIPE_INFO !* activate it, if needed */
#if (OPTION_MACCAN_MULTICHANNEL != 0)
#error multi-channel feature not supported
#endif
#ifdef OPTION_MACCAN_PIPE_TIMEOUT
#if !defined(__MAC_11_0)
#undef OPTION_MACCAN_PIPE_TIMEOUT /* xxxPipeTO() not available in macOS < 11 */
#endif
#endif
#ifndef OPTION_MACCAN_CLEAR_BOTH_ENDS
#if defined(__MAC_11_0)
#define OPTION_MACCAN_CLEAR_BOTH_ENDS 1 /* clear halt endpoint: 1 = both ends, 0 = only one end */
#else
#define OPTION_MACCAN_CLEAR_BOTH_ENDS 0 /* ClearPipeStallBothEnds() not available in macOS < 11 */
#endif
#endif
#define MAX_STRING_LENGTH 256
#define MIN(x,y) ((x) <= (y)) ? (x) : (y)
#define IS_INDEX_VALID(idx) ((0 <= (idx)) && ((idx) < CANUSB_MAX_DEVICES))
#define IS_HANDLE_VALID(hnd) IS_INDEX_VALID(hnd)
#define ENTER_CRITICAL_SECTION(idx) assert(0 == pthread_mutex_lock(&usbDevice[idx].ptMutex))
#define LEAVE_CRITICAL_SECTION(idx) assert(0 == pthread_mutex_unlock(&usbDevice[idx].ptMutex))
static void ReadPipeCallback(void *refCon, IOReturn result, void *arg0);
static void WritePipeCallback(void *refCon, IOReturn result, void *arg0);
static int SetupDirectory(SInt32 vendorID, SInt32 productID);
static void DeviceAdded(void *refCon, io_iterator_t iterator);
static void DeviceRemoved(void *refCon, io_iterator_t iterator);
static IOReturn ConfigureDevice(IOUSBDeviceInterface **dev);
static IOReturn FindInterface(IOUSBDeviceInterface **device, int index);
static void* WorkerThread(void* arg);
typedef struct usb_buffer_tag { /* Double buffer: */
UInt8 *data[2]; /* pointer to data buffers */
UInt8 index; /* index to active data buffer */
UInt32 size; /* size of each buffer (in byte) */
} CANUSB_Buffer_t;
typedef struct usb_async_pipe_tag { /* Asynchrounous pipe: */
UInt8 pipeRef; /* pipe number (endpoint) */
CANUSB_Handle_t handle; /* device handle */
CANUSB_Buffer_t buffer; /* double buffer */
CANUSB_AsyncPipeCbk_t callback; /* callback from notification function */
CANUSB_Context_t context; /* pointer to user context for callback */
#if (OPTION_MACCAN_PIPE_TIMEOUT != 0)
UInt32 noDataTimeout; /* time-out (in [ms]) if no data is transferred */
UInt32 completionTimeout; /* time-out (in [ms]) if the entire request is not completed */
#endif
Boolean running; /* flag to indicate the pipe state */
UInt64 serviced; /* counting callbacks (for debugging) */
} *CANUSB_AsyncPipe_t; /* note: forward declaration requires C11 */
typedef struct usb_interface_tag { /* USB interface: */
Boolean fOpened; /* interface is opened */
UInt8 u8Class; /* class of the interface (8-bit) */
UInt8 u8SubClass; /* subclass of the interface (8-bit) */
UInt8 u8Protocol; /* protocol of the interface (8-bit) */
UInt8 u8NumEndpoints; /* number of endpoints of the interface */
IOUSBInterfaceInterface **ioInterface; /* interface interface (instance) */
CANUSB_DetachedCbk_t cbkDeviceRemoved; /* callback when device has been removed */
CANUSB_Context_t refDeviceRemoved; /* pointer to user context for callback */
} USBInterface_t;
typedef struct usb_device_tag { /* USB device: */
Boolean fPresent; /* device is present */
io_name_t szName; /* device name */
UInt16 u16VendorId; /* vendor ID (16-bit) */
UInt16 u16ProductId; /* product ID (16-bit) */
UInt16 u16ReleaseNo; /* release no. (16-bit) */
UInt8 nCanChannels; /* "number of CAN channels" */
UInt32 u32Location; /* unique location ID (32-bit) */
UInt16 u16Address; /* device address (16-bit?) */
IOUSBDeviceInterface **ioDevice; /* device interface (instance) */
CANUSB_Descriptor_t ptrCanDevice; /* device descriptor (pointer) */
USBInterface_t usbInterface/*[x]*/; /* interface interface (only first one supported) */
pthread_mutex_t ptMutex; /* pthread mutex for mutual exclusion */
} USBDevice_t;
typedef struct usb_driver_tag { /* USB driver: */
Boolean fRunning; /* flag: driver running */
pthread_t ptThread; /* pthread of the driver */
pthread_mutex_t ptMutex; /* pthread mutex for mutual exclusion */
CFRunLoopRef refRunLoop; /* run loop of the driver */
IONotificationPortRef refNotifyPort; /* port for notifications */
io_iterator_t iterBulkDevicePlugged; /* iterator for plugged device(s) */
io_iterator_t iterBulkDeviceUnplugged; /* iterator for unplugged device(s) */
int nRevision; /* revision number */
} USBDriver_t;
static USBDriver_t usbDriver;
static USBDevice_t usbDevice[CANUSB_MAX_DEVICES];
static CANUSB_Index_t idxDevice = 0;
static Boolean fInitialized = false;
CANUSB_Return_t CANUSB_Initialize(void) {
int index, rc = -1;
pthread_attr_t attr;
Boolean running;
time_t now;
/* must not be initialized */
if (fInitialized)
return CANUSB_ERROR_YETINIT;
/* initialize the driver and its devices */
bzero(&usbDriver, sizeof(USBDriver_t));
usbDriver.fRunning = false;
for (index = 0; index < CANUSB_MAX_DEVICES; index++) {
bzero(&usbDevice[index], sizeof(USBDevice_t));
usbDevice[index].fPresent = false;
/* create a mutex for each device */
if (pthread_mutex_init(&usbDevice[index].ptMutex, NULL) != 0)
goto error_initialize;
}
/* create a mutex and a thread for the driver */
if (pthread_mutex_init(&usbDriver.ptMutex, NULL) != 0)
goto error_initialize;
if (pthread_attr_init(&attr) != 0)
goto error_initialize;
if (pthread_attr_setstacksize(&attr, 64*1024) != 0)
goto error_initialize;
if (pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED) != 0)
goto error_initialize;
if (pthread_attr_setschedpolicy(&attr, SCHED_RR) != 0)
goto error_initialize;
rc = pthread_create(&usbDriver.ptThread, &attr, WorkerThread, NULL);
assert(pthread_attr_destroy(&attr) == 0);
if (rc != 0)
goto error_initialize;
/* get SVN/RCS revision number from expanded keyword (to be used as the build number) */
if (sscanf(SVN_REVISION, "\044Rev: %i\044", &usbDriver.nRevision) != 1) usbDriver.nRevision = 0;
/* wait for the driver being loaded (by the created thread) or timed out */
MACCAN_DEBUG_INFO(" Loading the MacCAN driver (v%u.%u.%u.%i)\n", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, usbDriver.nRevision);
fInitialized = true;
now = time(NULL);
do {
usleep(1000);
assert(0 == pthread_mutex_lock(&usbDriver.ptMutex));
running = usbDriver.fRunning;
assert(0 == pthread_mutex_unlock(&usbDriver.ptMutex));
} while (!running && (time(NULL) < (now + 5/*seconds*/)));
if (!running)
goto error_runloop;
/* the driver is now loaded (notifications will be received) */
return CANUSB_SUCCESS;
error_runloop:
/* on error: terminate the thread! */
CFRunLoopStop(usbDriver.refRunLoop);
(void)pthread_mutex_destroy(&usbDriver.ptMutex);
error_initialize:
/* on error: tidy-up! */
for (index = index - 1; index >= 0; index--)
(void)pthread_mutex_destroy(&usbDevice[index].ptMutex);
/* the driver has not been loaded! */
fInitialized = false;
return CANUSB_ERROR_NOTINIT;
}
CANUSB_Return_t CANUSB_Teardown(void) {
int index;
/* must be initialized */
if (!fInitialized)
return CANUSB_ERROR_NOTINIT;
/* "Mr. Gorbachev, tear down this wall!" */
MACCAN_DEBUG_INFO(" Release the MacCAN driver (v%u.%u.%u.%i)\n", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, usbDriver.nRevision);
#if (0)
/* note: this does not terminate the worker thread! */
assert(pthread_cancel(usbDriver.ptThread) == 0);
#else
// TODO: switch completely over to CFRunLoop interface
CFRunLoopStop(usbDriver.refRunLoop);
#endif
usleep(54945);
/* close all USB devices */
for (index = 0; index < CANUSB_MAX_DEVICES; index++) {
/* release the USB device */
//MACCAN_DEBUG_FUNC("lock #%i\n", index);
ENTER_CRITICAL_SECTION(index);
if (usbDevice[index].fPresent &&
(usbDevice[index].ioDevice != NULL)) {
MACCAN_DEBUG_CORE(" - Device #%i: %s", index, usbDevice[index].szName);
if (usbDevice[index].usbInterface.fOpened) {
/* close the USB interface interface(s) */
if (usbDevice[index].usbInterface.ioInterface) {
MACCAN_DEBUG_CODE(0, "close and release I/O interface\n");
(void)(*usbDevice[index].usbInterface.ioInterface)->USBInterfaceClose(usbDevice[index].usbInterface.ioInterface);
(void)(*usbDevice[index].usbInterface.ioInterface)->Release(usbDevice[index].usbInterface.ioInterface);
usbDevice[index].usbInterface.ioInterface = NULL;
}
/* close the USB device interface */
MACCAN_DEBUG_CODE(0, "close I/O device\n");
(void)(*usbDevice[index].ioDevice)->USBDeviceClose(usbDevice[index].ioDevice);
usbDevice[index].usbInterface.fOpened = false;
}
/* rest in pease */
MACCAN_DEBUG_CODE(0, "release I/O device\n");
(void)(*usbDevice[index].ioDevice)->Release(usbDevice[index].ioDevice);
usbDevice[index].ioDevice = NULL;
usbDevice[index].fPresent = false;
MACCAN_DEBUG_CORE(" (R.I.P.)\n");
}
LEAVE_CRITICAL_SECTION(index);
//MACCAN_DEBUG_FUNC("unlocked\n");
(void)pthread_mutex_destroy(&usbDevice[index].ptMutex);
}
(void)pthread_mutex_destroy(&usbDriver.ptMutex);
fInitialized = false;
return 0;
}
CANUSB_Return_t CANUSB_DeviceRequest(CANUSB_Index_t index, CANUSB_SetupPacket_t setupPacket, void *buffer, UInt16 size, UInt32 *transferred) {
IOUSBDevRequest request;
IOReturn kr;
int ret = 0;
/* must be initialized */
if (!fInitialized)
return CANUSB_ERROR_NOTINIT;
/* must be a valid index */
if (!IS_INDEX_VALID(index))
return CANUSB_ERROR_HANDLE;
bzero(&request, sizeof(IOUSBDevRequest));
request.bmRequestType = setupPacket.RequestType;
request.bRequest = setupPacket.Request;
request.wValue = setupPacket.Value;
request.wIndex = setupPacket.Index;
request.wLength = setupPacket.Length;
request.pData = buffer;
request.wLenDone = 0;
(void)size;
MACCAN_DEBUG_FUNC("lock #%i\n", handle);
ENTER_CRITICAL_SECTION(index);
if (usbDevice[index].fPresent &&
(usbDevice[index].ioDevice != NULL)) {
kr = (*usbDevice[index].ioDevice)->DeviceRequest(usbDevice[index].ioDevice, &request);
if (kIOReturnSuccess != kr) {
MACCAN_DEBUG_ERROR("+++ Control transfer failed (%08x)\n", kr);
LEAVE_CRITICAL_SECTION(index);
MACCAN_DEBUG_FUNC("unlocked\n");
return CANUSB_ERROR_RESOURCE;
}
if (transferred)
*transferred = request.wLenDone;
} else {
MACCAN_DEBUG_ERROR("+++ Sorry, device #%i is not available\n", index);
ret = CANUSB_ERROR_HANDLE;
}
LEAVE_CRITICAL_SECTION(index);
MACCAN_DEBUG_FUNC("unlocked\n");
return ret;
}
CANUSB_Handle_t CANUSB_OpenDevice(CANUSB_Index_t index, UInt16 vendorId, UInt16 productId) {
IOReturn kr;
/* must be initialized */
if (!fInitialized)
return CANUSB_INVALID_HANDLE;
/* must be a valid index */
if (!IS_INDEX_VALID(index))
return CANUSB_INVALID_HANDLE;
/* open the USB device */
MACCAN_DEBUG_FUNC("lock #%i\n", index);
ENTER_CRITICAL_SECTION(index);
if (usbDevice[index].fPresent &&
(usbDevice[index].ioDevice != NULL)) {
if (!usbDevice[index].usbInterface.fOpened) {
/* Find matching device by vendor id. and product id. (optional) */
if ((vendorId != CANUSB_ANY_VENDOR_ID) && (productId != CANUSB_ANY_PRODUCT_ID)) {
/* $1 by both vendor id. and product id. */
if ((vendorId != usbDevice[index].u16VendorId) || (productId != usbDevice[index].u16ProductId)) {
MACCAN_DEBUG_ERROR("+++ Device #i doesn't match (vendor = %03x, product = %03x)\n", index, vendorId, productId);
LEAVE_CRITICAL_SECTION(index);
MACCAN_DEBUG_FUNC("unlocked\n");
return CANUSB_INVALID_HANDLE;
}
} else if (vendorId != CANUSB_ANY_VENDOR_ID) {
/* $2 by vendor id. only */
if (vendorId != usbDevice[index].u16VendorId) {
MACCAN_DEBUG_ERROR("+++ Device #i doesn't match (vendor = %03x)\n", index, vendorId);
LEAVE_CRITICAL_SECTION(index);
MACCAN_DEBUG_FUNC("unlocked\n");
return CANUSB_INVALID_HANDLE;
}
} else if (productId != CANUSB_ANY_PRODUCT_ID) {
/* $3 both id.s don't care */
MACCAN_DEBUG_ERROR("+++ Nope: vendor id. required (device #i, product = %03x)\n", index, productId);
LEAVE_CRITICAL_SECTION(index);
MACCAN_DEBUG_FUNC("unlocked\n");
return CANUSB_INVALID_HANDLE;
}
/* Open the device for exclusive access */
kr = (*usbDevice[index].ioDevice)->USBDeviceOpen(usbDevice[index].ioDevice);
if (kIOReturnSuccess != kr) {
MACCAN_DEBUG_ERROR("+++ Unable to open device #%i: %08x\n", index, kr);
LEAVE_CRITICAL_SECTION(index);
MACCAN_DEBUG_FUNC("unlocked\n");
return CANUSB_INVALID_HANDLE;
}
/* Configure the device */
kr = ConfigureDevice(usbDevice[index].ioDevice);
if (kIOReturnSuccess != kr) {
MACCAN_DEBUG_ERROR("+++ Unable to configure device #%i: %08x\n", index, kr);
(void)(*usbDevice[index].ioDevice)->USBDeviceClose(usbDevice[index].ioDevice);
usbDevice[index].usbInterface.fOpened = false;
LEAVE_CRITICAL_SECTION(index);
MACCAN_DEBUG_FUNC("unlocked\n");
return CANUSB_INVALID_HANDLE;
}
/* Get the interfaces */
kr = FindInterface(usbDevice[index].ioDevice, index);
if (kIOReturnSuccess != kr) {
MACCAN_DEBUG_ERROR("+++ Unable to find interfaces on device #%i: %08x\n", index, kr);
(void)(*usbDevice[index].ioDevice)->USBDeviceClose(usbDevice[index].ioDevice);
usbDevice[index].usbInterface.fOpened = false;
LEAVE_CRITICAL_SECTION(index);
MACCAN_DEBUG_FUNC("unlocked\n");
return CANUSB_INVALID_HANDLE;
}
/* note: fOpened is true */
} else {
/* all CAN channels on the USB interface are opened */
LEAVE_CRITICAL_SECTION(index);
MACCAN_DEBUG_FUNC("unlocked\n");
return CANUSB_INVALID_HANDLE;
}
} else {
MACCAN_DEBUG_ERROR("+++ Unable to open device #%i (device not present)\n", index);
LEAVE_CRITICAL_SECTION(index);
MACCAN_DEBUG_FUNC("unlocked\n");
return CANUSB_INVALID_HANDLE;
}
LEAVE_CRITICAL_SECTION(index);
MACCAN_DEBUG_FUNC("unlocked\n");
/* the index is the handle! */
return (CANUSB_Handle_t)index;
}
CANUSB_Return_t CANUSB_CloseDevice(CANUSB_Handle_t handle) {
IOReturn kr;
int ret = 0;
/* must be initialized */
if (!fInitialized)
return CANUSB_ERROR_NOTINIT;
/* must be a valid handle */
if (!IS_HANDLE_VALID(handle))
return CANUSB_ERROR_HANDLE;
/* close the USB device */
MACCAN_DEBUG_FUNC("lock #%i\n", handle);
ENTER_CRITICAL_SECTION(handle);
if (usbDevice[handle].fPresent) {
if (usbDevice[handle].usbInterface.fOpened) {
/* close the USB interface interface(s) */
if (usbDevice[handle].usbInterface.ioInterface) {
MACCAN_DEBUG_CODE(0, "close and release I/O interface\n");
kr = (*usbDevice[handle].usbInterface.ioInterface)->USBInterfaceClose(usbDevice[handle].usbInterface.ioInterface);
if (kIOReturnSuccess != kr) {
MACCAN_DEBUG_ERROR("+++ Unable to close I/O interface of device #%i: %08x\n", handle, kr);
// TODO: how to handle this?
}
kr = (*usbDevice[handle].usbInterface.ioInterface)->Release(usbDevice[handle].usbInterface.ioInterface);
if (kIOReturnSuccess != kr) {
MACCAN_DEBUG_ERROR("+++ Unable to release I/O interface of device #%i: %08x\n", handle, kr);
// TODO: how to handle this?
}
usbDevice[handle].usbInterface.ioInterface = NULL;
}
/* Close the task�s connection to the device */
if (usbDevice[handle].ioDevice) {
MACCAN_DEBUG_CODE(0, "close I/O device\n");
kr = (*usbDevice[handle].ioDevice)->USBDeviceClose(usbDevice[handle].ioDevice);
if (kIOReturnSuccess != kr) {
MACCAN_DEBUG_ERROR("+++ Unable to close I/O device #%i: %08x\n", handle, kr);
LEAVE_CRITICAL_SECTION(handle);
MACCAN_DEBUG_FUNC("unlocked\n");
return CANUSB_ERROR_RESOURCE;
}
}
/* the USB interface is now closed */
usbDevice[handle].usbInterface.fOpened = false;
} else {
/* the USB interface is not opened */
ret = CANUSB_ERROR_NOTINIT;
}
} else {
/* the USB device is not available */
ret = CANUSB_ERROR_HANDLE;
}
LEAVE_CRITICAL_SECTION(handle);
MACCAN_DEBUG_FUNC("unlocked\n");
return ret;
}
CANUSB_Return_t CANUSB_RegisterDetachedCallback(CANUSB_Handle_t handle, CANUSB_DetachedCbk_t callback, CANUSB_Context_t context) {
int ret = 0;
/* must be initialized */
if (!fInitialized)
return CANUSB_ERROR_NOTINIT;
/* must be a valid handle */
if (!IS_HANDLE_VALID(handle))
return CANUSB_ERROR_HANDLE;
MACCAN_DEBUG_FUNC("lock #%i\n", handle);
ENTER_CRITICAL_SECTION(handle);
if (usbDevice[handle].fPresent &&
(usbDevice[handle].usbInterface.fOpened) &&
(usbDevice[handle].usbInterface.ioInterface != NULL)) {
usbDevice[handle].usbInterface.cbkDeviceRemoved = callback;
usbDevice[handle].usbInterface.refDeviceRemoved = context;
} else {
MACCAN_DEBUG_ERROR("+++ Sorry, device #%i is not opened or not available (RegisterDetachedCallback)\n", handle);
ret = !usbDevice[handle].fPresent ? CANUSB_ERROR_HANDLE : CANUSB_ERROR_NOTINIT;
}
LEAVE_CRITICAL_SECTION(handle);
MACCAN_DEBUG_FUNC("unlocked\n");
return ret;
}
CANUSB_Return_t CANUSB_ReadPipe(CANUSB_Handle_t handle, UInt8 pipeRef, void *buffer, UInt32 *size, UInt16 timeout) {
IOReturn kr;
int ret = 0;
#if (OPTION_MACCAN_PIPE_TIMEOUT == 0)
(void)timeout;
#else
UInt32 noDataTimeout = (UInt32)(((UInt32)timeout * (UInt32)2) / (UInt32)5);
UInt32 completionTimeout = (UInt32)timeout;
#endif
/* must be initialized */
if (!fInitialized)
return CANUSB_ERROR_NOTINIT;
/* must be a valid handle */
if (!IS_HANDLE_VALID(handle))
return CANUSB_ERROR_HANDLE;
/* check for NULL pointer */
if (!buffer || !size)
return CANUSB_ERROR_NULLPTR;
MACCAN_DEBUG_FUNC("lock #%i (%u)\n", handle, pipeRef);
ENTER_CRITICAL_SECTION(handle);
if (usbDevice[handle].fPresent &&
(usbDevice[handle].usbInterface.fOpened) &&
(usbDevice[handle].usbInterface.ioInterface != NULL)) {
#if (OPTION_MACCAN_PIPE_TIMEOUT == 0)
/* note: deactivate define if ReadPipeTO() is not available in IOUSBInterfaceStructXYZ for the device. */
kr = (*usbDevice[handle].usbInterface.ioInterface)->ReadPipe(usbDevice[handle].usbInterface.ioInterface,
pipeRef, buffer, size);
#else
if (timeout)
kr = (*usbDevice[handle].usbInterface.ioInterface)->ReadPipeTO(usbDevice[handle].usbInterface.ioInterface,
pipeRef, buffer, size,
noDataTimeout, completionTimeout);
else
kr = (*usbDevice[handle].usbInterface.ioInterface)->ReadPipe(usbDevice[handle].usbInterface.ioInterface,
pipeRef, buffer, size);
#endif
if (kIOReturnSuccess != kr) {
MACCAN_DEBUG_ERROR("+++ Unable to read pipe #%d (%08x)\n", pipeRef, kr);
LEAVE_CRITICAL_SECTION(handle);
MACCAN_DEBUG_FUNC("unlocked\n");
return (kIOUSBTransactionTimeout != kr) ? CANUSB_ERROR_RESOURCE : CANUSB_ERROR_TIMEOUT;
}
} else {
MACCAN_DEBUG_ERROR("+++ Sorry, device #%i is not opened or not available (ReadPipe)\n", handle);
ret = !usbDevice[handle].fPresent ? CANUSB_ERROR_HANDLE : CANUSB_ERROR_NOTINIT;
}
LEAVE_CRITICAL_SECTION(handle);
MACCAN_DEBUG_FUNC("unlocked\n");
return ret;
}
CANUSB_Return_t CANUSB_WritePipe(CANUSB_Handle_t handle, UInt8 pipeRef, const void *buffer, UInt32 size, UInt16 timeout) {
IOReturn kr;
int ret = 0;
#if (OPTION_MACCAN_PIPE_TIMEOUT == 0)
(void)timeout;
#else
UInt32 noDataTimeout = (UInt32)timeout - (UInt32)(((UInt32)timeout * (UInt32)2) / (UInt32)5);
UInt32 completionTimeout = (UInt32)timeout;
#endif
/* must be initialized */
if (!fInitialized)
return CANUSB_ERROR_NOTINIT;
/* must be a valid handle */
if (!IS_HANDLE_VALID(handle))
return CANUSB_ERROR_HANDLE;
/* check for NULL pointer */
if (!buffer)
return CANUSB_ERROR_NULLPTR;
MACCAN_DEBUG_FUNC("lock #%i (%u)\n", handle, pipeRef);
ENTER_CRITICAL_SECTION(handle);
if (usbDevice[handle].fPresent &&
(usbDevice[handle].usbInterface.fOpened) &&
(usbDevice[handle].usbInterface.ioInterface != NULL)) {
kr = (*usbDevice[handle].usbInterface.ioInterface)->GetPipeStatus(usbDevice[handle].usbInterface.ioInterface,
pipeRef);
if (kIOReturnSuccess != kr) {
MACCAN_DEBUG_ERROR("+++ Unable to get status of pipe #%d (%08x)\n", pipeRef, kr);
LEAVE_CRITICAL_SECTION(handle);
MACCAN_DEBUG_FUNC("unlocked\n");
return (kIOUSBPipeStalled != kr) ? CANUSB_ERROR_RESOURCE : CANUSB_ERROR_STALLED;
}
#if (OPTION_MACCAN_PIPE_TIMEOUT == 0)
/* note: deactivate define if WritePipeTO() is not available in IOUSBInterfaceStructXYZ for the device. */
kr = (*usbDevice[handle].usbInterface.ioInterface)->WritePipe(usbDevice[handle].usbInterface.ioInterface,
pipeRef, (void*)buffer, size);
#else
if (timeout)
kr = (*usbDevice[handle].usbInterface.ioInterface)->WritePipeTO(usbDevice[handle].usbInterface.ioInterface,
pipeRef, (void*)buffer, size,
noDataTimeout, completionTimeout);
else
kr = (*usbDevice[handle].usbInterface.ioInterface)->WritePipe(usbDevice[handle].usbInterface.ioInterface,
pipeRef, (void*)buffer, size);
#endif
if (kIOReturnSuccess != kr) {
MACCAN_DEBUG_ERROR("+++ Unable to write pipe #%d (%08x)\n", pipeRef, kr);
LEAVE_CRITICAL_SECTION(handle);
MACCAN_DEBUG_FUNC("unlocked\n");
return (kIOUSBTransactionTimeout != kr) ? CANUSB_ERROR_RESOURCE : CANUSB_ERROR_TIMEOUT;
}
} else {
MACCAN_DEBUG_ERROR("+++ Sorry, device #%i is not opened or not available (WritePipe)\n", handle);
ret = !usbDevice[handle].fPresent ? CANUSB_ERROR_HANDLE : CANUSB_ERROR_NOTINIT;
}
LEAVE_CRITICAL_SECTION(handle);
MACCAN_DEBUG_FUNC("unlocked\n");
return ret;
}
CANUSB_Return_t CANUSB_ResetPipe(CANUSB_Handle_t handle, UInt8 pipeRef) {
IOReturn kr;
int ret = 0;
/* must be initialized */
if (!fInitialized)
return CANUSB_ERROR_NOTINIT;
/* must be a valid handle */
if (!IS_HANDLE_VALID(handle))
return CANUSB_ERROR_HANDLE;
MACCAN_DEBUG_FUNC("lock #%i (%u)\n", handle, pipeRef);
ENTER_CRITICAL_SECTION(handle);
if (usbDevice[handle].fPresent &&
(usbDevice[handle].usbInterface.fOpened) &&
(usbDevice[handle].usbInterface.ioInterface != NULL)) {
kr = (*usbDevice[handle].usbInterface.ioInterface)->AbortPipe(usbDevice[handle].usbInterface.ioInterface,
pipeRef);
if (kIOReturnSuccess != kr) {
MACCAN_DEBUG_ERROR("+++ Unable to abort pipe #%d (%08x)\n", pipeRef, kr);
LEAVE_CRITICAL_SECTION(handle);
MACCAN_DEBUG_FUNC("unlocked\n");
return CANUSB_ERROR_RESOURCE;
}
#if (OPTION_MACCAN_CLEAR_BOTH_ENDS == 0)
kr = (*usbDevice[handle].usbInterface.ioInterface)->ClearPipeStall(usbDevice[handle].usbInterface.ioInterface,
pipeRef);
#else
kr = (*usbDevice[handle].usbInterface.ioInterface)->ClearPipeStallBothEnds(usbDevice[handle].usbInterface.ioInterface,
pipeRef);
#endif
if (kIOReturnSuccess != kr) {
MACCAN_DEBUG_ERROR("+++ Unable to clear pipe #%d (%08x)\n", pipeRef, kr);
LEAVE_CRITICAL_SECTION(handle);
MACCAN_DEBUG_FUNC("unlocked\n");
return CANUSB_ERROR_RESOURCE;
}
kr = (*usbDevice[handle].usbInterface.ioInterface)->GetPipeStatus(usbDevice[handle].usbInterface.ioInterface,
pipeRef);
if (kIOReturnSuccess != kr) {
MACCAN_DEBUG_ERROR("+++ Unable to get status of pipe #%d (%08x)\n", pipeRef, kr);
LEAVE_CRITICAL_SECTION(handle);
MACCAN_DEBUG_FUNC("unlocked\n");
return CANUSB_ERROR_RESOURCE;
}
} else {
MACCAN_DEBUG_ERROR("+++ Sorry, device #%i is not opened or not available (ResetPipe)\n", handle);
ret = !usbDevice[handle].fPresent ? CANUSB_ERROR_HANDLE : CANUSB_ERROR_NOTINIT;
}
LEAVE_CRITICAL_SECTION(handle);
MACCAN_DEBUG_FUNC("unlocked\n");
return ret;
}
CANUSB_AsyncPipe_t CANUSB_CreatePipeAsync(CANUSB_Handle_t handle, UInt8 pipeRef, size_t bufferSize, Boolean doubleBuffer) {
CANUSB_AsyncPipe_t asyncPipe = NULL;
/* must be initialized */
if (!fInitialized)
return NULL;
/* must be a valid handle */
if (!IS_HANDLE_VALID(handle))
return NULL;
/* create asynchronous pipe context */
if ((asyncPipe = (CANUSB_AsyncPipe_t)malloc(sizeof(struct usb_async_pipe_tag))) == NULL) {
MACCAN_DEBUG_ERROR("+++ Unable to create asynchronous context for pipe #%u\n", pipeRef);
return NULL;
}
bzero(asyncPipe, sizeof(struct usb_async_pipe_tag));
asyncPipe->handle = CANUSB_INVALID_HANDLE;
/* create buffer for USB data transfer */
if (doubleBuffer) {
MACCAN_DEBUG_CORE(" - Double buffer each of size %u bytes for pipe #%u\n", bufferSize, pipeRef);
if ((asyncPipe->buffer.data[0] = malloc(bufferSize)) &&
(asyncPipe->buffer.data[1] = malloc(bufferSize))) {
asyncPipe->buffer.size = (UInt32)bufferSize;
asyncPipe->callback = NULL;
asyncPipe->context = NULL;
asyncPipe->pipeRef = pipeRef;
asyncPipe->handle = handle;
} else {
MACCAN_DEBUG_ERROR("+++ Unable to create double buffer (2 * %u bytes) for pipe #%u\n", bufferSize, pipeRef);
free(asyncPipe);
asyncPipe = NULL;
}
} else {
MACCAN_DEBUG_CORE(" - Single buffer of size %u bytes for pipe #%u\n", bufferSize, pipeRef);
if ((asyncPipe->buffer.data[0] = malloc(bufferSize))) {
asyncPipe->buffer.size = (UInt32)bufferSize;
asyncPipe->buffer.data[1] = NULL;
asyncPipe->callback = NULL;
asyncPipe->context = NULL;
asyncPipe->pipeRef = pipeRef;
asyncPipe->handle = handle;
} else {
MACCAN_DEBUG_ERROR("+++ Unable to create single buffer (1 * %u bytes) for pipe #%u\n", bufferSize, pipeRef);
free(asyncPipe);
asyncPipe = NULL;
}
}
return asyncPipe;
}
CANUSB_Return_t CANUSB_DestroyPipeAsync(CANUSB_AsyncPipe_t asyncPipe) {
/* must be initialized */
if (!fInitialized)
return CANUSB_ERROR_NOTINIT;
/* check for NULL pointer */
if (!asyncPipe)
return CANUSB_ERROR_NULLPTR;
/* must be a valid handle */
if (!IS_HANDLE_VALID(asyncPipe->handle))
return CANUSB_ERROR_HANDLE;
/* if running then abort */
if (asyncPipe->running)
(void)CANUSB_AbortPipeAsync(asyncPipe);
MACCAN_DEBUG_CORE(" %8" PRIu64 " notification(s) of pipe #%u serviced\n", asyncPipe->serviced, asyncPipe->pipeRef);
/* free buffer(s) and asynchronous pipe context */
if (asyncPipe->buffer.data[1])
free(asyncPipe->buffer.data[1]);
if (asyncPipe->buffer.data[0])
free(asyncPipe->buffer.data[0]);
free(asyncPipe);
return CANUSB_SUCCESS;
}
static void ReadPipeCallback(void *refCon, IOReturn result, void *arg0) {
CANUSB_AsyncPipe_t asyncPipe = (CANUSB_AsyncPipe_t)refCon;
UInt64 length = (arg0) ? (UInt64)arg0 : 0U;
UInt8 *buffer, index;
IOReturn kr;
switch (result)
{
case kIOReturnSuccess:
if (asyncPipe) {
asyncPipe->serviced++;
/* sanity check */
if (!IS_HANDLE_VALID(asyncPipe->handle)) {
asyncPipe->running = false;
return;
}
if (!usbDevice[asyncPipe->handle].usbInterface.ioInterface) {
asyncPipe->running = false;
return;
}
if (!asyncPipe->buffer.data[0] || !asyncPipe->buffer.data[1]) {
asyncPipe->running = false;
return;
}
if (asyncPipe->buffer.index >= 2) {
asyncPipe->running = false;
return;
}
/* double-buffer strategy */
index = asyncPipe->buffer.index;
buffer = asyncPipe->buffer.data[index];
asyncPipe->buffer.index = index ? 0 : 1;
/* preparation of the next asynchronous pipe read event (with our pipe context as reference, 6th argument) */
kr = (*usbDevice[asyncPipe->handle].usbInterface.ioInterface)->ReadPipeAsync(usbDevice[asyncPipe->handle].usbInterface.ioInterface,
asyncPipe->pipeRef,
asyncPipe->buffer.data[asyncPipe->buffer.index],
asyncPipe->buffer.size,
ReadPipeCallback,
(void *)asyncPipe);
if (kIOReturnSuccess != kr) {
MACCAN_DEBUG_ERROR("+++ Unable to read async pipe #%d of device #%d (%08x)\n", asyncPipe->pipeRef, asyncPipe->handle, kr);
/* error: pipe is boken */
asyncPipe->running = false;
}
/* call the CALLBACK routine with the referenced pipe context */
if (asyncPipe->callback && length) {
(void)asyncPipe->callback(asyncPipe->context, buffer, (UInt32)length);
}
} else {
MACCAN_DEBUG_ERROR("+++ Error: read async pipe without context (%08x)\n", result);
}
break;
case kIOReturnAborted:
if (asyncPipe) {
MACCAN_DEBUG_CORE("!!! Aborted: read async pipe #%d of device #%d (%08x)\n", asyncPipe->pipeRef, asyncPipe->handle, result);
asyncPipe->running = false;
} else {
MACCAN_DEBUG_CORE("!!! Aborted: read async pipe without context (%08x)\n", result);
}
break;
default:
if (asyncPipe) {
MACCAN_DEBUG_ERROR("+++ Error: read async pipe #%d of device #%d (%08x)\n", asyncPipe->pipeRef, asyncPipe->handle, result);
asyncPipe->running = false;
} else {
MACCAN_DEBUG_ERROR("+++ Error: read async pipe without context (%08x)\n", result);
}
break;
}
return;
}
CANUSB_Return_t CANUSB_ReadPipeAsync(CANUSB_AsyncPipe_t asyncPipe, CANUSB_AsyncPipeCbk_t callback, CANUSB_Context_t context) {
IOReturn kr;
int ret = 0;
/* must be initialized */
if (!fInitialized)
return CANUSB_ERROR_NOTINIT;
/* check for NULL pointer */
if (!asyncPipe ||
!asyncPipe->buffer.data[0] ||
!asyncPipe->buffer.data[1])
return CANUSB_ERROR_NULLPTR;
/* must be a valid handle */
if (!IS_HANDLE_VALID(asyncPipe->handle))
return CANUSB_ERROR_HANDLE;
MACCAN_DEBUG_FUNC("lock #%i (%u)\n", asyncPipe->handle, asyncPipe->pipeRef);
ENTER_CRITICAL_SECTION(asyncPipe->handle);
if (asyncPipe->running) {
MACCAN_DEBUG_ERROR("+++ Async read of pipe #%d already started\n", asyncPipe->pipeRef);
LEAVE_CRITICAL_SECTION(asyncPipe->handle);
MACCAN_DEBUG_FUNC("unlocked\n");
return CANUSB_ERROR_RESOURCE;
}
if (usbDevice[asyncPipe->handle].fPresent &&
(usbDevice[asyncPipe->handle].usbInterface.fOpened) &&
(usbDevice[asyncPipe->handle].usbInterface.ioInterface != NULL)) {
/* register the callback function and the reception data context */
asyncPipe->callback = callback;
asyncPipe->context = context;
/* preparation of the first asynchronous pipe read event (with our pipe context as reference, 6th argument) */
kr = (*usbDevice[asyncPipe->handle].usbInterface.ioInterface)->ReadPipeAsync(usbDevice[asyncPipe->handle].usbInterface.ioInterface,
asyncPipe->pipeRef,
asyncPipe->buffer.data[asyncPipe->buffer.index],
asyncPipe->buffer.size,
ReadPipeCallback,
(void*)asyncPipe);
if (kIOReturnSuccess != kr) {
MACCAN_DEBUG_ERROR("+++ Unable to start async read pipe #%d of device #%d (%08x)\n", asyncPipe->pipeRef, asyncPipe->handle, kr);
LEAVE_CRITICAL_SECTION(asyncPipe->handle);
MACCAN_DEBUG_FUNC("unlocked\n");
return CANUSB_ERROR_RESOURCE;
}
/* asynchronous pipe read event armed */
asyncPipe->running = true;
} else {
MACCAN_DEBUG_ERROR("+++ Sorry, device #%i is not opened or not available (ReadPipeAsync)\n", asyncPipe->handle);
ret = !usbDevice[asyncPipe->handle].fPresent ? CANUSB_ERROR_HANDLE : CANUSB_ERROR_NOTINIT;
}
LEAVE_CRITICAL_SECTION(asyncPipe->handle);
MACCAN_DEBUG_FUNC("unlocked\n");
return ret;
}
CANUSB_Return_t CANUSB_AbortPipeAsync(CANUSB_AsyncPipe_t asyncPipe) {
IOReturn kr;
int ret = 0;
/* must be initialized */
if (!fInitialized)
return CANUSB_ERROR_NOTINIT;
/* check for NULL pointer */
if (!asyncPipe)
return CANUSB_ERROR_NULLPTR;
/* must be a valid handle */
if (!IS_HANDLE_VALID(asyncPipe->handle))
return CANUSB_ERROR_HANDLE;
MACCAN_DEBUG_FUNC("lock #%i (%u)\n", asyncPipe->handle, asyncPipe->pipeRef);
ENTER_CRITICAL_SECTION(asyncPipe->handle);
if (usbDevice[asyncPipe->handle].fPresent &&
(usbDevice[asyncPipe->handle].usbInterface.fOpened) &&
(usbDevice[asyncPipe->handle].usbInterface.ioInterface != NULL)) {
kr = (*usbDevice[asyncPipe->handle].usbInterface.ioInterface)->AbortPipe(usbDevice[asyncPipe->handle].usbInterface.ioInterface,
asyncPipe->pipeRef);
if (kIOReturnSuccess != kr) {
MACCAN_DEBUG_ERROR("+++ Unable to abort async pipe #%d (%08x)\n", asyncPipe->pipeRef, kr);
LEAVE_CRITICAL_SECTION(asyncPipe->handle);
MACCAN_DEBUG_FUNC("unlocked\n");
return CANUSB_ERROR_RESOURCE;
}
} else {
MACCAN_DEBUG_ERROR("+++ Sorry, device #%i is not opened or not available (AbortPipeAsync #%d)\n", asyncPipe->handle, asyncPipe->pipeRef);
ret = !usbDevice[asyncPipe->handle].fPresent ? CANUSB_ERROR_HANDLE : CANUSB_ERROR_NOTINIT;
}
LEAVE_CRITICAL_SECTION(asyncPipe->handle);
MACCAN_DEBUG_FUNC("unlocked\n");
return ret;
}
static void WritePipeCallback(void *refCon, IOReturn result, void *arg0) {
CANUSB_AsyncPipe_t asyncPipe = (CANUSB_AsyncPipe_t)refCon;
IOReturn kr;
(void)arg0;
switch(result)
{
case kIOReturnSuccess:
if (asyncPipe) {
asyncPipe->serviced++;
/* sanity check */
if (!IS_HANDLE_VALID(asyncPipe->handle)) {
asyncPipe->running = false;
return;
}
if (!usbDevice[asyncPipe->handle].usbInterface.ioInterface) {
asyncPipe->running = false;
return;
}
if (!asyncPipe->buffer.data[0]) {
asyncPipe->running = false;
return;
}
/* check if there are more data to be sent */
if (asyncPipe->callback &&
asyncPipe->callback(asyncPipe->context, asyncPipe->buffer.data[0], asyncPipe->buffer.size)) {
/* preparation of the next asynchronous pipe write event (with our pipe context as reference, 8th resp. 6th argument) */
#if (OPTION_MACCAN_PIPE_TIMEOUT == 0)
kr = (*usbDevice[asyncPipe->handle].usbInterface.ioInterface)->WritePipeAsync(usbDevice[asyncPipe->handle].usbInterface.ioInterface,
asyncPipe->pipeRef,
asyncPipe->buffer.data[0],
asyncPipe->buffer.size,
WritePipeCallback,
(void*)asyncPipe);
#else
if (asyncPipe->noDataTimeout && asyncPipe->completionTimeout)
kr = (*usbDevice[asyncPipe->handle].usbInterface.ioInterface)->WritePipeAsyncTO(usbDevice[asyncPipe->handle].usbInterface.ioInterface,
asyncPipe->pipeRef,
asyncPipe->buffer.data[0],
asyncPipe->buffer.size,
asyncPipe->noDataTimeout,
asyncPipe->completionTimeout,
WritePipeCallback,
(void*)asyncPipe);
else
kr = (*usbDevice[asyncPipe->handle].usbInterface.ioInterface)->WritePipeAsync(usbDevice[asyncPipe->handle].usbInterface.ioInterface,
asyncPipe->pipeRef,
asyncPipe->buffer.data[0],
asyncPipe->buffer.size,
WritePipeCallback,
(void*)asyncPipe);
#endif
if (kIOReturnSuccess != kr) {
MACCAN_DEBUG_ERROR("+++ Unable to write async pipe #%d of device #%d (%08x)\n", asyncPipe->pipeRef, asyncPipe->handle, kr);
/* error: something went wrong */
asyncPipe->running = false;
} else {
/* success: write event armed */
asyncPipe->running = true;
}
} else {
/* no more data to be sent */
asyncPipe->running = false;
}
} else {
MACCAN_DEBUG_CORE("+++ Error: write async pipe without context (%08x)\n", result);
}
break;
case kIOReturnAborted:
if (asyncPipe) {
MACCAN_DEBUG_CORE("!!! Aborted: write async pipe #%d of device #%d (%08x)\n", asyncPipe->pipeRef, asyncPipe->handle, result);
asyncPipe->running = false;
} else {
MACCAN_DEBUG_CORE("!!! Aborted: write async pipe without context (%08x)\n", result);