forked from odeke-em/chdkptp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chdkptp.c
2259 lines (2017 loc) · 57.8 KB
/
chdkptp.c
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
/* chdkptp.c
*
* based on ptpcam.c
* Copyright (C) 2001-2005 Mariusz Woloszyn <[email protected]>
* additions
* Copyright (C) 2010-2014 <reyalp (at) gmail dot com>
*
* 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if defined(WIN32) && defined(CHDKPTP_PTPIP)
#define WINVER 0x0502
#endif
#include "config.h"
#include "ptp.h"
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <utime.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <fcntl.h>
#ifdef WIN32
#ifdef CHDKPTP_PTPIP
#include <winsock2.h>
#include <ws2tcpip.h>
#endif
#else
#include <sys/mman.h>
#ifdef CHDKPTP_PTPIP
#include <sys/socket.h>
#include <netdb.h>
#endif
#endif
#include <usb.h>
#ifdef CHDKPTP_READLINE
#include <readline/readline.h>
#include <readline/history.h>
#endif
#ifdef WIN32
#define usleep(usec) Sleep((usec)/1000)
#define sleep(sec) Sleep(sec*1000)
#endif
#ifdef ENABLE_NLS
# include <libintl.h>
# undef _
# define _(String) dgettext (GETTEXT_PACKAGE, String)
# ifdef gettext_noop
# define N_(String) gettext_noop (String)
# else
# define N_(String) (String)
# endif
#else
# define textdomain(String) (String)
# define gettext(String) (String)
# define dgettext(Domain,Message) (Message)
# define dcgettext(Domain,Message,Type) (Message)
# define bindtextdomain(Domain,Directory) (Domain)
# define _(String) (String)
# define N_(String) (String)
#endif
#include "sockutil.h"
#include "ptpcam.h"
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
#ifdef CHDKPTP_IUP
#include <iup.h>
#include <iuplua.h>
#ifdef CHDKPTP_CD
#include <cd.h>
#include <cdlua.h>
#include <cdiup.h>
#include <cdluaiup.h>
#endif
#endif
#include "lfs/lfs.h"
#include "lbuf.h"
#include "liveimg.h"
#include "rawimg.h"
// workaround for error building with CD using recent mingw
// d:/devel/cd-5.7/lib\libcdcontextplus.a(cdwinp.o):cdwinp.cpp:(.text+0x8dca): undefined reference to `_GdipFontFamilyCachedGenericSansSerif'
// these are defined "extern" in mingw include/gdiplus/gdiplusimpl.h
#if defined(CHDKPTP_CD) && defined(CHDKPTP_GDIP_FONT_HACK)
void *_GdipFontFamilyCachedGenericMonospace;
void *_GdipFontFamilyCachedGenericSansSerif;
void *_GdipFontFamilyCachedGenericSerif;
#endif
/* some defines comes here */
/* CHDK additions */
#define CHDKPTP_VERSION_MAJOR 0
#define CHDKPTP_VERSION_MINOR 5
/* lua registry indexes */
/* meta table for connection objects */
#define CHDK_CONNECTION_META "chkdptp.connection_meta"
/* list of opened connections, indexed weakly as t[path] = connection */
#define CHDK_CONNECTION_LIST "chkdptp.connection_list"
/* meta table for for connection list */
#define CHDK_CONNECTION_LIST_META "chkdptp.connection_list_meta"
/* meta for error object */
#define CHDK_API_ERROR_META "chkdptp.api_error_meta"
/* USB interface class */
#ifndef USB_CLASS_PTP
#define USB_CLASS_PTP 6
#endif
/* USB control message data phase direction */
#ifndef USB_DP_HTD
#define USB_DP_HTD (0x00 << 7) /* host to device */
#endif
#ifndef USB_DP_DTH
#define USB_DP_DTH (0x01 << 7) /* device to host */
#endif
/* PTP class specific requests */
#ifndef USB_REQ_DEVICE_RESET
#define USB_REQ_DEVICE_RESET 0x66
#endif
#ifndef USB_REQ_GET_DEVICE_STATUS
#define USB_REQ_GET_DEVICE_STATUS 0x67
#endif
/* USB Feature selector HALT */
#ifndef USB_FEATURE_HALT
#define USB_FEATURE_HALT 0x00
#endif
/* OUR APPLICATION USB URB (2MB) ;) */
#define PTPCAM_USB_URB 2097152
#define USB_TIMEOUT 5000
/* one global variable (yes, I know it sucks) */
short verbose=0;
// TODO this is lame
#define CHDK_CONNECTION_METHOD PTPParams *params; PTP_CON_STATE *ptp_cs; get_connection_data(L,1,¶ms,&ptp_cs);
// so is this
#define CHDK_ENSURE_CONNECTED if(!ptp_cs->connected) {push_api_error_ptp(L, PTP_ERROR_NOT_CONNECTED); return lua_error(L);}
/* we need it for a proper signal handling :/ */
// reyalp -not using signal handler for now, revisit later
#if 0
PTPParams* globalparams;
void
ptpcam_siginthandler(int signum)
{
PTP_CON_STATE* ptp_cs=(PTP_CON_STATE *)globalparams->data;
struct usb_device *dev=usb_device(ptp_cs->usb.handle);
if (signum==SIGINT)
{
/* hey it's not that easy though... but at least we can try! */
printf("Got SIGINT, trying to clean up and close...\n");
usleep(5000);
close_camera (ptp_cs, globalparams, dev);
exit (-1);
}
}
#endif
static int
ptp_usb_read_func (unsigned char *bytes, unsigned max_size, void *data)
{
int result=-1;
PTP_CON_STATE *ptp_cs=(PTP_CON_STATE *)data;
int toread=0;
signed long int rbytes=max_size;
int read_size = 0;
do {
bytes+=toread;
if (rbytes>PTPCAM_USB_URB)
toread = PTPCAM_USB_URB;
else
toread = rbytes;
//printf("read h:0x%p inep:0x%x b:0x%p c:%d to:%d\n",
// ptp_cs->usb.handle, ptp_cs->usb.inep,(char *)bytes, toread,ptp_cs->timeout);
result=USB_BULK_READ(ptp_cs->usb.handle, ptp_cs->usb.inep,(char *)bytes, toread,ptp_cs->timeout);
/* sometimes retry might help */
if (result==0) {
if(verbose) {
printf("read retry\n");
}
result=USB_BULK_READ(ptp_cs->usb.handle, ptp_cs->usb.inep,(char *)bytes, toread,ptp_cs->timeout);
}
if (result < 0)
break;
read_size += result;
ptp_cs->read_count += toread;
rbytes-=PTPCAM_USB_URB;
} while (rbytes>0);
//printf("read result=%d size=%d max=%d\n",result,read_size,max_size);
if (result >= 0) {
return read_size;
}
else
{
if (verbose) perror("usb_bulk_read");
return -1;
}
}
static short
ptp_usb_write_func (unsigned char *bytes, unsigned int size, void *data)
{
int result;
PTP_CON_STATE *ptp_cs=(PTP_CON_STATE *)data;
result=USB_BULK_WRITE(ptp_cs->usb.handle,ptp_cs->usb.outep,(char *)bytes,size,ptp_cs->timeout);
if (result >= 0) {
ptp_cs->write_count += size;
return (PTP_RC_OK);
} else {
if (verbose) perror("usb_bulk_write");
return PTP_ERROR_IO;
}
}
static int
ptp_usb_check_int (unsigned char *bytes, unsigned int size, void *data)
{
int result;
PTP_CON_STATE *ptp_cs=(PTP_CON_STATE *)data;
result=USB_BULK_READ(ptp_cs->usb.handle, ptp_cs->usb.intep,(char *)bytes,size,ptp_cs->timeout);
if (result==0)
result=USB_BULK_READ(ptp_cs->usb.handle, ptp_cs->usb.intep,(char *)bytes,size,ptp_cs->timeout);
if (verbose>2) fprintf (stderr, "USB_BULK_READ returned %i, size=%i\n", result, size);
if (result >= 0) {
return result;
} else {
if (verbose) perror("ptp_check_int");
return result;
}
}
void
ptpcam_debug (void *data, const char *format, va_list args);
void
ptpcam_debug (void *data, const char *format, va_list args)
{
if (verbose<2) return;
vfprintf (stderr, format, args);
fprintf (stderr,"\n");
fflush(stderr);
}
#ifdef CHDKPTP_PTPIP
static short
ptp_tcp_write_func (unsigned char *bytes, unsigned int size, void *data)
{
int result;
PTP_CON_STATE *ptp_cs=(PTP_CON_STATE *)data;
result = send( ptp_cs->tcp.cmd_sock, (char *)bytes, size, 0 );
if (result == SOCKET_ERROR) {
printf("send failed: %d %s\n", sockutil_errno(),sockutil_strerror(sockutil_errno()));
return PTP_ERROR_IO;
} else {
ptp_cs->write_count += size;
return (PTP_RC_OK);
}
}
// TODO this is all wrong, we might not get whole packet, or might get part of next
// need to restructure for a PTP/IP packet oriented read
static int
ptp_tcp_read_func (unsigned char *bytes, unsigned max_size, void *data)
{
PTP_CON_STATE *ptp_cs=(PTP_CON_STATE *)data;
int result = recv(ptp_cs->tcp.cmd_sock, (char *)bytes, max_size, 0);
if ( result > 0 ) {
//printf("read %d\n",result);
ptp_cs->read_count += result;
return result;
} else if ( result == 0 ) {
printf("Connection closed\n");
return -1;
} else {
printf("recv failed: %d %s\n", sockutil_errno(),sockutil_strerror(sockutil_errno()));
return -1;
}
}
// TODO
static int
ptp_tcp_check_int (unsigned char *bytes, unsigned int size, void *data)
{
return PTP_RC_OK;
}
// TODO should be specified in connection, in case it actually matters
// guid for connection request, must be 16 bytes, values don't seem to matter
char my_guid[] = {
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xde,0xad,0xbe,0xef,0x12,0x34,0x56,0x78
};
// friendly name (i.e windows network name), in utf16 value doesn't seem to matter
// according to draft spec, may be null (one 16 bit null)
char my_name[] = {
'w',0x00,'h',0x00,'e',0x00,'e',0x00,0x00,0x00
};
// TODO
static int init_event_channel_tcp(PTP_CON_STATE* ptp_cs) {
printf("initializing event channel\n");
// Create a socket for the command channel
socket_t sock = socket(ptp_cs->tcp.ai_con->ai_family, ptp_cs->tcp.ai_con->ai_socktype, ptp_cs->tcp.ai_con->ai_protocol);
if (sock == INVALID_SOCKET) {
printf("socket failed with error: %d %s\n", sockutil_errno(),sockutil_strerror(sockutil_errno()));
}
// Connect to camera
int r = connect( sock, ptp_cs->tcp.ai_con->ai_addr, (int)ptp_cs->tcp.ai_con->ai_addrlen);
if (r == SOCKET_ERROR) {
printf("connect failed with error: %d %s\n", sockutil_errno(),sockutil_strerror(sockutil_errno()));
return 0;
}
ptp_cs->tcp.event_sock = sock;
// TODO need to init channel before open session will work
PTPIPContainer pkt;
// todo should use htod*
pkt.type = PTPIP_TYPE_INIT_EVENT;
pkt.length = 12; // header + connection number
*(uint32_t *)(pkt.data) = ptp_cs->tcp.connection_id;
int result = send( ptp_cs->tcp.event_sock, (char *)&pkt, pkt.length, 0 );
if (result == SOCKET_ERROR) {
printf("send failed: %d %s\n", sockutil_errno(),sockutil_strerror(sockutil_errno()));
return 0;
}
memset(&pkt,0,sizeof(pkt));
r = recv(ptp_cs->tcp.event_sock, (char *)&pkt, sizeof(pkt), 0);
if ( r > 0 ) {
if( r >= 8) {
if(pkt.length != r) {
printf("size %d != %d\n",pkt.length,r);
return 0;
}
if(pkt.type != PTPIP_TYPE_INIT_EVENT_ACK) {
printf("unexpected type %d\n",pkt.type);
return 0;
}
} else {
printf("failed to read header %d\n",r);
return 0;
}
} else if ( r == 0 ) {
printf("connection closed\n");
return 0;
} else {
printf("recv failed with error: %d %s\n", sockutil_errno(),sockutil_strerror(sockutil_errno()));
return 0;
}
return 1;
}
int init_ptp_tcp(PTPParams* params, PTP_CON_STATE* ptp_cs) {
params->write_func=ptp_tcp_write_func;
params->read_func=ptp_tcp_read_func;
params->check_int_func=ptp_tcp_check_int;
params->check_int_fast_func=ptp_tcp_check_int;
params->read_control_func=ptp_tcp_read_control;
params->read_data_func=ptp_tcp_read_data;
params->debug_func=ptpcam_debug;
params->sendreq_func=ptp_tcp_sendreq;
params->senddata_func=ptp_tcp_senddata;
params->getresp_func=ptp_tcp_getresp;
params->getdata_func=ptp_tcp_getdata;
params->data=ptp_cs;
params->transaction_id=0;
params->byteorder = PTP_DL_LE;
params->pkt_buf.pos = params->pkt_buf.len = 0;
ptp_cs->write_count = ptp_cs->read_count = 0;
socket_t sock = INVALID_SOCKET;
struct addrinfo *result = NULL,
*ptr = NULL,
hints;
sockutil_startup();
memset( &hints, 0, sizeof(hints) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// resolve address and port
int r = getaddrinfo(ptp_cs->tcp.host, ptp_cs->tcp.port, &hints, &result);
if ( r != 0 ) {
printf("getaddrinfo failed: %d\n", r);
return 0;
}
// Attempt to connect to an address until one succeeds
for(ptr=result; ptr != NULL ;ptr=ptr->ai_next) {
// Create a socket for the command channel
sock = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
if (sock == INVALID_SOCKET) {
printf("socket failed: %d %s\n", sockutil_errno(),sockutil_strerror(sockutil_errno()));
freeaddrinfo(result);
return 0;
}
// Connect to camera
r = connect( sock, ptr->ai_addr, (int)ptr->ai_addrlen);
if (r == SOCKET_ERROR) {
sockutil_close(sock);
sock = INVALID_SOCKET;
continue;
}
break;
}
ptp_cs->tcp.ai = result;
ptp_cs->tcp.ai_con = ptr;
ptp_cs->tcp.cmd_sock = sock;
printf("initializing command channel\n");
PTPIPContainer pkt;
// TODO should use pack functons
pkt.type = PTPIP_TYPE_INIT_CMD;
pkt.length = sizeof(my_guid) + sizeof(my_name) + 12; // header + version
char *p = (char *)pkt.data;
memcpy(p,my_guid,sizeof(my_guid));
p+=sizeof(my_guid);
memcpy(p,my_name,sizeof(my_name));
p+=sizeof(my_name);
*(int *)p = 0x00010000; // version is after variable length name...
if(params->write_func((unsigned char *)&pkt,pkt.length,ptp_cs) != PTP_RC_OK) {
return 0;
}
memset(&pkt,0,sizeof(pkt));
if(params->read_func((unsigned char *)&pkt,sizeof(pkt),ptp_cs) < 0) {
return 0;
}
if(pkt.length < 34) { // header 8 + connection id 4 + guid 16 + version 4 + wchar null name
printf("response too small\n");
return 0;
}
// TODO should use unpack functons
if(pkt.type != PTPIP_TYPE_INIT_CMD_ACK) {
printf("not ack, aborting\n");
return 0;
}
p = (char *)&pkt;
ptp_cs->tcp.connection_id = *(uint32_t *)(p + 8);
memcpy(ptp_cs->tcp.cam_guid,p + 12,16);
// TODO name and version
if(!init_event_channel_tcp(ptp_cs)) {
return 0;
}
printf("opening session\n");
short ret = ptp_opensession(params,1);
if(ret!=PTP_RC_OK) {
printf("opensession failed 0x%x\n",ret);
return 0;
}
ptp_cs->connected = 1;
if (ptp_getdeviceinfo(params,¶ms->deviceinfo)!=PTP_RC_OK) {
printf("Could not get device info!\n");
return 0;
}
return 1;
}
#endif
int
init_ptp_usb (PTPParams* params, PTP_CON_STATE* ptp_cs, struct usb_device* dev)
{
usb_dev_handle *device_handle;
params->write_func=ptp_usb_write_func;
params->read_func=ptp_usb_read_func;
params->check_int_func=ptp_usb_check_int;
params->check_int_fast_func=ptp_usb_check_int;
params->read_control_func=ptp_usb_read_control;
params->read_data_func=ptp_usb_read_data;
params->debug_func=ptpcam_debug;
params->sendreq_func=ptp_usb_sendreq;
params->senddata_func=ptp_usb_senddata;
params->getresp_func=ptp_usb_getresp;
params->getdata_func=ptp_usb_getdata;
params->data=ptp_cs;
params->transaction_id=0;
params->byteorder = PTP_DL_LE;
params->pkt_buf.pos = params->pkt_buf.len = 0;
device_handle = usb_open(dev);
if (!device_handle) {
perror("usb_open()");
return 0;
}
ptp_cs->usb.handle=device_handle;
ptp_cs->write_count = ptp_cs->read_count = 0;
usb_set_configuration(device_handle, dev->config->bConfigurationValue);
// TODO should check status, -EBUSY!
usb_claim_interface(device_handle,
dev->config->interface->altsetting->bInterfaceNumber);
// Get max endpoint packet size for bulk transfer fix
params->max_packet_size = dev->config->interface->altsetting->endpoint->wMaxPacketSize;
// fprintf(stderr,"max endpoint size = %d\n",params->max_packet_size);
if (params->max_packet_size == 0) params->max_packet_size = 512; // safety net ?
return 1;
}
void
clear_stall(PTP_CON_STATE* ptp_cs)
{
uint16_t status=0;
int ret;
/* check the inep status */
ret=usb_get_endpoint_status(ptp_cs,ptp_cs->usb.inep,&status);
if (ret<0) perror ("inep: usb_get_endpoint_status()");
/* and clear the HALT condition if happend */
else if (status) {
printf("Resetting input pipe!\n");
ret=usb_clear_stall_feature(ptp_cs,ptp_cs->usb.inep);
/*usb_clear_halt(ptp_usb->handle,ptp_usb->inep); */
if (ret<0)perror ("usb_clear_stall_feature()");
}
status=0;
/* check the outep status */
ret=usb_get_endpoint_status(ptp_cs,ptp_cs->usb.outep,&status);
if (ret<0) perror ("outep: usb_get_endpoint_status()");
/* and clear the HALT condition if happend */
else if (status) {
printf("Resetting output pipe!\n");
ret=usb_clear_stall_feature(ptp_cs,ptp_cs->usb.outep);
/*usb_clear_halt(ptp_usb->handle,ptp_usb->outep); */
if (ret<0)perror ("usb_clear_stall_feature()");
}
/*usb_clear_halt(ptp_usb->handle,ptp_usb->intep); */
}
void
close_usb(PTP_CON_STATE* ptp_cs, struct usb_device* dev)
{
//clear_stall(ptp_cs);
usb_release_interface(ptp_cs->usb.handle, dev->config->interface->altsetting->bInterfaceNumber);
usb_reset(ptp_cs->usb.handle);
usb_close(ptp_cs->usb.handle);
}
struct usb_bus*
get_busses()
{
usb_find_busses();
usb_find_devices();
return (usb_get_busses());
}
void
find_endpoints(struct usb_device *dev, int* inep, int* outep, int* intep);
void
find_endpoints(struct usb_device *dev, int* inep, int* outep, int* intep)
{
int i,n;
struct usb_endpoint_descriptor *ep;
ep = dev->config->interface->altsetting->endpoint;
n=dev->config->interface->altsetting->bNumEndpoints;
for (i=0;i<n;i++) {
if (ep[i].bmAttributes==USB_ENDPOINT_TYPE_BULK) {
if ((ep[i].bEndpointAddress&USB_ENDPOINT_DIR_MASK)==USB_ENDPOINT_DIR_MASK)
{
*inep=ep[i].bEndpointAddress;
if (verbose>1)
fprintf(stderr, "Found inep: 0x%02x\n",*inep);
}
if ((ep[i].bEndpointAddress&USB_ENDPOINT_DIR_MASK)==0)
{
*outep=ep[i].bEndpointAddress;
if (verbose>1)
fprintf(stderr, "Found outep: 0x%02x\n",*outep);
}
} else if ((ep[i].bmAttributes==USB_ENDPOINT_TYPE_INTERRUPT) &&
((ep[i].bEndpointAddress&USB_ENDPOINT_DIR_MASK)==
USB_ENDPOINT_DIR_MASK))
{
*intep=ep[i].bEndpointAddress;
if (verbose>1)
fprintf(stderr, "Found intep: 0x%02x\n",*intep);
}
}
}
void close_camera_usb(PTP_CON_STATE *ptp_cs, PTPParams *params) {
// usb_device(handle) appears to give bogus results when the device has gone away
// TODO possible a different device could come back on this bus/dev ?
struct usb_device *dev=find_device_by_path(ptp_cs->usb.bus,ptp_cs->usb.dev);
if(!dev) {
fprintf(stderr,"attempted to close non-present device %s:%s\n",ptp_cs->usb.bus,ptp_cs->usb.dev);
return;
}
if (ptp_closesession(params)!=PTP_RC_OK)
fprintf(stderr,"ERROR: Could not close session!\n");
close_usb(ptp_cs, dev);
}
void close_camera_tcp(PTP_CON_STATE *ptp_cs, PTPParams *params) {
#ifdef CHDKPTP_PTPIP
if(ptp_cs->connected) {
if (ptp_closesession(params)!=PTP_RC_OK) {
fprintf(stderr,"ERROR: Could not close session!\n");
}
}
if( ptp_cs->tcp.cmd_sock != INVALID_SOCKET) {
sockutil_close(ptp_cs->tcp.cmd_sock);
ptp_cs->tcp.cmd_sock = INVALID_SOCKET;
}
if( ptp_cs->tcp.event_sock != INVALID_SOCKET) {
sockutil_close(ptp_cs->tcp.event_sock);
ptp_cs->tcp.event_sock = INVALID_SOCKET;
}
if(ptp_cs->tcp.ai) {
freeaddrinfo(ptp_cs->tcp.ai);
ptp_cs->tcp.ai = ptp_cs->tcp.ai_con = NULL;
}
#endif
return;
}
void
close_camera(PTP_CON_STATE *ptp_cs, PTPParams *params)
{
if(ptp_cs->con_type == PTP_CON_USB) {
close_camera_usb(ptp_cs,params);
} else {
close_camera_tcp(ptp_cs,params);
}
}
int
usb_get_endpoint_status(PTP_CON_STATE* ptp_cs, int ep, uint16_t* status)
{
return (usb_control_msg(ptp_cs->usb.handle,
USB_DP_DTH|USB_RECIP_ENDPOINT, USB_REQ_GET_STATUS,
USB_FEATURE_HALT, ep, (char *)status, 2, 3000));
}
int
usb_clear_stall_feature(PTP_CON_STATE* ptp_cs, int ep)
{
return (usb_control_msg(ptp_cs->usb.handle,
USB_RECIP_ENDPOINT, USB_REQ_CLEAR_FEATURE, USB_FEATURE_HALT,
ep, NULL, 0, 3000));
}
int
usb_ptp_get_device_status(PTP_CON_STATE* ptp_cs, uint16_t* devstatus);
int
usb_ptp_get_device_status(PTP_CON_STATE* ptp_cs, uint16_t* devstatus)
{
return (usb_control_msg(ptp_cs->usb.handle,
USB_DP_DTH|USB_TYPE_CLASS|USB_RECIP_INTERFACE,
USB_REQ_GET_DEVICE_STATUS, 0, 0,
(char *)devstatus, 4, 3000));
}
int
usb_ptp_device_reset(PTP_CON_STATE* ptp_cs);
int
usb_ptp_device_reset(PTP_CON_STATE* ptp_cs)
{
return (usb_control_msg(ptp_cs->usb.handle,
USB_TYPE_CLASS|USB_RECIP_INTERFACE,
USB_REQ_DEVICE_RESET, 0, 0, NULL, 0, 3000));
}
void
reset_device (struct usb_device *dev);
void
reset_device (struct usb_device *dev)
{
PTPParams params;
PTP_CON_STATE ptp_cs;
uint16_t status;
uint16_t devstatus[2] = {0,0};
int ret;
printf("reset_device: ");
if (dev==NULL) {
printf("null dev\n");
return;
}
printf("dev %s\tbus %s\n",dev->filename,dev->bus->dirname);
find_endpoints(dev,&ptp_cs.usb.inep,&ptp_cs.usb.outep,&ptp_cs.usb.intep);
if(!init_ptp_usb(¶ms, &ptp_cs, dev)) {
printf("init_ptp_usb failed\n");
return;
}
/* get device status (devices likes that regardless of its result)*/
usb_ptp_get_device_status(&ptp_cs,devstatus);
/* check the in endpoint status*/
ret = usb_get_endpoint_status(&ptp_cs,ptp_cs.usb.inep,&status);
if (ret<0) perror ("usb_get_endpoint_status()");
/* and clear the HALT condition if happend*/
if (status) {
printf("Resetting input pipe!\n");
ret=usb_clear_stall_feature(&ptp_cs,ptp_cs.usb.inep);
if (ret<0)perror ("usb_clear_stall_feature()");
}
status=0;
/* check the out endpoint status*/
ret = usb_get_endpoint_status(&ptp_cs,ptp_cs.usb.outep,&status);
if (ret<0) perror ("usb_get_endpoint_status()");
/* and clear the HALT condition if happend*/
if (status) {
printf("Resetting output pipe!\n");
ret=usb_clear_stall_feature(&ptp_cs,ptp_cs.usb.outep);
if (ret<0)perror ("usb_clear_stall_feature()");
}
status=0;
/* check the interrupt endpoint status*/
ret = usb_get_endpoint_status(&ptp_cs,ptp_cs.usb.intep,&status);
if (ret<0)perror ("usb_get_endpoint_status()");
/* and clear the HALT condition if happend*/
if (status) {
printf ("Resetting interrupt pipe!\n");
ret=usb_clear_stall_feature(&ptp_cs,ptp_cs.usb.intep);
if (ret<0)perror ("usb_clear_stall_feature()");
}
/* get device status (now there should be some results)*/
ret = usb_ptp_get_device_status(&ptp_cs,devstatus);
if (ret<0)
perror ("usb_ptp_get_device_status()");
else {
if (devstatus[1]==PTP_RC_OK)
printf ("Device status OK\n");
else
printf ("Device status 0x%04x\n",devstatus[1]);
}
/* finally reset the device (that clears prevoiusly opened sessions)*/
ret = usb_ptp_device_reset(&ptp_cs);
if (ret<0)perror ("usb_ptp_device_reset()");
/* get device status (devices likes that regardless of its result)*/
usb_ptp_get_device_status(&ptp_cs,devstatus);
close_usb(&ptp_cs, dev);
}
//----------------------------
/*
get pointers out of user data in given arg
*/
static void get_connection_data(lua_State *L,int narg, PTPParams **params,PTP_CON_STATE **ptp_cs) {
*params = (PTPParams *)luaL_checkudata(L,narg,CHDK_CONNECTION_META);
*ptp_cs = (PTP_CON_STATE *)((*params)->data);
}
static void close_connection(PTPParams *params,PTP_CON_STATE *ptp_cs)
{
if(ptp_cs->connected) {
close_camera(ptp_cs,params);
}
ptp_cs->connected = 0;
}
static int check_connection_status_usb(PTP_CON_STATE *ptp_cs) {
uint16_t devstatus[2] = {0,0};
// TODO shouldn't ever be true
if(!ptp_cs->connected) {// never initialized
return 0;
}
if(usb_ptp_get_device_status(ptp_cs,devstatus) < 0) {
return 0;
}
return (devstatus[1] == 0x2001);
}
// TODO
static int check_connection_status_tcp(PTP_CON_STATE *ptp_cs) {
return 1;
}
/*
get dev and bus from table arg
return 1 on success, 0 on failure leaving rbus and rdev unchanged
*/
static int get_lua_devspec_usb(lua_State *L, int index, const char **rbus, const char **rdev) {
const char *bus;
const char *dev;
if(!lua_istable(L,index)) {
return 0;
}
lua_getfield(L,index,"dev");
dev = lua_tostring(L,-1);
lua_pop(L,1);
lua_getfield(L,index,"bus");
bus = lua_tostring(L,-1);
lua_pop(L,1);
if(!dev || !bus) {
return 0;
}
*rdev = dev;
*rbus = bus;
return 1;
}
/*
get the connection user data specified by connection_list key and push it on the stack
if nothing is found, returns 0 and pushes nothing
*/
int get_connection_list_udata(lua_State *L, const char *key) {
if(!key) {
return 0;
}
lua_getfield(L,LUA_REGISTRYINDEX,CHDK_CONNECTION_LIST);
lua_getfield(L,-1,key);
// TODO could check meta table
if(lua_isuserdata(L,-1)) {
lua_replace(L, -2); // move udata up to connection list
return 1;
} else {
lua_pop(L, 2); // nil, connection list
return 0;
}
}
struct usb_device *find_device_by_path(const char *find_bus, const char *find_dev) {
struct usb_bus *bus;
struct usb_device *dev;
bus=get_busses();
for (; bus; bus = bus->next) {
if(strcmp(find_bus,bus->dirname) != 0) {
continue;
}
for (dev = bus->devices; dev; dev = dev->next) {
if (dev->config) {
if ((dev->config->interface->altsetting->bInterfaceClass==USB_CLASS_PTP)) {
if(strcmp(find_dev,dev->filename) == 0) {
return dev;
}
}
}
}
}
return NULL;
}
int open_camera_dev_usb(struct usb_device *dev, PTP_CON_STATE *ptp_cs, PTPParams *params)
{
uint16_t devstatus[2] = {0,0};
int ret;
if(!dev) {
printf("open_camera_dev_usb: NULL dev\n");
return 0;
}
find_endpoints(dev,&ptp_cs->usb.inep,&ptp_cs->usb.outep,&ptp_cs->usb.intep);
if(!init_ptp_usb(params, ptp_cs, dev)) {
printf("open_camera_dev_usb: init_ptp_usb 1 failed\n");
return 0;
}
ret = ptp_opensession(params,1);
if(ret!=PTP_RC_OK) {
// TODO temp debug - this appears to be needed on linux if other stuff grabbed the dev
printf("open_camera_dev_usb: ptp_opensession failed 0x%x\n",ret);
ret = usb_ptp_device_reset(ptp_cs);
if (ret<0)perror ("open_camera_dev_usb:usb_ptp_device_reset()");
/* get device status (devices likes that regardless of its result)*/
ret = usb_ptp_get_device_status(ptp_cs,devstatus);
if (ret<0)
perror ("usb_ptp_get_device_status()");
else {
if (devstatus[1]==PTP_RC_OK)
printf ("Device status OK\n");
else
printf ("Device status 0x%04x\n",devstatus[1]);
}
close_usb(ptp_cs, dev);
find_endpoints(dev,&ptp_cs->usb.inep,&ptp_cs->usb.outep,&ptp_cs->usb.intep);
if(!init_ptp_usb(params, ptp_cs, dev)) {
printf("open_camera_dev_usb: init_ptp_usb 2 failed\n");
return 0;
}
ret=ptp_opensession(params,1);
if(ret!=PTP_RC_OK) {
printf("open_camera_dev_usb: ptp_opensession 2 failed: 0x%x\n",ret);
return 0;
}
}
if (ptp_getdeviceinfo(params,¶ms->deviceinfo)!=PTP_RC_OK) {
// TODO do we want to close here ?
printf("Could not get device info!\n");
close_camera(ptp_cs, params);
return 0;
}
// TODO we could check camera CHDK, API version, etc here
ptp_cs->connected = 1;
return 1;
}
/*
tostring metamethod for errors
*/
static int api_error_tostring(lua_State *L) {
if(!lua_istable(L,1)) {
return luaL_error(L,"expected table");
}
lua_getfield(L,1,"msg");
if(lua_isnil(L,-1)) {
lua_pop(L,1);
// if etype is available, use that
lua_getfield(L,1,"etype");
if(lua_isnil(L,-1)) {
lua_pop(L,1);
lua_pushstring(L,"unknown error");
}
}
return 1;
}
/*
push a new error object
*/
static int push_api_error(lua_State *L) {
lua_newtable(L);
luaL_getmetatable(L, CHDK_API_ERROR_META);
lua_setmetatable(L, -2);
return 1;
}
/*
set stacktrace as field in error object
allows catching and re-throwing with correct stack
assumes stack top is error table, leaves it there
*/
static void api_error_traceback(lua_State *L, int level) {
// borrowed from iuplua.c
lua_getglobal(L, "debug");
if (!lua_istable(L, -1)) {
lua_pop(L, 1);
return;