aboutsummaryrefslogtreecommitdiffstats
path: root/lib/lufa/Demos/Device/ClassDriver/MIDI/MIDI.c
blob: d52542234a5521db73e6a42fe8d77e47b5e91c98 (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
/*
             LUFA Library
     Copyright (C) Dean Camera, 2017.

  dean [at] fourwalledcubicle [dot] com
           www.lufa-lib.org
*/

/*
  Copyright 2017  Dean Camera (dean [at] fourwalledcubicle [dot] com)

  Permission to use, copy, modify, distribute, and sell this
  software and its documentation for any purpose is hereby granted
  without fee, provided that the above copyright notice appear in
  all copies and that both that the copyright notice and this
  permission notice and warranty disclaimer appear in supporting
  documentation, and that the name of the author not be used in
  advertising or publicity pertaining to distribution of the
  software without specific, written prior permission.

  The author disclaims all warranties with regard to this
  software, including all implied warranties of merchantability
  and fitness.  In no event shall the author be liable for any
  special, indirect or consequential damages or any damages
  whatsoever resulting from loss of use, data or profits, whether
  in an action of contract, negligence or other tortious action,
  arising out of or in connection with the use or performance of
  this software.
*/

/** \file
 *
 *  Main source file for the MIDI demo. This file contains the main tasks of
 *  the demo and is responsible for the initial application hardware configuration.
 */

#include "MIDI.h"

/** LUFA MIDI Class driver interface configuration and state information. This structure is
 *  passed to all MIDI Class driver functions, so that multiple instances of the same class
 *  within a device can be differentiated from one another.
 */
USB_ClassInfo_MIDI_Device_t Keyboard_MIDI_Interface =
	{
		.Config =
			{
				.StreamingInterfaceNumber = INTERFACE_ID_AudioStream,
				.DataINEndpoint           =
					{
						.Address          = MIDI_STREAM_IN_EPADDR,
						.Size             = MIDI_STREAM_EPSIZE,
						.Banks            = 1,
					},
				.DataOUTEndpoint          =
					{
						.Address          = MIDI_STREAM_OUT_EPADDR,
						.Size             = MIDI_STREAM_EPSIZE,
						.Banks            = 1,
					},
			},
	};


/** Main program entry point. This routine contains the overall program flow, including initial
 *  setup of all components and the main program loop.
 */
int main(void)
{
	SetupHardware();

	LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
	GlobalInterruptEnable();

	for (;;)
	{
		CheckJoystickMovement();

		MIDI_EventPacket_t ReceivedMIDIEvent;
		while (MIDI_Device_ReceiveEventPacket(&Keyboard_MIDI_Interface, &ReceivedMIDIEvent))
		{
			if ((ReceivedMIDIEvent.Event == MIDI_EVENT(0, MIDI_COMMAND_NOTE_ON)) && (ReceivedMIDIEvent.Data3 > 0))
			  LEDs_SetAllLEDs(ReceivedMIDIEvent.Data2 > 64 ? LEDS_LED1 : LEDS_LED2);
			else
			  LEDs_SetAllLEDs(LEDS_NO_LEDS);
		}

		MIDI_Device_USBTask(&Keyboard_MIDI_Interface);
		USB_USBTask();
	}
}

/** Configures the board hardware and chip peripherals for the demo's functionality. */
void SetupHardware(void)
{
#if (ARCH == ARCH_AVR8)
	/* Disable watchdog if enabled by bootloader/fuses */
	MCUSR &= ~(1 << WDRF);
	wdt_disable();

	/* Disable clock division */
	clock_prescale_set(clock_div_1);
#elif (ARCH == ARCH_XMEGA)
	/* Start the PLL to multiply the 2MHz RC oscillator to 32MHz and switch the CPU core to run from it */
	XMEGACLK_StartPLL(CLOCK_SRC_INT_RC2MHZ, 2000000, F_CPU);
	XMEGACLK_SetCPUClockSource(CLOCK_SRC_PLL);

	/* Start the 32MHz internal RC oscillator and start the DFLL to increase it to 48MHz using the USB SOF as a reference */
	XMEGACLK_StartInternalOscillator(CLOCK_SRC_INT_RC32MHZ);
	XMEGACLK_StartDFLL(CLOCK_SRC_INT_RC32MHZ, DFLL_REF_INT_USBSOF, F_USB);

	PMIC.CTRL = PMIC_LOLVLEN_bm | PMIC_MEDLVLEN_bm | PMIC_HILVLEN_bm;
#endif

	/* Hardware Initialization */
	Joystick_Init();
	LEDs_Init();
	Buttons_Init();
	USB_Init();
}

/** Checks for changes in the position of the board joystick, sending MIDI events to the host upon each change. */
void CheckJoystickMovement(void)
{
	static uint8_t PrevJoystickStatus;

	uint8_t MIDICommand = 0;
	uint8_t MIDIPitch;

	/* Get current joystick mask, XOR with previous to detect joystick changes */
	uint8_t JoystickStatus  = Joystick_GetStatus();
	uint8_t JoystickChanges = (JoystickStatus ^ PrevJoystickStatus);

	/* Get board button status - if pressed use channel 10 (percussion), otherwise use channel 1 */
	uint8_t Channel = ((Buttons_GetStatus() & BUTTONS_BUTTON1) ? MIDI_CHANNEL(10) : MIDI_CHANNEL(1));

	if (JoystickChanges & JOY_LEFT)
	{
		MIDICommand = ((JoystickStatus & JOY_LEFT)? MIDI_COMMAND_NOTE_ON : MIDI_COMMAND_NOTE_OFF);
		MIDIPitch   = 0x3C;
	}

	if (JoystickChanges & JOY_UP)
	{
		MIDICommand = ((JoystickStatus & JOY_UP)? MIDI_COMMAND_NOTE_ON : MIDI_COMMAND_NOTE_OFF);
		MIDIPitch   = 0x3D;
	}

	if (JoystickChanges & JOY_RIGHT)
	{
		MIDICommand = ((JoystickStatus & JOY_RIGHT)? MIDI_COMMAND_NOTE_ON : MIDI_COMMAND_NOTE_OFF);
		MIDIPitch   = 0x3E;
	}

	if (JoystickChanges & JOY_DOWN)
	{
		MIDICommand = ((JoystickStatus & JOY_DOWN)? MIDI_COMMAND_NOTE_ON : MIDI_COMMAND_NOTE_OFF);
		MIDIPitch   = 0x3F;
	}

	if (JoystickChanges & JOY_PRESS)
	{
		MIDICommand = ((JoystickStatus & JOY_PRESS)? MIDI_COMMAND_NOTE_ON : MIDI_COMMAND_NOTE_OFF);
		MIDIPitch   = 0x3B;
	}

	if (MIDICommand)
	{
		MIDI_EventPacket_t MIDIEvent = (MIDI_EventPacket_t)
			{
				.Event       = MIDI_EVENT(0, MIDICommand),

				.Data1       = MIDICommand | Channel,
				.Data2       = MIDIPitch,
				.Data3       = MIDI_STANDARD_VELOCITY,
			};

		MIDI_Device_SendEventPacket(&Keyboard_MIDI_Interface, &MIDIEvent);
		MIDI_Device_Flush(&Keyboard_MIDI_Interface);
	}

	PrevJoystickStatus = JoystickStatus;
}

/** Event handler for the library USB Connection event. */
void EVENT_USB_Device_Connect(void)
{
	LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
}

/** Event handler for the library USB Disconnection event. */
void EVENT_USB_Device_Disconnect(void)
{
	LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
}

/** Event handler for the library USB Configuration Changed event. */
void EVENT_USB_Device_ConfigurationChanged(void)
{
	bool ConfigSuccess = true;

	ConfigSuccess &= MIDI_Device_ConfigureEndpoints(&Keyboard_MIDI_Interface);

	LEDs_SetAllLEDs(ConfigSuccess ? LEDMASK_USB_READY : LEDMASK_USB_ERROR);
}

/** Event handler for the library USB Control Request reception event. */
void EVENT_USB_Device_ControlRequest(void)
{
	MIDI_Device_ProcessControlRequest(&Keyboard_MIDI_Interface);
}
="cpf"><stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include <sys/socket.h> #include "include/ebtables_u.h" extern char* hooknames[NF_BR_NUMHOOKS]; #ifdef KERNEL_64_USERSPACE_32 #define sparc_cast (uint64_t) #else #define sparc_cast #endif int sockfd = -1; static int get_sockfd(void) { int ret = 0; if (sockfd == -1) { sockfd = socket(AF_INET, SOCK_RAW, PF_INET); if (sockfd < 0) { ebt_print_error("Problem getting a socket, " "you probably don't have the right " "permissions"); ret = -1; } } return ret; } static struct ebt_replace *translate_user2kernel(struct ebt_u_replace *u_repl) { struct ebt_replace *new; struct ebt_u_entry *e; struct ebt_u_match_list *m_l; struct ebt_u_watcher_list *w_l; struct ebt_u_entries *entries; char *p, *base; int i, j; unsigned int entries_size = 0, *chain_offsets; new = (struct ebt_replace *)malloc(sizeof(struct ebt_replace)); if (!new) ebt_print_memory(); new->valid_hooks = u_repl->valid_hooks; strcpy(new->name, u_repl->name); new->nentries = u_repl->nentries; new->num_counters = u_repl->num_counters; new->counters = sparc_cast u_repl->counters; chain_offsets = (unsigned int *)malloc(u_repl->num_chains * sizeof(unsigned int)); /* Determine size */ for (i = 0; i < u_repl->num_chains; i++) { if (!(entries = u_repl->chains[i])) continue; chain_offsets[i] = entries_size; entries_size += sizeof(struct ebt_entries); j = 0; e = entries->entries->next; while (e != entries->entries) { j++; entries_size += sizeof(struct ebt_entry); m_l = e->m_list; while (m_l) { entries_size += m_l->m->match_size + sizeof(struct ebt_entry_match); m_l = m_l->next; } w_l = e->w_list; while (w_l) { entries_size += w_l->w->watcher_size + sizeof(struct ebt_entry_watcher); w_l = w_l->next; } entries_size += e->t->target_size + sizeof(struct ebt_entry_target); e = e->next; } /* A little sanity check */ if (j != entries->nentries) ebt_print_bug("Wrong nentries: %d != %d, hook = %s", j, entries->nentries, entries->name); } new->entries_size = entries_size; p = (char *)malloc(entries_size); if (!p) ebt_print_memory(); /* Put everything in one block */ new->entries = sparc_cast p; for (i = 0; i < u_repl->num_chains; i++) { struct ebt_entries *hlp; hlp = (struct ebt_entries *)p; if (!(entries = u_repl->chains[i])) continue; if (i < NF_BR_NUMHOOKS) new->hook_entry[i] = sparc_cast hlp; hlp->nentries = entries->nentries; hlp->policy = entries->policy; strcpy(hlp->name, entries->name); hlp->counter_offset = entries->counter_offset; hlp->distinguisher = 0; /* Make the kernel see the light */ p += sizeof(struct ebt_entries); e = entries->entries->next; while (e != entries->entries) { struct ebt_entry *tmp = (struct ebt_entry *)p; tmp->bitmask = e->bitmask | EBT_ENTRY_OR_ENTRIES; tmp->invflags = e->invflags; tmp->ethproto = e->ethproto; strcpy(tmp->in, e->in); strcpy(tmp->out, e->out); strcpy(tmp->logical_in, e->logical_in); strcpy(tmp->logical_out, e->logical_out); memcpy(tmp->sourcemac, e->sourcemac, sizeof(tmp->sourcemac)); memcpy(tmp->sourcemsk, e->sourcemsk, sizeof(tmp->sourcemsk)); memcpy(tmp->destmac, e->destmac, sizeof(tmp->destmac)); memcpy(tmp->destmsk, e->destmsk, sizeof(tmp->destmsk)); base = p; p += sizeof(struct ebt_entry); m_l = e->m_list; while (m_l) { memcpy(p, m_l->m, m_l->m->match_size + sizeof(struct ebt_entry_match)); p += m_l->m->match_size + sizeof(struct ebt_entry_match); m_l = m_l->next; } tmp->watchers_offset = p - base; w_l = e->w_list; while (w_l) { memcpy(p, w_l->w, w_l->w->watcher_size + sizeof(struct ebt_entry_watcher)); p += w_l->w->watcher_size + sizeof(struct ebt_entry_watcher); w_l = w_l->next; } tmp->target_offset = p - base; memcpy(p, e->t, e->t->target_size + sizeof(struct ebt_entry_target)); if (!strcmp(e->t->u.name, EBT_STANDARD_TARGET)) { struct ebt_standard_target *st = (struct ebt_standard_target *)p; /* Translate the jump to a udc */ if (st->verdict >= 0) st->verdict = chain_offsets [st->verdict + NF_BR_NUMHOOKS]; } p += e->t->target_size + sizeof(struct ebt_entry_target); tmp->next_offset = p - base; e = e->next; } } /* Sanity check */ if (p - (char *)new->entries != new->entries_size) ebt_print_bug("Entries_size bug"); free(chain_offsets); return new; } static void store_table_in_file(char *filename, struct ebt_replace *repl) { char *data; int size; int fd; /* Start from an empty file with right priviliges */ if (!(fd = creat(filename, 0600))) { ebt_print_error("Couldn't create file %s", filename); return; } size = sizeof(struct ebt_replace) + repl->entries_size + repl->nentries * sizeof(struct ebt_counter); data = (char *)malloc(size); if (!data) ebt_print_memory(); memcpy(data, repl, sizeof(struct ebt_replace)); memcpy(data + sizeof(struct ebt_replace), (char *)repl->entries, repl->entries_size); /* Initialize counters to zero, deliver_counters() can update them */ memset(data + sizeof(struct ebt_replace) + repl->entries_size, 0, repl->nentries * sizeof(struct ebt_counter)); if (write(fd, data, size) != size) ebt_print_error("Couldn't write everything to file %s", filename); close(fd); free(data); } void ebt_deliver_table(struct ebt_u_replace *u_repl) { socklen_t optlen; struct ebt_replace *repl; /* Translate the struct ebt_u_replace to a struct ebt_replace */ repl = translate_user2kernel(u_repl); if (u_repl->filename != NULL) { store_table_in_file(u_repl->filename, repl); goto free_repl; } /* Give the data to the kernel */ optlen = sizeof(struct ebt_replace) + repl->entries_size; if (get_sockfd()) goto free_repl; if (!setsockopt(sockfd, IPPROTO_IP, EBT_SO_SET_ENTRIES, repl, optlen)) goto free_repl; if (u_repl->command == 8) { /* The ebtables module may not * yet be loaded with --atomic-commit */ ebtables_insmod("ebtables"); if (!setsockopt(sockfd, IPPROTO_IP, EBT_SO_SET_ENTRIES, repl, optlen)) goto free_repl; } ebt_print_error("The kernel doesn't support a certain ebtables" " extension, consider recompiling your kernel or insmod" " the extension"); free_repl: if (repl) { free(repl->entries); free(repl); } } static int store_counters_in_file(char *filename, struct ebt_u_replace *repl) { int size = repl->nentries * sizeof(struct ebt_counter), ret = 0; unsigned int entries_size; struct ebt_replace hlp; FILE *file; if (!(file = fopen(filename, "r+b"))) { ebt_print_error("Could not open file %s", filename); return -1; } /* Find out entries_size and then set the file pointer to the * counters */ if (fseek(file, (char *)(&hlp.entries_size) - (char *)(&hlp), SEEK_SET) || fread(&entries_size, sizeof(char), sizeof(unsigned int), file) != sizeof(unsigned int) || fseek(file, entries_size + sizeof(struct ebt_replace), SEEK_SET)) { ebt_print_error("File %s is corrupt", filename); ret = -1; goto close_file; } if (fwrite(repl->counters, sizeof(char), size, file) != size) { ebt_print_error("Could not write everything to file %s", filename); ret = -1; } close_file: fclose(file); return 0; } /* Gets executed after ebt_deliver_table. Delivers the counters to the kernel * and resets the counterchanges to CNT_NORM */ void ebt_deliver_counters(struct ebt_u_replace *u_repl) { struct ebt_counter *old, *new, *newcounters; socklen_t optlen; struct ebt_replace repl; struct ebt_cntchanges *cc = u_repl->cc->next, *cc2; struct ebt_u_entries *entries = NULL; struct ebt_u_entry *next = NULL; int i, chainnr = 0; if (u_repl->nentries == 0) return; newcounters = (struct ebt_counter *) malloc(u_repl->nentries * sizeof(struct ebt_counter)); if (!newcounters) ebt_print_memory(); memset(newcounters, 0, u_repl->nentries * sizeof(struct ebt_counter)); old = u_repl->counters; new = newcounters; while (cc != u_repl->cc) { if (!next || next == entries->entries) { while (chainnr < u_repl->num_chains && (!(entries = u_repl->chains[chainnr++]) || (next = entries->entries->next) == entries->entries)); if (chainnr == u_repl->num_chains) break; } if (cc->type == CNT_NORM) { /* 'Normal' rule, meaning we didn't do anything to it * So, we just copy */ *new = *old; next->cnt = *new; next->cnt_surplus.pcnt = next->cnt_surplus.bcnt = 0; old++; /* We've used an old counter */ new++; /* We've set a new counter */ next = next->next; } else if (cc->type == CNT_DEL) { old++; /* Don't use this old counter */ } else { if (cc->type == CNT_CHANGE) { if (cc->change % 3 == 1) new->pcnt = old->pcnt + next->cnt_surplus.pcnt; else if (cc->change % 3 == 2) new->pcnt = old->pcnt - next->cnt_surplus.pcnt; else new->pcnt = next->cnt.pcnt; if (cc->change / 3 == 1) new->bcnt = old->bcnt + next->cnt_surplus.bcnt; else if (cc->change / 3 == 2) new->bcnt = old->bcnt - next->cnt_surplus.bcnt; else new->bcnt = next->cnt.bcnt; } else *new = next->cnt; next->cnt = *new; next->cnt_surplus.pcnt = next->cnt_surplus.bcnt = 0; if (cc->type == CNT_ADD) new++; else { old++; new++; } next = next->next; } cc = cc->next; } free(u_repl->counters); u_repl->counters = newcounters; u_repl->num_counters = u_repl->nentries; /* Reset the counterchanges to CNT_NORM and delete the unused cc */ i = 0; cc = u_repl->cc->next; while (cc != u_repl->cc) { if (cc->type == CNT_DEL) { cc->prev->next = cc->next; cc->next->prev = cc->prev; cc2 = cc->next; free(cc); cc = cc2; } else { cc->type = CNT_NORM; cc->change = 0; i++; cc = cc->next; } } if (i != u_repl->nentries) ebt_print_bug("i != u_repl->nentries"); if (u_repl->filename != NULL) { store_counters_in_file(u_repl->filename, u_repl); return; } optlen = u_repl->nentries * sizeof(struct ebt_counter) + sizeof(struct ebt_replace); /* Now put the stuff in the kernel's struct ebt_replace */ repl.counters = sparc_cast u_repl->counters; repl.num_counters = u_repl->num_counters; memcpy(repl.name, u_repl->name, sizeof(repl.name)); if (get_sockfd()) return; if (setsockopt(sockfd, IPPROTO_IP, EBT_SO_SET_COUNTERS, &repl, optlen)) ebt_print_bug("Couldn't update kernel counters"); } static int ebt_translate_match(struct ebt_entry_match *m, struct ebt_u_match_list ***l) { struct ebt_u_match_list *new; int ret = 0; new = (struct ebt_u_match_list *) malloc(sizeof(struct ebt_u_match_list)); if (!new) ebt_print_memory(); new->m = (struct ebt_entry_match *) malloc(m->match_size + sizeof(struct ebt_entry_match)); if (!new->m) ebt_print_memory(); memcpy(new->m, m, m->match_size + sizeof(struct ebt_entry_match)); new->next = NULL; **l = new; *l = &new->next; if (ebt_find_match(new->m->u.name) == NULL) { ebt_print_error("Kernel match %s unsupported by userspace tool", new->m->u.name); ret = -1; } return ret; } static int ebt_translate_watcher(struct ebt_entry_watcher *w, struct ebt_u_watcher_list ***l) { struct ebt_u_watcher_list *new; int ret = 0; new = (struct ebt_u_watcher_list *) malloc(sizeof(struct ebt_u_watcher_list)); if (!new) ebt_print_memory(); new->w = (struct ebt_entry_watcher *) malloc(w->watcher_size + sizeof(struct ebt_entry_watcher)); if (!new->w) ebt_print_memory(); memcpy(new->w, w, w->watcher_size + sizeof(struct ebt_entry_watcher)); new->next = NULL; **l = new; *l = &new->next; if (ebt_find_watcher(new->w->u.name) == NULL) { ebt_print_error("Kernel watcher %s unsupported by userspace " "tool", new->w->u.name); ret = -1; } return ret; } static int ebt_translate_entry(struct ebt_entry *e, int *hook, int *n, int *cnt, int *totalcnt, struct ebt_u_entry **u_e, struct ebt_u_replace *u_repl, unsigned int valid_hooks, char *base, struct ebt_cntchanges **cc) { /* An entry */ if (e->bitmask & EBT_ENTRY_OR_ENTRIES) { struct ebt_u_entry *new; struct ebt_u_match_list **m_l; struct ebt_u_watcher_list **w_l; struct ebt_entry_target *t; new = (struct ebt_u_entry *)malloc(sizeof(struct ebt_u_entry)); if (!new) ebt_print_memory(); new->bitmask = e->bitmask; /* * Plain userspace code doesn't know about * EBT_ENTRY_OR_ENTRIES