source: trunk/csctapi/ifd_smartreader.c@ 1650

Last change on this file since 1650 was 1650, checked in by landlord, 11 years ago

Fixed a small problem as the Irdeto flag was not properly cleared in the smartreader code

File size: 41.0 KB
Line 
1#if defined(LIBUSB)
2/*
3 ifd_smartreader.c
4 This module provides IFD handling functions for for Argolis smartreader+.
5*/
6
7#include <stdio.h>
8#include <time.h>
9#include <string.h>
10#include"ifd_smartreader.h"
11
12#define OK 0
13#define ERROR 1
14#define LOBYTE(w) ((BYTE)((w) & 0xff))
15#define HIBYTE(w) ((BYTE)((w) >> 8))
16
17//The number of concurrent bulk reads to queue onto the smartreader
18#define NUM_TXFERS 2
19
20typedef struct s_reader S_READER;
21
22static bool smartreader_check_endpoint(libusb_device *usb_dev);
23static struct libusb_device *find_smartreader(const char*busname,const char *devname);
24static void smartreader_init(S_READER *reader);
25static unsigned int smartreader_determine_max_packet_size(S_READER *reader);
26static int smartreader_usb_close_internal (S_READER *reader);
27static int smartreader_usb_reset(S_READER *reader);
28static int smartreader_usb_open_dev(S_READER *reader);
29static int smartreader_usb_purge_rx_buffer(S_READER *reader);
30static int smartreader_usb_purge_tx_buffer(S_READER *reader);
31static int smartreader_usb_purge_buffers(S_READER *reader);
32static int smartreader_convert_baudrate(int baudrate, S_READER *reader, unsigned short *value, unsigned short *index);
33static int smartreader_set_baudrate(S_READER *reader, int baudrate);
34static int smartreader_setdtr_rts(S_READER *reader, int dtr, int rts);
35static int smartreader_setflowctrl(S_READER *reader, int flowctrl);
36static int smartreader_set_line_property2(S_READER *reader, enum smartreader_bits_type bits,
37 enum smartreader_stopbits_type sbit, enum smartreader_parity_type parity,
38 enum smartreader_break_type break_type);
39static int smartreader_set_line_property(S_READER *reader, enum smartreader_bits_type bits,
40 enum smartreader_stopbits_type sbit, enum smartreader_parity_type parity);
41static void smart_flush(S_READER *reader);
42static int smart_read(S_READER *reader, unsigned char* buff, unsigned int size, int timeout_sec);
43static int smartreader_write_data(S_READER *reader, unsigned char *buf, unsigned int size);
44static int smart_write(S_READER *reader, unsigned char* buff, unsigned int size, int udelay);
45static int smartreader_set_latency_timer(S_READER *reader, unsigned short latency);
46static void EnableSmartReader(S_READER *reader, int clock, unsigned short Fi, unsigned char Di, unsigned char Ni, unsigned char T,unsigned char inv, int parity);
47static void ResetSmartReader(S_READER *reader);
48static void *ReaderThread(void *p);
49
50int SR_Init (struct s_reader *reader)
51{
52
53 int ret;
54 char device[128];
55 char *busname;
56 char *devname;
57 char *search = ":";
58 // split the device name from the reader conf into devname and busname
59 memcpy(device,reader->device,128);
60 busname=strtok(device,search);
61 devname=strtok(NULL,search);
62 if(!busname || !devname) {
63 cs_log("Wrong device format (%s), it should be Device=bus:dev",reader->device);
64 return ERROR;
65 }
66
67 cs_debug_mask (D_IFD,"IO:SR: Looking for device %s on bus %s",devname,busname);
68
69 ret = libusb_init(NULL);
70 if (ret < 0) {
71 cs_log("Libusb init error : %d",ret);
72 return ret;
73 }
74
75 smartreader_init(reader);
76
77 reader->sr_config.usb_dev=find_smartreader(busname,devname);
78 if(!reader->sr_config.usb_dev)
79 return ERROR;
80
81 cs_debug_mask (D_IFD,"IO:SR: Opening smartreader device %s on bus %s",devname,busname);
82 //The smartreader has different endpoint addresses
83 //compared to a real FT232 device, so change them here,
84 //also a good way to compare a real FT232 with a smartreader
85 //if you enumarate usb devices
86 reader->sr_config.in_ep = 0x1;
87 reader->sr_config.out_ep = 0x82;
88
89 //open the first smartreader found in the system, this
90 //would need to be changed to an enumerate function
91 //of some sort using the ftdi library. /dev/ttyUSB0 wont exist
92 //as we are accessing the device directly so you will have
93 //to have some other way of addressing the smartreader within
94 //OSCam config files etc...
95 if ((ret=smartreader_usb_open_dev(reader))) {
96 cs_log("unable to open smartreader device %s in bus %s (ret=%d)\n", devname,busname,ret);
97 return ERROR;
98 }
99
100 cs_debug_mask (D_IFD,"IO:SR: Setting smartreader latency timer to 1ms");
101
102 //Set the FTDI latency timer to 1ms
103 ret = smartreader_set_latency_timer(reader, 1);
104
105 //Set databits to 8o2
106 ret = smartreader_set_line_property(reader, BITS_8, STOP_BIT_2, ODD);
107
108 //Set the DTR HIGH and RTS LOW
109 ret=smartreader_setdtr_rts(reader, 0, 0);
110
111 //Disable flow control
112 ret=smartreader_setflowctrl(reader, 0);
113
114 // start the reading thread
115 reader->g_read_buffer_size = 0;
116 reader->modem_status = 0 ;
117 pthread_mutex_init(&reader->g_read_mutex,NULL);
118 pthread_mutex_init(&reader->g_usb_mutex,NULL);
119 ret = pthread_create(&reader->rt, NULL, ReaderThread, (void *)(reader));
120 if (ret) {
121 cs_log("ERROR; return code from pthread_create() is %d", ret);
122 return ERROR;
123 }
124
125 return OK;
126}
127
128
129int SR_GetStatus (struct s_reader *reader, int * in)
130{
131 int state;
132
133 pthread_mutex_lock(&reader->g_read_mutex);
134 state =(reader->modem_status & 0x80) == 0x80 ? 0 : 2;
135 pthread_mutex_unlock(&reader->g_read_mutex);
136
137
138 //state = 0 no card, 1 = not ready, 2 = ready
139 if (state)
140 *in = 1; //CARD, even if not ready report card is in, or it will never get activated
141 else
142 *in = 0; //NOCARD
143
144 return OK;
145}
146
147int SR_Reset (struct s_reader *reader, ATR *atr)
148{
149 unsigned char data[40];
150 int ret;
151 int atr_ok;
152 unsigned int i;
153 int parity[4] = {EVEN, ODD, NONE, EVEN}; // the last EVEN is to try with different F, D values for irdeto card.
154
155 char *parity_str[5]={"NONE", "ODD", "EVEN", "MARK", "SPACE"};
156
157
158 if(reader->mhz==reader->cardmhz && reader->cardmhz*10000 > 3690000)
159 reader->sr_config.fs=reader->cardmhz*10000;
160 else
161 reader->sr_config.fs=3690000;
162
163 ResetSmartReader(reader);
164 for(i=0 ; i < 4 ;i++) {
165 reader->sr_config.irdeto=FALSE;
166 atr_ok=ERROR;
167 memset(data,0,sizeof(data));
168 reader->sr_config.parity=parity[i];
169
170 cs_debug_mask (D_IFD,"IO:SR: Trying with parity %s",parity_str[reader->sr_config.parity]);
171
172
173 // special irdeto case
174 if(i==3) {
175 cs_debug_mask (D_IFD,"IO:SR: Trying irdeto");
176
177 reader->sr_config.F=618; /// magic smartreader value
178 reader->sr_config.D=1;
179 reader->sr_config.T=2; // will be set to T=1 in EnableSmartReader
180 reader->sr_config.irdeto=TRUE;
181 }
182
183 smart_flush(reader);
184 EnableSmartReader(reader, reader->sr_config.fs/10000, reader->sr_config.F, (BYTE)reader->sr_config.D, reader->sr_config.N, reader->sr_config.T, reader->sr_config.inv,reader->sr_config.parity);
185 sched_yield();
186 cs_sleepms(500); //smartreader in mouse mode needs this, so it might also be needed in native mode.
187
188 //Reset smartcard
189
190 //Set the DTR HIGH and RTS HIGH
191 smartreader_setdtr_rts(reader, 1, 1);
192 // A card with an active low reset is reset by maintaining RST in state L for at least 40 000 clock cycles
193 // so if we have a base freq of 3.5712MHz : 40000/3690000 = .0112007168458781 seconds, aka 11ms
194 // so if we have a base freq of 6.00MHz : 40000/6000000 = .0066666666666666 seconds, aka 6ms
195 // here were doing 200ms .. is it too much ?
196 cs_sleepms(200);
197
198 //Set the DTR HIGH and RTS LOW
199 smartreader_setdtr_rts(reader, 1, 0);
200
201 cs_sleepms(200);
202 sched_yield();
203
204 //Read the ATR
205 ret = smart_read(reader,data, 40,1);
206 cs_debug_mask (D_IFD,"IO:SR: get ATR ret = %d" , ret);
207 if(ret)
208 cs_ddump(data,ATR_MAX_SIZE*2,"IO:SR: ");
209
210 if(data[0]!=0x3B && data[0]!=0x03 && data[0]!=0x3F) {
211 reader->sr_config.irdeto=FALSE;
212 continue; // this is not a valid ATR.
213 }
214
215 if(data[0]==0x03) {
216 cs_debug_mask (D_IFD,"IO:SR: Inverse convention detected, setting smartreader inv to 1");
217
218 reader->sr_config.inv=1;
219 EnableSmartReader(reader, reader->sr_config.fs/10000, reader->sr_config.F, (BYTE)reader->sr_config.D, reader->sr_config.N, reader->sr_config.T, reader->sr_config.inv,reader->sr_config.parity);
220 }
221 // parse atr
222 if(ATR_InitFromArray (atr, data, ret) == ATR_OK) {
223 cs_debug_mask (D_IFD,"IO:SR: ATR parsing OK");
224 atr_ok=OK;
225 if(i==3) {
226 cs_debug_mask (D_IFD,"IO:SR: Locking F and D for Irdeto mode");
227 reader->sr_config.irdeto=TRUE;
228 }
229 }
230
231 if(atr_ok == OK)
232 break;
233 }
234
235
236 return atr_ok;
237}
238
239int SR_Transmit (struct s_reader *reader, BYTE * buffer, unsigned size)
240
241{
242 unsigned int ret;
243 ret = smart_write(reader, buffer, size, 0);
244 if (ret!=size)
245 return ERROR;
246
247 return OK;
248}
249
250int SR_Receive (struct s_reader *reader, BYTE * buffer, unsigned size)
251{
252 unsigned int ret;
253 ret = smart_read(reader, buffer, size, 1);
254 if (ret!=size)
255 return ERROR;
256
257 return OK;
258}
259
260int SR_WriteSettings (struct s_reader *reader, unsigned short F, BYTE D, BYTE N, BYTE T)
261{
262// maintaining all this admin seems overdone, since after this init the values are nowhere needed
263// reader[ridx].sr_config.F=F;
264// reader[ridx].sr_config.D=D;
265// reader[ridx].sr_config.N=N;
266// reader[ridx].sr_config.T=T;
267// reader->sr_config.fs=reader->mhz*10000; //freq in Hz */
268// EnableSmartReader(reader, reader->sr_config.fs, reader->sr_config.F, (BYTE)reader->sr_config.D, reader->sr_config.N, reader->sr_config.T, reader->sr_config.inv,reader->sr_config.parity);
269
270 // smartreader supports 3.20, 3.43, 3.69, 4.00, 4.36, 4.80, 5.34, 6.00, 6.86, 8.00, 9.61, 12.0, 16.0 Mhz
271 if (reader->mhz >=1600) reader->mhz = 1600; else
272 if (reader->mhz >=1200) reader->mhz = 1200; else
273 if (reader->mhz >=961) reader->mhz = 961; else
274 if (reader->mhz >=800) reader->mhz = 800; else
275 if (reader->mhz >=686) reader->mhz = 686; else
276 if (reader->mhz >=600) reader->mhz = 600; else
277 if (reader->mhz >=534) reader->mhz = 534; else
278 if (reader->mhz >=480) reader->mhz = 480; else
279 if (reader->mhz >=436) reader->mhz = 436; else
280 if (reader->mhz >=400) reader->mhz = 400; else
281 if (reader->mhz >=369) reader->mhz = 369; else
282 if (reader->mhz >=343) reader->mhz = 343; else
283 reader->mhz = 320;
284 EnableSmartReader(reader, reader->mhz, F, D, N, T, reader->sr_config.inv,reader->sr_config.parity);
285
286 //baud rate not really used in native mode since
287 //it's handled by the card, so just set to maximum 3Mb/s
288 smartreader_set_baudrate(reader, 3000000);
289 sched_yield();
290
291 return OK;
292}
293
294int SR_SetParity (struct s_reader *reader)
295{
296 int ret;
297
298 char *parity_str[5]={"NONE", "ODD", "EVEN", "MARK", "SPACE"};
299 cs_debug_mask (D_IFD,"IO:SR: Setting parity to %s",parity_str[reader->sr_config.parity]);
300
301 ret = smartreader_set_line_property(reader, (enum smartreader_bits_type) 8, STOP_BIT_2, reader->sr_config.parity);
302 if(ret)
303 return ERROR;
304
305 sched_yield();
306
307 return OK;
308}
309
310int SR_Close (struct s_reader *reader)
311{
312
313 cs_debug_mask(D_IFD,"IO:SR: Closing smarteader\n");
314
315 reader->sr_config.running=FALSE;
316 pthread_join(reader->rt,NULL);
317 libusb_close(reader->sr_config.usb_dev_handle);
318 libusb_exit(NULL);
319 return OK;
320
321}
322
323
324static void EnableSmartReader(S_READER *reader, int clock, unsigned short Fi, unsigned char Di, unsigned char Ni, unsigned char T, unsigned char inv,int parity) {
325
326 int ret = 0;
327 unsigned char FiDi[4];
328 unsigned short freqk;
329 unsigned char Freq[3];
330 unsigned char N[2];
331 unsigned char Prot[2];
332 unsigned char Invert[2];
333
334 ret = smartreader_set_baudrate(reader, 9600);
335 smartreader_setflowctrl(reader, 0);
336 ret = smartreader_set_line_property(reader, (enum smartreader_bits_type) 5, STOP_BIT_2, NONE);
337
338 // command 1, set F and D parameter
339 if(!reader->sr_config.irdeto) {
340 cs_debug_mask (D_IFD,"IO:SR: sending F=%04X (%d) to smartreader",Fi,Fi);
341 cs_debug_mask (D_IFD,"IO:SR: sending D=%02X (%d) to smartreader",Di,Di);
342 FiDi[0]=0x01;
343 FiDi[1]=HIBYTE(Fi);
344 FiDi[2]=LOBYTE(Fi);
345 FiDi[3]=Di;
346 ret = smart_write(reader,FiDi, sizeof (FiDi),0);
347 }
348 else {
349 cs_log("Not setting F and D as we're in Irdeto mode");
350 }
351
352 // command 2, set the frequency in KHz
353 // direct from the source .. 4MHz is the best init frequency for T=0 card, but looks like it's causing issue with some nagra card, reveting to 3.69MHz
354 freqk = clock * 10; //clock with type int couldnt hold freq in Hz on all platforms, so I reverted to 10khz units (like mhz) - dingo
355 cs_debug_mask (D_IFD,"IO:SR: sending Freq=%04X (%d) to smartreader",freqk,freqk);
356 Freq[0]=0x02;
357 Freq[1]=HIBYTE(freqk);
358 Freq[2]=LOBYTE(freqk);
359 ret = smart_write(reader, Freq, sizeof (Freq),0);
360
361 // command 3, set paramter N
362 cs_debug_mask (D_IFD,"IO:SR: sending N=%02X (%d) to smartreader",Ni,Ni);
363 N[0]=0x03;
364 N[1]=Ni;
365 ret = smart_write(reader, N, sizeof (N),0);
366
367 // command 4 , set parameter T
368 if(reader->sr_config.irdeto && T==2) // special trick to get ATR for Irdeto card, we need T=1 at reset, after that oscam takes care of T1 protocol, so we need T=0
369 {
370 T=1;
371 reader->sr_config.T=1;
372 }
373 else if (T==1)
374 T=0; // T=1 protocol is handled by oscam
375
376 cs_debug_mask (D_IFD,"IO:SR: sending T=%02X (%d) to smartreader",T,T);
377 Prot[0]=0x04;
378 Prot[1]=T;
379 ret = smart_write(reader, Prot, sizeof (Prot),0);
380
381 // command 5, set invert y/n
382 cs_debug_mask (D_IFD,"IO:SR: sending inv=%02X to smartreader",inv);
383 Invert[0]=0x05;
384 Invert[1]=inv;
385 ret = smart_write(reader, Invert, sizeof (Invert),0);
386
387 ret = smartreader_set_line_property2(reader, BITS_8, STOP_BIT_2, parity, BREAK_ON);
388 // send break for 350ms, also comes from JoePub debugging.
389 cs_sleepms(350);
390 ret = smartreader_set_line_property2(reader, BITS_8, STOP_BIT_2, parity, BREAK_OFF);
391
392 smart_flush(reader);
393}
394
395static void ResetSmartReader(S_READER *reader)
396{
397
398 smart_flush(reader);
399 // set smartreader+ default values
400 reader->sr_config.F=372;
401 reader->sr_config.D=1.0;
402 if(reader->mhz==reader->cardmhz && reader->cardmhz*10000 > 3690000)
403 reader->sr_config.fs=reader->cardmhz*10000;
404 else
405 reader->sr_config.fs=3690000;
406 reader->sr_config.N=0;
407 reader->sr_config.T=0;
408 reader->sr_config.inv=0;
409
410 EnableSmartReader(reader, reader->sr_config.fs/10000, reader->sr_config.F, (BYTE)reader->sr_config.D, reader->sr_config.N, reader->sr_config.T, reader->sr_config.inv,reader->sr_config.parity);
411 sched_yield();
412
413}
414
415static bool smartreader_check_endpoint(libusb_device *usb_dev)
416{
417 struct libusb_device_descriptor desc;
418 struct libusb_config_descriptor *configDesc;
419 int ret;
420 int j,k,l;
421 uint8_t tmpEndpointAddress;
422 int nb_endpoint_ok;
423
424
425 nb_endpoint_ok=0;
426 ret = libusb_get_device_descriptor(usb_dev, &desc);
427 if (ret < 0) {
428 cs_log("Smartreader : couldn't read device descriptor, assuming this is not a smartreader");
429 return FALSE;
430 }
431 if (desc.bNumConfigurations) {
432 ret=libusb_get_active_config_descriptor(usb_dev,&configDesc);
433 if(ret) {
434 cs_log("Smartreader : couldn't read config descriptor , assuming this is not a smartreader");
435 return FALSE;
436 }
437
438 for(j=0; j<configDesc->bNumInterfaces; j++)
439 for(k=0; k<configDesc->interface[j].num_altsetting; k++)
440 for(l=0; l<configDesc->interface[j].altsetting[k].bNumEndpoints; l++) {
441 tmpEndpointAddress=configDesc->interface[j].altsetting[k].endpoint[l].bEndpointAddress;
442 if((tmpEndpointAddress== 0x1) || (tmpEndpointAddress== 0x82))
443 nb_endpoint_ok++;
444 }
445 }
446 if(nb_endpoint_ok!=2)
447 return FALSE;
448 return TRUE;
449}
450
451
452static struct libusb_device* find_smartreader(const char *busname,const char *devname)
453{
454 int dev_found;
455 libusb_device *dev;
456 libusb_device_handle *usb_dev_handle;
457 libusb_device **devs;
458 ssize_t cnt;
459 int i = 0;
460 int ret;
461 struct libusb_device_descriptor desc;
462
463 cnt = libusb_get_device_list(NULL, &devs);
464 if (cnt < 0)
465 return NULL;
466
467 while ((dev = devs[i++]) != NULL) {
468 dev_found=FALSE;
469 ret = libusb_get_device_descriptor(dev, &desc);
470 if (ret < 0) {
471 cs_log("failed to get device descriptor for device %s on bus %s\n",devname,busname);
472 return NULL;
473 }
474
475 if (desc.idVendor==0x0403 && desc.idProduct==0x6001) {
476 ret=libusb_open(dev,&usb_dev_handle);
477 if (ret) {
478 cs_log ("coulnd't open device %03d:%03d\n", libusb_get_bus_number(dev), libusb_get_device_address(dev));
479 continue;
480 }
481
482 if(libusb_get_bus_number(dev)==atoi(busname) && libusb_get_device_address(dev)==atoi(devname)) {
483 cs_debug_mask(D_IFD,"IO:SR: Checking FTDI device: %03d on bus %03d",libusb_get_device_address(dev),libusb_get_bus_number(dev));
484 // check for smargo endpoints.
485 if(smartreader_check_endpoint(dev))
486 dev_found=TRUE;
487 }
488
489
490 libusb_close(usb_dev_handle);
491 }
492
493 if (dev_found)
494 break;
495 }
496
497 if(!dev_found) {
498 cs_log("Smartreader device %s:%s not found",busname,devname);
499 return NULL;
500 }
501 else
502 cs_log("Found smartreader device %s:%s",busname,devname);
503
504 return dev;
505}
506
507void smartreader_init(S_READER *reader)
508{
509 reader->sr_config.usb_dev = NULL;
510 reader->sr_config.usb_dev_handle=NULL;
511 reader->sr_config.usb_read_timeout = 10000;
512 reader->sr_config.usb_write_timeout = 10000;
513
514 reader->sr_config.type = TYPE_BM; /* chip type */
515 reader->sr_config.baudrate = -1;
516 reader->sr_config.bitbang_enabled = 0; /* 0: normal mode 1: any of the bitbang modes enabled */
517
518 reader->sr_config.writebuffer_chunksize = 64;
519 reader->sr_config.max_packet_size = 0;
520
521 reader->sr_config.interface = INTERFACE_ANY;
522 reader->sr_config.index = INTERFACE_A;
523 reader->sr_config.in_ep = 0x02;
524 reader->sr_config.out_ep = 0x82;
525}
526
527
528static unsigned int smartreader_determine_max_packet_size(S_READER *reader)
529{
530 unsigned int packet_size;
531 struct libusb_device_descriptor desc;
532 struct libusb_config_descriptor *configDesc;
533 struct libusb_interface interface;
534 struct libusb_interface_descriptor intDesc;
535
536 int ret;
537 // Determine maximum packet size. Init with default value.
538 // New hi-speed devices from FTDI use a packet size of 512 bytes
539 // but could be connected to a normal speed USB hub -> 64 bytes packet size.
540 if (reader->sr_config.type == TYPE_2232H || reader->sr_config.type == TYPE_4232H)
541 packet_size = 512;
542 else
543 packet_size = 64;
544
545 ret = libusb_get_device_descriptor(reader->sr_config.usb_dev, &desc);
546 if (ret < 0) {
547 cs_log("Smartreader : couldn't read device descriptor , using default packet size");
548 return packet_size;
549 }
550 if (desc.bNumConfigurations)
551 {
552 ret=libusb_get_active_config_descriptor(reader->sr_config.usb_dev,&configDesc);
553 if(ret) {
554 cs_log("Smartreader : couldn't read config descriptor , using default packet size");
555 return packet_size;
556 }
557
558 if (reader->sr_config.interface < configDesc->bNumInterfaces)
559 {
560 interface=configDesc->interface[reader->sr_config.interface];
561 if (interface.num_altsetting > 0)
562 {
563 intDesc = interface.altsetting[0];
564 if (intDesc.bNumEndpoints > 0)
565 {
566 packet_size = intDesc.endpoint[0].wMaxPacketSize;
567 }
568 }
569 }
570 }
571
572 return packet_size;
573}
574
575
576static int smartreader_usb_close_internal (S_READER *reader)
577{
578 int ret = 0;
579
580 if (reader->sr_config.usb_dev_handle)
581 {
582 libusb_close (reader->sr_config.usb_dev_handle);
583 reader->sr_config.usb_dev_handle=NULL;
584 }
585
586 return ret;
587}
588
589
590int smartreader_usb_reset(S_READER *reader)
591{
592 if (libusb_control_transfer(reader->sr_config.usb_dev_handle,
593 FTDI_DEVICE_OUT_REQTYPE,
594 SIO_RESET_REQUEST,
595 SIO_RESET_SIO,
596 reader->sr_config.index,
597 NULL,
598 0,
599 reader->sr_config.usb_write_timeout) != 0) {
600 cs_log("Smartreader reset failed");
601 return (-1);
602 }
603
604 // Invalidate data in the readbuffer
605 // ftdi->readbuffer_offset = 0;
606 // ftdi->readbuffer_remaining = 0;
607
608 return 0;
609}
610
611
612int smartreader_usb_open_dev(S_READER *reader)
613{
614 int detach_errno = 0;
615 struct libusb_device_descriptor desc;
616 int ret;
617
618#ifdef __WIN32__
619 int config;
620 int config_val = 1;
621#endif
622
623 ret=libusb_open(reader->sr_config.usb_dev,&reader->sr_config.usb_dev_handle);
624 if (ret) {
625 cs_log("Smartreader usb_open() failed");
626 return (-4);
627 }
628#if defined(OS_LINUX)
629 // Try to detach smartreader_sio kernel module.
630 // Returns ENODATA if driver is not loaded.
631 //
632 // The return code is kept in a separate variable and only parsed
633 // if usb_set_configuration() or usb_claim_interface() fails as the
634 // detach operation might be denied and everything still works fine.
635 // Likely scenario is a static smartreader_sio kernel module.
636 if (libusb_detach_kernel_driver(reader->sr_config.usb_dev_handle, reader->sr_config.interface) != 0 && errno != ENODATA) {
637 detach_errno = errno;
638 cs_log("Couldn't detach interface from kernel. Please unload the FTDI drivers");
639 return(LIBUSB_ERROR_NOT_SUPPORTED);
640 }
641#endif
642 ret = libusb_get_device_descriptor(reader->sr_config.usb_dev, &desc);
643
644#ifdef __WIN32__
645 // set configuration (needed especially for windows)
646 // tolerate EBUSY: one device with one configuration, but two interfaces
647 // and libftdi sessions to both interfaces (e.g. FT2232)
648
649 if (desc.bNumConfigurations > 0)
650 {
651 ret=libusb_get_configuration(reader->sr_config.usb_dev_handle,&config);
652
653 // libusb-win32 on Windows 64 can return a null pointer for a valid device
654 if (libusb_set_configuration(reader->sr_config.usb_dev_handle, config) &&
655 errno != EBUSY)
656 {
657 smartreader_usb_close_internal (reader);
658 if (detach_errno == EPERM) {
659 cs_log("inappropriate permissions on device!");
660 return(-8);
661 }
662 else {
663 cs_log("unable to set usb configuration. Make sure smartreader_sio is unloaded!");
664 return (-3);
665 }
666 }
667 }
668#endif
669
670 ret=libusb_claim_interface(reader->sr_config.usb_dev_handle, reader->sr_config.interface) ;
671 if (ret!= 0)
672 {
673 smartreader_usb_close_internal (reader);
674 if (detach_errno == EPERM) {
675 cs_log("inappropriate permissions on device!");
676 return (-8);
677 }
678 else {
679 cs_log("unable to claim usb device. Make sure smartreader_sio is unloaded!");
680 return (-5);
681 }
682 }
683
684 if (smartreader_usb_reset (reader) != 0) {
685 smartreader_usb_close_internal (reader);
686 cs_log("smartreader_usb_reset failed");
687 return (-6);
688 }
689
690 // Try to guess chip type
691 // Bug in the BM type chips: bcdDevice is 0x200 for serial == 0
692 if (desc.bcdDevice == 0x400 || (desc.bcdDevice == 0x200
693 && desc.iSerialNumber == 0))
694 reader->sr_config.type = TYPE_BM;
695 else if (desc.bcdDevice == 0x200)
696 reader->sr_config.type = TYPE_AM;
697 else if (desc.bcdDevice == 0x500)
698 reader->sr_config.type = TYPE_2232C;
699 else if (desc.bcdDevice == 0x600)
700 reader->sr_config.type = TYPE_R;
701 else if (desc.bcdDevice == 0x700)
702 reader->sr_config.type = TYPE_2232H;
703 else if (desc.bcdDevice == 0x800)
704 reader->sr_config.type = TYPE_4232H;
705
706 // Set default interface on dual/quad type chips
707 switch(reader->sr_config.type) {
708 case TYPE_2232C:
709 case TYPE_2232H:
710 case TYPE_4232H:
711 if (!reader->sr_config.index)
712 reader->sr_config.index = INTERFACE_A;
713 break;
714 default:
715 break;
716 }
717
718 // Determine maximum packet size
719 reader->sr_config.max_packet_size = smartreader_determine_max_packet_size(reader);
720
721 if (smartreader_set_baudrate (reader, 9600) != 0) {
722 smartreader_usb_close_internal (reader);
723 cs_log("set baudrate failed");
724 return (-7);
725 }
726
727 return (0);
728}
729
730
731int smartreader_usb_purge_rx_buffer(S_READER *reader)
732{
733 if (libusb_control_transfer(reader->sr_config.usb_dev_handle,
734 FTDI_DEVICE_OUT_REQTYPE,
735 SIO_RESET_REQUEST,
736 SIO_RESET_PURGE_RX,
737 reader->sr_config.index,
738 NULL,
739 0,
740 reader->sr_config.usb_write_timeout) != 0) {
741 cs_log("FTDI purge of RX buffer failed");
742 return (-1);
743 }
744
745
746 return 0;
747}
748
749int smartreader_usb_purge_tx_buffer(S_READER *reader)
750{
751 if (libusb_control_transfer(reader->sr_config.usb_dev_handle,
752 FTDI_DEVICE_OUT_REQTYPE,
753 SIO_RESET_REQUEST,
754 SIO_RESET_PURGE_TX,
755 reader->sr_config.index,
756 NULL,
757 0,
758 reader->sr_config.usb_write_timeout) != 0) {
759 cs_log("FTDI purge of TX buffer failed");
760 return (-1);
761 }
762
763 return 0;
764}
765
766int smartreader_usb_purge_buffers(S_READER *reader)
767{
768 int result;
769
770 result = smartreader_usb_purge_rx_buffer(reader);
771 if (result < 0)
772 return -1;
773
774 result = smartreader_usb_purge_tx_buffer(reader);
775 if (result < 0)
776 return -2;
777
778 return 0;
779}
780
781static int smartreader_convert_baudrate(int baudrate, S_READER *reader, unsigned short *value, unsigned short *index)
782{
783 static const char am_adjust_up[8] = {0, 0, 0, 1, 0, 3, 2, 1};
784 static const char am_adjust_dn[8] = {0, 0, 0, 1, 0, 1, 2, 3};
785 static const char frac_code[8] = {0, 3, 2, 4, 1, 5, 6, 7};
786 int divisor, best_divisor, best_baud, best_baud_diff;
787 unsigned long encoded_divisor;
788 int i;
789
790 if (baudrate <= 0)
791 {
792 // Return error
793 return -1;
794 }
795
796 divisor = 24000000 / baudrate;
797
798 if (reader->sr_config.type == TYPE_AM)
799 {
800 // Round down to supported fraction (AM only)
801 divisor -= am_adjust_dn[divisor & 7];
802 }
803
804 // Try this divisor and the one above it (because division rounds down)
805 best_divisor = 0;
806 best_baud = 0;
807 best_baud_diff = 0;
808 for (i = 0; i < 2; i++)
809 {
810 int try_divisor = divisor + i;
811 int baud_estimate;
812 int baud_diff;
813
814 // Round up to supported divisor value
815 if (try_divisor <= 8)
816 {
817 // Round up to minimum supported divisor
818 try_divisor = 8;
819 }
820 else if (reader->sr_config.type != TYPE_AM && try_divisor < 12)
821 {
822 // BM doesn't support divisors 9 through 11 inclusive
823 try_divisor = 12;
824 }
825 else if (divisor < 16)
826 {
827 // AM doesn't support divisors 9 through 15 inclusive
828 try_divisor = 16;
829 }
830 else
831 {
832 if (reader->sr_config.type == TYPE_AM)
833 {
834 // Round up to supported fraction (AM only)
835 try_divisor += am_adjust_up[try_divisor & 7];
836 if (try_divisor > 0x1FFF8)
837 {
838 // Round down to maximum supported divisor value (for AM)
839 try_divisor = 0x1FFF8;
840 }
841 }
842 else
843 {
844 if (try_divisor > 0x1FFFF)
845 {
846 // Round down to maximum supported divisor value (for BM)
847 try_divisor = 0x1FFFF;
848 }
849 }
850 }
851 // Get estimated baud rate (to nearest integer)
852 baud_estimate = (24000000 + (try_divisor / 2)) / try_divisor;
853 // Get absolute difference from requested baud rate
854 if (baud_estimate < baudrate)
855 {
856 baud_diff = baudrate - baud_estimate;
857 }
858 else
859 {
860 baud_diff = baud_estimate - baudrate;
861 }
862 if (i == 0 || baud_diff < best_baud_diff)
863 {
864 // Closest to requested baud rate so far
865 best_divisor = try_divisor;
866 best_baud = baud_estimate;
867 best_baud_diff = baud_diff;
868 if (baud_diff == 0)
869 {
870 // Spot on! No point trying
871 break;
872 }
873 }
874 }
875 // Encode the best divisor value
876 encoded_divisor = (best_divisor >> 3) | (frac_code[best_divisor & 7] << 14);
877 // Deal with special cases for encoded value
878 if (encoded_divisor == 1)
879 {
880 encoded_divisor = 0; // 3000000 baud
881 }
882 else if (encoded_divisor == 0x4001)
883 {
884 encoded_divisor = 1; // 2000000 baud (BM only)
885 }
886 // Split into "value" and "index" values
887 *value = (unsigned short)(encoded_divisor & 0xFFFF);
888 if (reader->sr_config.type == TYPE_2232C || reader->sr_config.type == TYPE_2232H || reader->sr_config.type == TYPE_4232H)
889 {
890 *index = (unsigned short)(encoded_divisor >> 8);
891 *index &= 0xFF00;
892 *index |= reader->sr_config.index;
893 }
894 else
895 *index = (unsigned short)(encoded_divisor >> 16);
896
897 // Return the nearest baud rate
898 return best_baud;
899}
900
901int smartreader_set_baudrate(S_READER *reader, int baudrate)
902{
903 unsigned short value, index;
904 int actual_baudrate;
905
906 if (reader->sr_config.bitbang_enabled)
907 {
908 baudrate = baudrate*4;
909 }
910
911 actual_baudrate = smartreader_convert_baudrate(baudrate, reader, &value, &index);
912 if (actual_baudrate <= 0) {
913 cs_log("Silly baudrate <= 0.");
914 return (-1);
915 }
916
917 // Check within tolerance (about 5%)
918 if ((actual_baudrate * 2 < baudrate /* Catch overflows */ )
919 || ((actual_baudrate < baudrate)
920 ? (actual_baudrate * 21 < baudrate * 20)
921 : (baudrate * 21 < actual_baudrate * 20))) {
922 cs_log("Unsupported baudrate. Note: bitbang baudrates are automatically multiplied by 4");
923 return (-1);
924 }
925
926 if (libusb_control_transfer(reader->sr_config.usb_dev_handle,
927 FTDI_DEVICE_OUT_REQTYPE,
928 SIO_SET_BAUDRATE_REQUEST,
929 value,
930 index,
931 NULL,
932 0,
933 reader->sr_config.usb_write_timeout) != 0) {
934 cs_log("Setting new baudrate failed");
935 return (-2);
936 }
937
938 reader->sr_config.baudrate = baudrate;
939 return 0;
940}
941
942int smartreader_setdtr_rts(S_READER *reader, int dtr, int rts)
943{
944 unsigned short usb_val;
945
946 if (dtr)
947 usb_val = SIO_SET_DTR_HIGH;
948 else
949 usb_val = SIO_SET_DTR_LOW;
950
951 if (rts)
952 usb_val |= SIO_SET_RTS_HIGH;
953 else
954 usb_val |= SIO_SET_RTS_LOW;
955
956 if (libusb_control_transfer(reader->sr_config.usb_dev_handle,
957 FTDI_DEVICE_OUT_REQTYPE,
958 SIO_SET_MODEM_CTRL_REQUEST,
959 usb_val,
960 reader->sr_config.index,
961 NULL,
962 0,
963 reader->sr_config.usb_write_timeout) != 0) {
964 cs_log("set of rts/dtr failed");
965 return (-1);
966 }
967
968 return 0;
969}
970
971int smartreader_setflowctrl(S_READER *reader, int flowctrl)
972{
973 if (libusb_control_transfer(reader->sr_config.usb_dev_handle,
974 FTDI_DEVICE_OUT_REQTYPE,
975 SIO_SET_FLOW_CTRL_REQUEST,
976 0,
977 (flowctrl | reader->sr_config.index),
978 NULL,
979 0,
980 reader->sr_config.usb_write_timeout) != 0) {
981 cs_log("set flow control failed");
982 return (-1);
983 }
984
985 return 0;
986}
987
988int smartreader_set_line_property2(S_READER *reader, enum smartreader_bits_type bits,
989 enum smartreader_stopbits_type sbit, enum smartreader_parity_type parity,
990 enum smartreader_break_type break_type)
991{
992 unsigned short value = bits;
993
994 switch (parity)
995 {
996 case NONE:
997 value |= (0x00 << 8);
998 break;
999 case ODD:
1000 value |= (0x01 << 8);
1001 break;
1002 case EVEN:
1003 value |= (0x02 << 8);
1004 break;
1005 case MARK:
1006 value |= (0x03 << 8);
1007 break;
1008 case SPACE:
1009 value |= (0x04 << 8);
1010 break;
1011 }
1012
1013 switch (sbit)
1014 {
1015 case STOP_BIT_1:
1016 value |= (0x00 << 11);
1017 break;
1018 case STOP_BIT_15:
1019 value |= (0x01 << 11);
1020 break;
1021 case STOP_BIT_2:
1022 value |= (0x02 << 11);
1023 break;
1024 }
1025
1026 switch (break_type)
1027 {
1028 case BREAK_OFF:
1029 value |= (0x00 << 14);
1030 break;
1031 case BREAK_ON:
1032 value |= (0x01 << 14);
1033 break;
1034 }
1035
1036 if (libusb_control_transfer(reader->sr_config.usb_dev_handle,
1037 FTDI_DEVICE_OUT_REQTYPE,
1038 SIO_SET_DATA_REQUEST,
1039 value,
1040 reader->sr_config.index,
1041 NULL,
1042 0,
1043 reader->sr_config.usb_write_timeout) != 0) {
1044 cs_log("Setting new line property failed");
1045 return (-1);
1046 }
1047
1048 return 0;
1049}
1050
1051
1052int smartreader_set_line_property(S_READER *reader, enum smartreader_bits_type bits,
1053 enum smartreader_stopbits_type sbit, enum smartreader_parity_type parity)
1054{
1055 return smartreader_set_line_property2(reader, bits, sbit, parity, BREAK_OFF);
1056}
1057
1058
1059
1060void smart_flush(S_READER *reader)
1061{
1062
1063 smartreader_usb_purge_buffers(reader);
1064
1065 pthread_mutex_lock(&reader->g_read_mutex);
1066 reader->g_read_buffer_size = 0;
1067 pthread_mutex_unlock(&reader->g_read_mutex);
1068 sched_yield();
1069}
1070
1071static int smart_read(S_READER *reader, unsigned char* buff, unsigned int size, int timeout_sec)
1072{
1073
1074 int ret = 0;
1075 unsigned int total_read = 0;
1076 struct timeval start, now, dif = {0,0};
1077 gettimeofday(&start,NULL);
1078
1079 while(total_read < size && dif.tv_sec < timeout_sec) {
1080 pthread_mutex_lock(&reader->g_read_mutex);
1081
1082 if(reader->g_read_buffer_size > 0) {
1083
1084 ret = reader->g_read_buffer_size > size-total_read ? size-total_read : reader->g_read_buffer_size;
1085 memcpy(buff+total_read,reader->g_read_buffer,ret);
1086 reader->g_read_buffer_size -= ret;
1087
1088 if(reader->g_read_buffer_size > 0){
1089 memcpy(reader->g_read_buffer, reader->g_read_buffer + ret, reader->g_read_buffer_size);
1090 }
1091
1092 total_read+=ret;
1093 }
1094 pthread_mutex_unlock(&reader->g_read_mutex);
1095
1096 gettimeofday(&now,NULL);
1097 timersub(&now, &start, &dif);
1098 struct timespec req_ts;
1099 req_ts.tv_sec = 0;
1100 req_ts.tv_nsec = 50000;
1101 nanosleep (&req_ts, NULL);//behaves better to signals than usleep and sleep
1102 sched_yield();
1103 }
1104 cs_ddump(buff, total_read, "SR IO: Receive: ");
1105
1106
1107 return total_read;
1108}
1109
1110int smartreader_write_data(S_READER *reader, unsigned char *buf, unsigned int size)
1111{
1112 int ret;
1113 int write_size;
1114 unsigned int offset = 0;
1115 int total_written = 0;
1116 int written;
1117
1118 if(size<reader->sr_config.writebuffer_chunksize)
1119 write_size=size;
1120 else
1121 write_size = reader->sr_config.writebuffer_chunksize;
1122
1123 while (offset < size)
1124 {
1125
1126 if (offset+write_size > size)
1127 write_size = size-offset;
1128
1129 ret = libusb_bulk_transfer(reader->sr_config.usb_dev_handle,
1130 reader->sr_config.in_ep,
1131 buf+offset,
1132 write_size,
1133 &written,
1134 reader->sr_config.usb_write_timeout);
1135 if (ret < 0) {
1136 cs_log("usb bulk write failed : ret = %d",ret);
1137 return(ret);
1138 }
1139 cs_ddump(buf+offset, written, "SR IO: Transmit: ");
1140 total_written += written;
1141 offset += write_size;//FIXME shouldnt this be written?
1142 }
1143
1144 return total_written;
1145}
1146
1147static int smartreader_set_latency_timer(S_READER *reader, unsigned short latency)
1148{
1149 unsigned short usb_val;
1150
1151 if (latency < 1) {
1152 cs_log("latency out of range. Only valid for 1-255");
1153 return (-1);
1154 }
1155
1156 usb_val = latency;
1157 if (libusb_control_transfer(reader->sr_config.usb_dev_handle,
1158 FTDI_DEVICE_OUT_REQTYPE,
1159 SIO_SET_LATENCY_TIMER_REQUEST,
1160 usb_val,
1161 reader->sr_config.index,
1162 NULL,
1163 0,
1164 reader->sr_config.usb_write_timeout) != 0) {
1165 cs_log("unable to set latency timer");
1166 return (-2);
1167 }
1168
1169 return 0;
1170}
1171
1172static int smart_write(S_READER *reader, unsigned char* buff, unsigned int size, int udelay)
1173{
1174
1175 int ret = 0;
1176 unsigned int idx;
1177
1178 if (udelay == 0) {
1179 ret = smartreader_write_data(reader, buff, size);
1180 if(ret<0) {
1181 cs_debug_mask (D_IFD,"IO:SR: USB write error : %d",ret);
1182 }
1183 }
1184 else {
1185 for (idx = 0; idx < size; idx++) {
1186 if ((ret = smartreader_write_data(reader, &buff[idx], 1)) < 0){
1187 break;
1188 }
1189 struct timespec req_ts;
1190 req_ts.tv_sec = 0;
1191 req_ts.tv_nsec = udelay * 1000;
1192 nanosleep (&req_ts, NULL); //behaves better with signals than usleep
1193 }
1194 }
1195 sched_yield();
1196 return ret;
1197}
1198
1199static void read_callback(struct libusb_transfer *transfer){
1200
1201 struct s_reader *reader = (struct s_reader*)transfer->user_data;
1202 int copy_size;
1203 int ret;
1204
1205 if(transfer->status == LIBUSB_TRANSFER_COMPLETED) {
1206
1207 if(transfer->actual_length > 2) { //FTDI always sends modem status bytes as first 2 chars with the 232BM
1208
1209 pthread_mutex_lock(&reader->g_read_mutex);
1210
1211 if(reader->g_read_buffer_size == sizeof(reader->g_read_buffer)) {
1212 cs_log("IO:SR: buffer full\n");
1213 //if out read buffer is full then delay
1214 //slightly and go around again
1215 ret = libusb_submit_transfer(transfer);
1216 if(ret!=0)
1217 cs_log("IO:SR: submit async transfer failed with error %d\n",ret);
1218 pthread_mutex_unlock(&reader->g_read_mutex);
1219 return;
1220 }
1221
1222 reader->modem_status = transfer->buffer[1];
1223 copy_size = sizeof(reader->g_read_buffer) - reader->g_read_buffer_size > (unsigned int)transfer->actual_length-2 ? (unsigned int)transfer->actual_length-2: sizeof(reader->g_read_buffer) - reader->g_read_buffer_size;
1224 memcpy(reader->g_read_buffer+reader->g_read_buffer_size,transfer->buffer+2,copy_size);
1225 reader->g_read_buffer_size += copy_size;
1226 pthread_mutex_unlock(&reader->g_read_mutex);
1227 }
1228 else {
1229 if(transfer->actual_length==2) {
1230 pthread_mutex_lock(&reader->g_read_mutex);
1231 reader->modem_status=transfer->buffer[1];
1232 pthread_mutex_unlock(&reader->g_read_mutex);
1233 }
1234 }
1235
1236 ret = libusb_submit_transfer(transfer);
1237 sched_yield();
1238
1239 if(ret!=0)
1240 cs_log("IO:SR: submit async transfer failed with error %d\n",ret);
1241
1242 }
1243 else
1244 cs_log("IO:SR: USB bulk read failed with error %d\n",transfer->status);
1245}
1246
1247
1248static void* ReaderThread(void *p)
1249{
1250
1251 struct libusb_transfer* usbt[NUM_TXFERS];
1252 unsigned char usb_buffers[NUM_TXFERS][64];
1253 struct s_reader *reader;
1254 int ret,idx;
1255
1256 reader = (struct s_reader *)p;
1257 reader->sr_config.running=TRUE;
1258
1259 for(idx=0; idx<NUM_TXFERS; idx++) {
1260 usbt[idx] = libusb_alloc_transfer(0);
1261
1262 libusb_fill_bulk_transfer( usbt[idx],
1263 reader->sr_config.usb_dev_handle,
1264 reader->sr_config.out_ep,
1265 usb_buffers[idx],
1266 64,
1267 &read_callback,
1268 p,
1269 0 );
1270
1271 ret = libusb_submit_transfer(usbt[idx]);
1272 }
1273
1274 while(reader->sr_config.running) {
1275 ret = libusb_handle_events(NULL);
1276 if(ret!=0)
1277 cs_log("libusb_handle_events returned with %d\n",ret);
1278 }
1279
1280 pthread_exit(NULL);
1281}
1282
1283#endif // HAVE_LIBUSB && USE_PTHREAD
Note: See TracBrowser for help on using the repository browser.