aboutsummaryrefslogtreecommitdiffstats
path: root/lib/lufa/Demos/Device/LowLevel/VirtualSerial/VirtualSerial.c
blob: 6f83a84af0b609eb91605cf4338b9cf4b736fa8d (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
/*
             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 VirtualSerial demo. This file contains the main tasks of the demo and
 *  is responsible for the initial application hardware configuration.
 */

#include "VirtualSerial.h"

/** Contains the current baud rate and other settings of the virtual serial port. While this demo does not use
 *  the physical USART and thus does not use these settings, they must still be retained and returned to the host
 *  upon request or the host will assume the device is non-functional.
 *
 *  These values are set by the host via a class-specific request, however they are not required to be used accurately.
 *  It is possible to completely ignore these value or use other settings as the host is completely unaware of the physical
 *  serial link characteristics and instead sends and receives data in endpoint streams.
 */
static CDC_LineEncoding_t LineEncoding = { .BaudRateBPS = 0,
                                           .CharFormat  = CDC_LINEENCODING_OneStopBit,
                                           .ParityType  = CDC_PARITY_None,
                                           .DataBits    = 8                            };


/** 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 (;;)
	{
		CDC_Task();
		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();
	USB_Init();
}

/** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs and
 *  starts the library USB task to begin the enumeration and USB management process.
 */
void EVENT_USB_Device_Connect(void)
{
	/* Indicate USB enumerating */
	LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
}

/** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
 *  the status LEDs and stops the USB management and CDC management tasks.
 */
void EVENT_USB_Device_Disconnect(void)
{
	/* Indicate USB not ready */
	LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
}

/** Event handler for the USB_ConfigurationChanged event. This is fired when the host set the current configuration
 *  of the USB device after enumeration - the device endpoints are configured and the CDC management task started.
 */
void EVENT_USB_Device_ConfigurationChanged(void)
{
	bool ConfigSuccess = true;

	/* Setup CDC Data Endpoints */
	ConfigSuccess &= Endpoint_ConfigureEndpoint(CDC_NOTIFICATION_EPADDR, EP_TYPE_INTERRUPT, CDC_NOTIFICATION_EPSIZE, 1);
	ConfigSuccess &= Endpoint_ConfigureEndpoint(CDC_TX_EPADDR, EP_TYPE_BULK, CDC_TXRX_EPSIZE, 1);
	ConfigSuccess &= Endpoint_ConfigureEndpoint(CDC_RX_EPADDR, EP_TYPE_BULK,  CDC_TXRX_EPSIZE, 1);

	/* Reset line encoding baud rate so that the host knows to send new values */
	LineEncoding.BaudRateBPS = 0;

	/* Indicate endpoint configuration success or failure */
	LEDs_SetAllLEDs(ConfigSuccess ? LEDMASK_USB_READY : LEDMASK_USB_ERROR);
}

/** Event handler for the USB_ControlRequest event. This is used to catch and process control requests sent to
 *  the device from the USB host before passing along unhandled control requests to the library for processing
 *  internally.
 */
void EVENT_USB_Device_ControlRequest(void)
{
	/* Process CDC specific control requests */
	switch (USB_ControlRequest.bRequest)
	{
		case CDC_REQ_GetLineEncoding:
			if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
			{
				Endpoint_ClearSETUP();

				/* Write the line coding data to the control endpoint */
				Endpoint_Write_Control_Stream_LE(&LineEncoding, sizeof(CDC_LineEncoding_t));
				Endpoint_ClearOUT();
			}

			break;
		case CDC_REQ_SetLineEncoding:
			if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
			{
				Endpoint_ClearSETUP();

				/* Read the line coding data in from the host into the global struct */
				Endpoint_Read_Control_Stream_LE(&LineEncoding, sizeof(CDC_LineEncoding_t));
				Endpoint_ClearIN();
			}

			break;
		case CDC_REQ_SetControlLineState:
			if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
			{
				Endpoint_ClearSETUP();
				Endpoint_ClearStatusStage();

				/* NOTE: Here you can read in the line state mask from the host, to get the current state of the output handshake
				         lines. The mask is read in from the wValue parameter in USB_ControlRequest, and can be masked against the
						 CONTROL_LINE_OUT_* masks to determine the RTS and DTR line states using the following code:
				*/
			}

			break;
	}
}

/** Function to manage CDC data transmission and reception to and from the host. */
void CDC_Task(void)
{
	char*       ReportString    = NULL;
	uint8_t     JoyStatus_LCL   = Joystick_GetStatus();
	static bool ActionSent      = false;

	/* Device must be connected and configured for the task to run */
	if (USB_DeviceState != DEVICE_STATE_Configured)
	  return;

	/* Determine if a joystick action has occurred */
	if (JoyStatus_LCL & JOY_UP)
	  ReportString = "Joystick Up\r\n";
	else if (JoyStatus_LCL & JOY_DOWN)
	  ReportString = "Joystick Down\r\n";
	else if (JoyStatus_LCL & JOY_LEFT)
	  ReportString = "Joystick Left\r\n";
	else if (JoyStatus_LCL & JOY_RIGHT)
	  ReportString = "Joystick Right\r\n";
	else if (JoyStatus_LCL & JOY_PRESS)
	  ReportString = "Joystick Pressed\r\n";
	else
	  ActionSent = false;

	/* Flag management - Only allow one string to be sent per action */
	if ((ReportString != NULL) && (ActionSent == false) && LineEncoding.BaudRateBPS)
	{
		ActionSent = true;

		/* Select the Serial Tx Endpoint */
		Endpoint_SelectEndpoint(CDC_TX_EPADDR);

		/* Write the String to the Endpoint */
		Endpoint_Write_Stream_LE(ReportString, strlen(ReportString), NULL);

		/* Remember if the packet to send completely fills the endpoint */
		bool IsFull = (Endpoint_BytesInEndpoint() == CDC_TXRX_EPSIZE);

		/* Finalize the stream transfer to send the last packet */
		Endpoint_ClearIN();

		/* If the last packet filled the endpoint, send an empty packet to release the buffer on
		 * the receiver (otherwise all data will be cached until a non-full packet is received) */
		if (IsFull)
		{
			/* Wait until the endpoint is ready for another packet */
			Endpoint_WaitUntilReady();

			/* Send an empty packet to ensure that the host does not buffer data sent to it */
			Endpoint_ClearIN();
		}
	}

	/* Select the Serial Rx Endpoint */
	Endpoint_SelectEndpoint(CDC_RX_EPADDR);

	/* Throw away any received data from the host */
	if (Endpoint_IsOUTReceived())
	  Endpoint_ClearOUT();
}
an> 13 -> PDB.write_register ctx ES new_val | 14 -> PDB.write_register ctx FS new_val | 15 -> PDB.write_register ctx GS new_val | _ -> print_endline (Printf.sprintf "write unknown register [%d]" reg) in Scanf.sscanf command "P%x=%lx" write_reg; "OK" (** General Query Packets *) let gdb_query command = match command with | "qC" -> "" | "qOffsets" -> "" | "qSymbol::" -> "" | _ -> print_endline (Printf.sprintf "unknown gdb query packet [%s]" command); "E01" (** Write Memory Binary Packets *) let gdb_write_memory_binary ctx command = let write_mem addr len = let pos = Str.search_forward (Str.regexp ":") command 0 in let txt = Str.string_after command (pos + 1) in PDB.write_memory ctx addr (int_list_of_string txt len) in Scanf.sscanf command "X%lx,%d" write_mem; "OK" (** Last Signal Command *) let gdb_last_signal = "S00" (** Process PDB extensions to the GDB serial protocol. Changes the mutable context state. *) let pdb_extensions command sock = let process_extension key value = (* since this command can change the context, we need to grab it again each time *) let ctx = PDB.find_context sock in match key with | "status" -> PDB.debug_contexts (); (* print_endline ("debugger status"); debugger_status () *) | "context" -> PDB.add_context sock (List.hd value) (int_list_of_string_list (List.tl value)) | _ -> failwith (Printf.sprintf "unknown pdb extension command [%s:%s]" key (List.hd value)) in try Util.little_parser process_extension (String.sub command 1 ((String.length command) - 1)); "OK" with | Unknown_context s -> print_endline (Printf.sprintf "unknown context [%s]" s); "E01" | Unknown_domain -> "E01" | Failure s -> "E01" (** Insert Breakpoint or Watchpoint Packet *) let bwc_watch_write = 102 (* from pdb_module.h *) let bwc_watch_read = 103 let bwc_watch_access = 104 let gdb_insert_bwcpoint ctx command = let insert cmd addr length = try match cmd with | 0 -> PDB.insert_memory_breakpoint ctx addr length; "OK" | 2 -> PDB.insert_watchpoint ctx bwc_watch_write addr length; "OK" | 3 -> PDB.insert_watchpoint ctx bwc_watch_read addr length; "OK" | 4 -> PDB.insert_watchpoint ctx bwc_watch_access addr length; "OK" | _ -> "" with Failure s -> "E03" in Scanf.sscanf command "Z%d,%lx,%x" insert (** Remove Breakpoint or Watchpoint Packet *) let gdb_remove_bwcpoint ctx command = let insert cmd addr length = try match cmd with | 0 -> PDB.remove_memory_breakpoint ctx addr length; "OK" | 2 -> PDB.remove_watchpoint ctx bwc_watch_write addr length; "OK" | 3 -> PDB.remove_watchpoint ctx bwc_watch_read addr length; "OK" | 4 -> PDB.remove_watchpoint ctx bwc_watch_access addr length; "OK" | _ -> "" with Failure s -> "E04" in Scanf.sscanf command "z%d,%lx,%d" insert (** Do Work! @param command char list *) let process_command command sock = let ctx = PDB.find_context sock in try match command.[0] with | 'c' -> gdb_continue ctx | 'D' -> gdb_detach ctx | 'g' -> gdb_read_registers ctx | 'H' -> gdb_set_thread command | 'k' -> gdb_kill () | 'm' -> gdb_read_memory ctx command | 'M' -> gdb_write_memory ctx command | 'p' -> gdb_read_register ctx command | 'P' -> gdb_write_register ctx command | 'q' -> gdb_query command | 's' -> gdb_step ctx | 'x' -> pdb_extensions command sock | 'X' -> gdb_write_memory_binary ctx command | '?' -> gdb_last_signal | 'z' -> gdb_remove_bwcpoint ctx command | 'Z' -> gdb_insert_bwcpoint ctx command | _ -> print_endline (Printf.sprintf "unknown gdb command [%s]" command); "" with Unimplemented s -> print_endline (Printf.sprintf "loser. unimplemented command [%s][%s]" command s); "E03" (** process_xen_domain This is called whenever a domain debug assist responds to a pdb packet. *) let process_xen_domain fd = let channel = Evtchn.read fd in let ctx = find_context fd in let (dom, pid, str) = begin match ctx with | Xen_domain d -> Xen_domain.process_response (Xen_domain.get_ring d) | _ -> failwith ("process_xen_domain called without Xen_domain context") end in let sock = PDB.find_process dom pid in print_endline (Printf.sprintf "(linux) dom:%d pid:%d %s %s" dom pid str (Util.get_connection_info sock)); Util.send_reply sock str; Evtchn.unmask fd channel (* allow next virq *) (** process_xen_virq This is called each time a virq_pdb is sent from xen to dom 0. It is sent by Xen when a domain hits a breakpoint. Think of this as the continuation function for a "c" or "s" command issued to a domain. *) external query_domain_stop : unit -> (int * int) list = "query_domain_stop" (* returns a list of paused domains : () -> (domain, vcpu) list *) let process_xen_virq fd = let channel = Evtchn.read fd in let find_pair (dom, vcpu) = print_endline (Printf.sprintf "checking %d.%d" dom vcpu); try let sock = PDB.find_domain dom vcpu in true with Unknown_domain -> false in let dom_list = query_domain_stop () in let (dom, vcpu) = List.find find_pair dom_list in let vec = 3 in let sock = PDB.find_domain dom vcpu in print_endline (Printf.sprintf "handle bkpt dom:%d vcpu:%d vec:%d %s" dom vcpu vec (Util.get_connection_info sock)); Util.send_reply sock "S05"; Evtchn.unmask fd channel (* allow next virq *) (** process_xen_xcs This is called each time the software assist residing in a backend domain starts up. The control message includes the address of a shared ring page and our end of an event channel (which indicates when data is available on the ring). *) let process_xen_xcs xcs_fd = let (local_evtchn_fd, evtchn, dom, ring) = Xcs.read xcs_fd in add_xen_domain_context local_evtchn_fd dom evtchn ring; local_evtchn_fd