summaryrefslogtreecommitdiffstats
path: root/tools/iap/Device/iPod.pm
blob: b2d686cce76c526fb6826d2ff27c13ca2b253c2e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
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
package Device::iPod;

use Device::SerialPort;
use POSIX qw(isgraph);
use strict;

sub new {
    my $class = shift;
    my $port = shift;
    my $self = {};
    my $s;

    $self->{-serial} = undef;
    $self->{-inbuf} = '';
    $self->{-error} = undef;
    $self->{-baudrate} = 57600;
    $self->{-debug} = 0;

    return bless($self, $class);
}

sub open {
    my $self = shift;
    my $port = shift;

    $self->{-serial} = new Device::SerialPort($port);
    unless(defined($self->{-serial})) {
        $self->{-error} = $!;
        return undef;
    }

    $self->{-serial}->parity('none');
    $self->{-serial}->databits(8);
    $self->{-serial}->stopbits(1);
    $self->{-serial}->handshake('none');
    return $self->baudrate($self->{-baudrate});
}

sub baudrate {
    my $self = shift;
    my $baudrate = shift;

    if ($baudrate < 1) {
        $self->{-error} = "Invalid baudrate";
        return undef;
    }

    $self->{-baudrate} = $baudrate;
    if (defined($self->{-serial})) {
        $self->{-serial}->baudrate($baudrate);
    }

    return 1;
}

sub sendmsg {
    my $self = shift;
    my $lingo = shift;
    my $command = shift;
    my $data = shift || '';

    return $self->_nosetup() unless(defined($self->{-serial}));

    if (($lingo < 0) || ($lingo > 255)) {
        $self->{-error} = 'Invalid lingo';
        return undef;
    }

    if ($command < 0) {
        $self->{-error} = 'Invalid command';
        return undef;
    }

    if ($lingo == 4) {
        if ($command > 0xffff) {
            $self->{-error} = 'Invalid command';
            return undef;
        }
        return $self->_send($self->_frame_cmd(pack("Cn", $lingo, $command) . $data));
    } else {
        if ($command > 0xff) {
            $self->{-error} = 'Invalid command';
            return undef;
        }
        return $self->_send($self->_frame_cmd(pack("CC", $lingo, $command) . $data));
    }
}

sub sendraw {
    my $self = shift;
    my $data = shift;

    return $self->_nosetup() unless(defined($self->{-serial}));

    return $self->_send($data);
}

sub recvmsg {
    my $self = shift;
    my $m;
    my @m;

    return $self->_nosetup() unless(defined($self->{-serial}));

    $m = $self->_fillbuf();
    unless(defined($m)) {
        # Error was set by lower levels
        return wantarray?():undef;
    }

    printf("Fetched %s\n", $self->_hexstring($m)) if $self->{-debug};

    @m = $self->_unframe_cmd($m);

    unless(@m) {
        return undef;
    }

    if (wantarray()) {
        return @m;
    } else {
        return {-lingo => $m[0], -cmd => $m[1], -payload => $m[2]};
    }
}

sub emptyrecv {
    my $self = shift;
    my $m;

    while ($m = $self->_fillbuf()) {
        printf("Discarded %s\n", $self->_hexstring($m)) if (defined($m) && $self->{-debug});
    }
}

sub error {
    my $self = shift;

    return $self->{-error};
}

sub _nosetup {
    my $self = shift;

    $self->{-error} = 'Serial port not setup';
    return undef;
}

sub _frame_cmd {
    my $self = shift;
    my $data = shift;
    my $l = length($data);
    my $csum;

    if ($l > 0xffff) {
        $self->{-error} = 'Command too long';
        return undef;
    }

    if ($l > 255) {
        $data = pack("Cn", 0, length($data)) . $data;
    } else {
        $data = pack("C", length($data)) . $data;
    }

    foreach (unpack("C" x length($data), $data)) {
        $csum += $_;
    }
    $csum &= 0xFF;
    $csum = 0x100 - $csum;

    return "\xFF\x55" . $data . pack("C", $csum);
}

sub _unframe_cmd {
    my $self = shift;
    my $data = shift;
    my $payload = '';
    my ($count, $length, $csum);
    my $state = 0;
    my $c;
    my ($lingo, $cmd);

    return () unless(defined($data));

    foreach $c (unpack("C" x length($data), $data)) {
        if ($state == 0) {
            # Wait for sync
            next unless($c == 255);
            $state = 1;
        } elsif ($state == 1) {
            # Wait for sop
            next unless($c == 85);
            $state = 2;
        } elsif ($state == 2) {
            # Length (short frame)
            $csum = $c;
            if ($c == 0) {
                # Large frame
                $state = 3;
            } else {
                $state = 5;
            }
            $length = $c;
            $count = 0;
            next;
        } elsif ($state == 3) {
            # Large frame, hi
            $csum += $c;
            $length = ($c << 8);
            $state = 4;
            next;
        } elsif ($state == 4) {
            # Large frame, lo
            $csum += $c;
            $length |= $c;
            if ($length == 0) {
                $self->{-error} = 'Length is 0';
                return ();
            }
            $state = 5;
            next;
        } elsif ($state == 5) {
            # Data bytes
            $csum += $c;
            $payload .= chr($c);
            $count += 1;
            if ($count == $length) {
                $state = 6;
            }
        } elsif ($state == 6) {
            # Checksum byte
            $csum += $c;
            if (($csum & 0xFF) != 0) {
                $self->{-error} = 'Invalid checksum';
                return ();
            }
            $state = 7;
            last;
        } else {
            $self->{-error} = 'Invalid state';
            return ();
        }
    }

    # If we get here, we either have data or not. Check.
    if ($state != 7) {
        $self->{-error} = 'Could not unframe data';
        return ();
    }

    $lingo = unpack("C", $payload);
    if ($lingo == 4) {
        return unpack("Cna*", $payload);
    } else {
        return unpack("CCa*", $payload);
    }
}

sub _send {
    my $self = shift;
    my $data = shift;
    my $l = length($data);
    my $c;

    printf("Sending %s\n", $self->_hexstring($data)) if $self->{-debug};

    $c = $self->{-serial}->write($data);
    unless(defined($c)) {
        $self->{-error} = 'write failed';
        return undef;
    }

    if ($c != $l) {
        $self->{-error} = 'incomplete write';
        return undef;
    }

    return 1;
}

sub _fillbuf {
    my $self = shift;
    my $timeout = shift || 2;
    my $to;

    # Read from the port until we have a complete message in the buffer,
    # or until we haven't read any new data for $timeout seconds, whatever
    # comes first.

    $to = $timeout;

    while(!$self->_message_in_buffer() && $to > 0) {
        my ($c, $s) = $self->{-serial}->read(255);
        if ($c == 0) {
            # No data read
            select(undef, undef, undef, 0.1);
            $to -= 0.1;
        } else {
            $self->{-inbuf} .= $s;
            $to = $timeout;
        }
    }
    if ($self->_message_in_buffer()) {
        # There is a complete message in the buffer
        return $self->_message();
    } else {
        # Timeout occured
        $self->{-error} = 'Timeout reading from port';
        return undef;
    }
}

sub _message_in_buffer {
    my $self = shift;
    my $sp = 0;
    my $i;

    $i = index($self->{-inbuf}, "\xFF\x55", $sp);
    while ($i != -1) {
        my $header;
        my $len;
        my $large = 0;


        $header = substr($self->{-inbuf}, $i, 3);
        if (length($header) != 3) {
            # Runt frame
            return ();
        }
        $len = unpack("x2C", $header);
        if ($len == 0) {
            # Possible large frame
            $header = substr($self->{-inbuf}, $i, 5);
            if (length($header) != 5) {
                # Runt frame
                return ();
            }
            $large = 1;
            $len = unpack("x3n", $header);
        }

        # Add framing, checksum and length
        $len = $len+3+($large?3:1);

        if (length($self->{-inbuf}) < ($i+$len)) {
            # Buffer too short to hold rest of frame. Try again.
            $sp = $i+1;
            $i = index($self->{-inbuf}, "\xFF\x55", $sp);
        } else {
            return ($i, $len);
        }
    }

    # No complete message found
    return ();
}


sub _message {
    my $self = shift;
    my $start;
    my $len;
    my $m;

    # Return the first complete message in the buffer, removing the message
    # and everything before it from the buffer.
    ($start, $len) = $self->_message_in_buffer();
    unless(defined($start)) {
        $self->{-error} = 'No complete message in buffer';
        return undef;
    }
    $m = substr($self->{-inbuf}, $start, $len);
    $self->{-inbuf} = substr($self->{-inbuf}, $start+$len);

    return $m;
}

sub _hexstring {
    my $self = shift;
    my $s = shift;

    return join("", map { (($_ == 0x20) || isgraph(chr($_)))?chr($_):sprintf("\\x%02x", $_) }
            unpack("C" x length($s), $s));
}

1;