Created
October 13, 2013 22:02
-
-
Save briansorahan/6967891 to your computer and use it in GitHub Desktop.
Read a MIDI SDS data packet
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static int | |
read_packet(midi_t midi, | |
unsigned char *buf, | |
unsigned int channel_num, | |
unsigned int modded_packet_num, | |
err_t err) { | |
const int checksum_byte = 125; | |
const time_t timeout_sec = 1; | |
int raw_bytes_read, bytes_read; | |
char strbuf[500]; strbuf[0] = '\0'; | |
unsigned char c; | |
unsigned char checksum; | |
start: | |
raw_bytes_read = bytes_read = 0; | |
printf("Reading Packet %d\n", modded_packet_num); | |
time_t start_time, now; | |
start_time = time(NULL); | |
while (bytes_read < SDS_PACKET_LENGTH) { | |
now = time(NULL); | |
if (now - start_time > timeout_sec) { | |
printf("Done!\n"); | |
exit(0); | |
} | |
if (! midi_read(midi, &c)) { | |
err_set2(err, "Could not read midi."); | |
return 0; | |
} else { | |
raw_bytes_read++; | |
} | |
switch(bytes_read) { | |
case 0: | |
if (c == 0xf0) { | |
buf[bytes_read++] = c; | |
} | |
break; | |
case 1: | |
if (c == 0x7e) { | |
checksum = c; | |
buf[bytes_read++] = c; | |
} | |
break; | |
case 2: | |
if (c == channel_num) { | |
checksum ^= c; | |
buf[bytes_read++] = c; | |
} | |
break; | |
case 3: | |
if (c == 0x02) { | |
checksum ^= c; | |
buf[bytes_read++] = c; | |
} | |
break; | |
case 4: | |
if (c == modded_packet_num) { | |
checksum ^= c; | |
buf[bytes_read++] = c; | |
} | |
break; | |
case 125: | |
buf[bytes_read++] = c; | |
break; | |
case 126: | |
if (c == 0xf7) { | |
buf[bytes_read++] = c; | |
checksum &= 0x7f; | |
if (checksum != buf[checksum_byte]) { | |
fprintf(stderr, "Calculated checksum = %02X. Actual checksum = %02X.\n", | |
checksum, buf[checksum_byte]); | |
if (send_response(midi, channel_num, modded_packet_num, RESPONSE_NAK, err)) { | |
// attempt to re-read sample | |
printf("Sent NAK...\n"); | |
goto start; | |
} | |
} | |
} | |
break; | |
default: | |
checksum ^= c; | |
buf[bytes_read++] = c; | |
break; | |
} | |
} | |
sds_serialize_packet(strbuf, buf, bytes_read); | |
printf("Total bytes read = %d\n", bytes_read); | |
printf("Received Packet %s\n", strbuf); | |
return bytes_read; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment