#!/usr/bin/env perl use Getopt::Std; use FindBin; use Cwd; use lib "$FindBin::Bin"; use metadata; use warnings; use strict; use Cwd 'abs_path'; chdir "$FindBin::Bin/.."; $ENV{TOPDIR} //= getcwd(); chdir $ENV{TOPDIR}; $ENV{GIT_CONFIG_PARAMETERS}="'core.autocrlf=false'"; $ENV{GREP_OPTIONS}=""; my $mk=`which gmake 2>/dev/null`; # select the right 'make' program chomp($mk); # trim trailing newline $mk or $mk = "make"; # default to 'make' # check version of make my @mkver = split /\s+/, `$mk -v`, 4; my $valid_mk = 1; $mkver[0] =~ /^GNU/ or $valid_mk = 0; $mkver[1] =~ /^Make/ or $valid_mk = 0; my ($mkv1, $mkv2) = split /\./, $mkver[2]; ($mkv1 >= 4 || ($mkv1 == 3 && $mkv2 >= 81)) or $valid_mk = 0; $valid_mk or die "Unsupported version of make found: $mk\n"; my @feeds; my %build_packages; my %installed; my %installed_pkg; my %installed_targets; my %feed_cache; my $feed_package = {}; my $feed_src = {}; my $feed_target = {}; my $feed_vpackage = {}; sub parse_config() { my $line = 0; my %name; open FEEDS, "feeds.conf" or open FEEDS, "feeds.conf.default" or die "Unable to open feeds configuration"; while () { chomp; s/#.+$//; next unless /\S/; my @line = split /\s+/, $_, 3; my @src; $line++; my $valid = 1; $line[0] =~ /^src-[\w-]+$/ or $valid = 0; $line[1] =~ /^\w+$/ or $valid = 0; @src = split /\s+/, $line[2]; $valid or die "Syntax error in feeds.conf, line: $line\n"; $name{$line[1]} and die "Duplicate feed name '$line[1]', line: $line\n"; $name{$line[1]} = 1; push @feeds, [$line[0], $line[1], \@src]; } close FEEDS; } sub update_location($$) { my $name = shift; my $url = shift; my $old_url; -d "./feeds/$name.tmp" or mkdir "./feeds/$name.tmp" or return 1; if( open LOC, "< ./feeds/$name.tmp/location" ) { chomp($old_url = readline LOC); close LOC; } if( !$old_url || $old_url ne $url ) { if( open LOC, "> ./feeds/$name.tmp/location" ) { print LOC $url, "\n"; close LOC; } return $old_url ? 1 : 0; } return 0; } sub update_index($) { my $name = shift; -d "./feeds/$name.tmp" or mkdir "./feeds/$name.tmp" or return 1; -d "./feeds/$name.tmp/info" or mkdir "./feeds/$name.tmp/info" or return 1; system("$mk -s prepare-mk OPENWRT_BUILD= TMP_DIR=\"$ENV{TOPDIR}/feeds/$name.tmp\""); system("$mk -s -f include/scan.mk IS_TTY=1 SCAN_TARGET=\"packageinfo\" SCAN_DIR=\"feeds/$name\" SCAN_NAME=\"package\" SCAN_DEPS=\"$ENV{TOPDIR}/include/package*.mk\" SCAN_DEPTH=5 SCAN_EXTRA=\"\" TMP_DIR=\"$ENV{TOPDIR}/feeds/$name.tmp\""); system("$mk -s -f include/scan.mk IS_TTY=1 SCAN_TARGET=\"targetinfo\" SCAN_DIR=\"feeds/$name\" SCAN_NAME=\"target\" SCAN_DEPS=\"profiles/*.mk $ENV{TOPDIR}/include/target.mk\" SCAN_DEPTH=5 SCAN_EXTRA=\"\" SCAN_MAKEOPTS=\"TARGET_BUILD=1\" TMP_DIR=\"$ENV{TOPDIR}/feeds/$name.tmp\""); system("ln -sf $name.tmp/.packageinfo ./feeds/$name.index"); system("ln -sf $name.tmp/.targetinfo ./feeds/$name.targetindex"); return 0; } my %update_method = ( 'src-svn' => { 'init' => "svn checkout '%s' '%s'", 'update' => "svn update", 'controldir' => ".svn", 'revision' => "svn info | grep 'Revision' | cut -d ' ' -f 2 | tr -d '\n'"}, 'src-cpy' => { 'init' => "cp -Rf '%s' '%s'", 'update' => "", 'revision' => "echo -n 'local'"}, 'src-link' => { 'init' => "ln -s '%s' '%s'", 'update' => "", 'revision' => "echo -n 'local'"}, 'src-git' => { 'init' => "git clone --depth 1 '%s' '%s'", 'init_branch' => "git clone --depth 1 --branch '%s' '%s' '%s'", 'init_commit' => "git clone '%s' '%s' && cd '%s' && git checkout -b '%s' '%s' && cd -", 'update' => "git pull --ff", 'update_force' => "git pull --ff || (git reset --hard HEAD; git pull --ff; exit 1)", 'controldir' => ".git", 'revision' => "git rev-parse --short HEAD | tr -d '\n'"}, 'src-git-full' => { 'init' => "git clone '%s' '%s'", 'init_branch' => "git clone --branch '%s' '%s' '%s'", 'init_commit' => "git clone '%s' '%s' && cd '%s' && git checkout -b '%s' '%s' && cd -", 'update' => "git pull --ff", 'update_force' => "git pull --ff || (git reset --hard HEAD; git pull --ff; exit 1)", 'controldir' => ".git", 'revision' => "git rev-parse --short HEAD | tr -d '\n'"}, 'src-gitsvn' => { 'init' => "git svn clone -r HEAD '%s' '%s'", 'update' => "git svn rebase", 'controldir' => ".git", 'revision' => "git rev-parse --short HEAD | tr -d '\n'"}, 'src-bzr' => { 'init' => "bzr checkout --lightweight '%s' '%s'", 'update' => "bzr update", 'controldir' => ".bzr"}, 'src-hg' => { 'init' => "hg clone '%s' '%s'", 'update' => "hg pull --update", 'controldir' => ".hg"}, 'src-darcs' => { 'init' => "darcs get '%s' '%s'", 'update' => "darcs pull -a", 'controldir' => "_darcs"}, ); # src-git: pull broken # src-cpy: broken if `basename $src` != $name sub update_feed_via($$$$$) { my $type = shift; my $name = shift; my $src = shift; my $relocate = shift; my $force = shift; my $m = $update_method{$type}; my $localpath = "./feeds/$name"; my $safepath = $localpath; $safepath =~ s/'/'\\''/; my ($base_branch, $branch) = split(/;/, $src, 2); my ($base_commit, $commit) = split(/\^/, $src, 2); if( $relocate || !$m->{'update'} || !-d "$localpath/$m->{'controldir'}" ) { system("rm -rf '$safepath'"); if ($m->{'init_branch'} and $branch) { system(sprintf($m->{'init_branch'}, $branch, $base_branch, $safepath)) == 0 or return 1; } elsif ($m->{'init_commit'} and $commit) { system(sprintf($m->{'init_commit'}, $base_commit, $safepath, $safepath, $commit, $commit)) == 0 or return 1; } else { system(sprintf($m->{'init'}, $src, $safepath)) == 0 or return 1; } } elsif ($m->{'init_commit'} and $commit) { # in case git hash has been provided don't update the feed } else { my $update_cmd = $m->{'update'}; if ($force && exists $m->{'update_force'}) { $update_cmd = $m->{'update_force'}; } system("cd '$safepath'; $update_cmd") == 0 or return 1; } return 0; } sub get_targets($) { my $file = shift; my @target = parse_target_metadata($file); my %target; foreach my $target (@target) { $target{$target->{id}} = $target; } return %target } sub get_feed($) { my $feed = shift; if (!defined($feed_cache{$feed})) { my $file = "./feeds/$feed.index"; clear_packages(); -f $file or do { print "Ignoring feed '$feed' - index missing\n"; return; }; parse_package_metadata($file) or return; my %target = get_targets("./feeds/$feed.targetindex"); $feed_cache{$feed} = [ { %package }, { %srcpackage }, { %target }, { %vpackage } ]; } $feed_package = $feed_cache{$feed}->[0]; $feed_src = $feed_cache{$feed}->[1]; $feed_target = $feed_cache{$feed}->[2]; $feed_vpackage = $feed_cache{$feed}->[3]; } sub get_installed() { system("$mk -s prepare-tmpinfo OPENWRT_BUILD="); clear_packages(); parse_package_metadata("./tmp/.packageinfo"); %installed_pkg = %vpackage; %installed = %srcpackage; %installed_targets = get_targets("./tmp/.targetinfo"); } sub search_feed { my $feed = shift; my @substr = @_; my $display; return unless @substr > 0; get_feed($feed); foreach my $name (sort { lc($a) cmp lc($b) } keys %$feed_package) { my $pkg = $feed_package->{$name}; my $substr; my $pkgmatch = 1; foreach my $substr (@substr) { my $match; foreach my $key (qw(name title description src)) { $pkg->{$key} and $substr and $pkg->{$key} =~ m/$substr/i and $match = 1; } $match or undef $pkgmatch; }; $pkgmatch and do { $display or do { print "Search results in feed '$feed':\n"; $display = 1; }; printf "\%-25s\t\%s\n", $pkg->{name}, $pkg->{title}; }; } foreach my $name (sort { lc($a) cmp lc($b) } keys %$feed_target) { my $target = $feed_target->{$name}; my $targetmatch = 1; foreach my $substr (@substr) { my $match; foreach my $key (qw(id name description)) { $target->{$key} and $substr and $target->{$key} =~ m/$substr/i and $match = 1; } $match or undef $targetmatch; }; $targetmatch and do { $display or do { print "Search results in feed '$feed':\n"; $display = 1; }; printf "TARGET: \%-17s\t\%s\n", $target->{id}, $target->{name}; }; } return 0; } sub search { my %opts; getopt('r:', \%opts); foreach my $feed (@feeds) { search_feed($feed->[1], @ARGV) if (!defined($opts{r}) or $opts{r} eq $feed->[1]); } } sub list_feed { my $feed = shift; get_feed($feed); foreach my $name (sort { lc($a) cmp lc($b) } keys %$feed_package) { my $pkg = $feed_package->{$name}; if($pkg->{name}) { printf "\%-32s\t\%s\n", $pkg->{name}, $pkg->{title}; } } foreach my $name (sort { lc($a) cmp lc($b) } keys %$feed_target) { my $target = $feed_target->{$name}; if($target->{name}) { printf "TARGET: \%-24s\t\%s\n", $target->{id}, $target->{name}; } } return 0; } sub list { my %opts; getopts('r:d:nshf', \%opts); if ($opts{h}) { usage(); return 0; } if ($opts{n}) { foreach my $feed (@feeds) { printf "%s\n", $feed->[1]; } return 0; } if ($opts{s}) { foreach my $feed (@feeds) { my $localpath = "./feeds/$feed->[1]"; my $m = $update_method{$feed->[0]}; my $revision; if (!-d "$localpath" || !$m->{'revision'}) { $revision = "X"; } elsif( $m->{'controldir'} && -d "$localpath/$m->{'controldir'}" ) { $revision = `cd '$localpath'; $m->{'revision'}`; } else { $revision = "local"; } if ($opts{d}) { printf "%s%s%s%s%s%s%s\n", $feed->[1], $opts{d}, $feed->[0], $opts{d}, $revision, $opts{d}, join(", ", @{$feed->[2]}); } elsif ($opts{f}) { my $uri = join(", ", @{$feed->[2]}); if ($revision ne "local" && $revision ne "X") { $uri =~ s/[;^].*//; $uri .= "^" . $revision; } printf "%s %s %s\n", $feed->[0], $feed->[1], $uri; } else { printf "\%-10s \%-8s \%-8s \%s\n", $feed->[1], $feed->[0], $revision, join(", ", @{$feed->[2]}); } } return 0; } foreach my $feed (@feeds) { list_feed($feed->[1], @ARGV) if (!defined($opts{r}) or $opts{r} eq $feed->[1]); } return 0; } sub do_install_src($$) { my $feed = shift; my $src = shift; my $path = $src->{makefile}; if ($path) { $path =~ s/\/Makefile$//; -d "./package/feeds" or mkdir "./package/feeds"; -d "./package/feeds/$feed->[1]" or mkdir "./package/feeds/$feed->[1]"; system("ln -sf ../../../$path ./package/feeds/$feed->[1]/"); } else { warn "Package is not valid\n"; return 1; } return 0; } sub do_install_target($) { my $target = shift; my $path = $target->{makefile}; if ($path) { $path =~ s/\/Makefile$//; my $name = $path; $name =~ s/.*\///; my $dest = "./target/linux/$name"; -e $dest and do { warn "Path $dest already exists"; return 1; }; system("ln -sf ../../$path ./target/linux/"); } else { warn "Target is not valid\n"; return 1; } return 0; } sub lookup_src($$) { my $feed = shift; my $src = shift; foreach my $feed ($feed, @feeds) { next unless $feed->[1]; next unless $feed_cache{$feed->[1]}; $feed_cache{$feed->[1]}->[1]->{$src} and return $feed; } return; } sub lookup_package($$) { my $feed = shift; my $package = shift; foreach my $feed ($feed, @feeds) { next unless $feed->[1]
/*
             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 VirtualSerialHost demo. This file contains the main tasks of
 *  the demo and is responsible for the initial application hardware configuration.
 */

#include "VirtualSerialHost.h"

/** LUFA CDC Class driver interface configuration and state information. This structure is
 *  passed to all CDC Class driver functions, so that multiple instances of the same class
 *  within a device can be differentiated from one another.
 */
USB_ClassInfo_CDC_Host_t VirtualSerial_CDC_Interface =
	{
		.Config =
			{
				.DataINPipe             =
					{
						.Address        = (PIPE_DIR_IN  | 1),
						.Banks          = 1,
					},
				.DataOUTPipe            =
					{
						.Address        = (PIPE_DIR_OUT | 2),
						.Banks          = 1,
					},
				.NotificationPipe       =
					{
						.Address        = (PIPE_DIR_IN  | 3),
						.Banks          = 1,
					},
			},
	};


/** Main program entry point. This routine configures the hardware required by the application, then
 *  enters a loop to run the application tasks in sequence.
 */
int main(void)
{
	SetupHardware();

	puts_P(PSTR(ESC_FG_CYAN "CDC Host Demo running.\r\n" ESC_FG_WHITE));

	LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
	GlobalInterruptEnable();

	for (;;)
	{
		CDCHost_Task();

		CDC_Host_USBTask(&VirtualSerial_CDC_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);
#endif

	/* Hardware Initialization */
	Serial_Init(9600, false);
	LEDs_Init();
	USB_Init();

	/* Create a stdio stream for the serial port for stdin and stdout */
	Serial_CreateStream(NULL);
}

/** Task to manage an enumerated USB CDC device once connected, to print received data
 *  from the device to the serial port.
 */
void CDCHost_Task(void)
{
	if (USB_HostState != HOST_STATE_Configured)
	  return;

	if (CDC_Host_BytesReceived(&VirtualSerial_CDC_Interface))
	{
		/* Echo received bytes from the attached device through the USART */
		int16_t ReceivedByte = CDC_Host_ReceiveByte(&VirtualSerial_CDC_Interface);
		if (!(ReceivedByte < 0))
		  putchar(ReceivedByte);
	}
}

/** Event handler for the USB_DeviceAttached event. This indicates that a device has been attached to the host, and
 *  starts the library USB task to begin the enumeration and USB management process.
 */
void EVENT_USB_Host_DeviceAttached(void)
{
	puts_P(PSTR("Device Attached.\r\n"));
	LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
}

/** Event handler for the USB_DeviceUnattached event. This indicates that a device has been removed from the host, and
 *  stops the library USB task management process.
 */
void EVENT_USB_Host_DeviceUnattached(void)
{
	puts_P(PSTR("\r\nDevice Unattached.\r\n"));
	LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
}

/** Event handler for the USB_DeviceEnumerationComplete event. This indicates that a device has been successfully
 *  enumerated by the host and is now ready to be used by the application.
 */
void EVENT_USB_Host_DeviceEnumerationComplete(void)
{
	LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);

	uint16_t ConfigDescriptorSize;
	uint8_t  ConfigDescriptorData[512];

	if (USB_Host_GetDeviceConfigDescriptor(1, &ConfigDescriptorSize, ConfigDescriptorData,
	                                       sizeof(ConfigDescriptorData)) != HOST_GETCONFIG_Successful)
	{
		puts_P(PSTR("Error Retrieving Configuration Descriptor.\r\n"));
		LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
		return;
	}

	if (CDC_Host_ConfigurePipes(&VirtualSerial_CDC_Interface,
	                            ConfigDescriptorSize, ConfigDescriptorData) != CDC_ENUMERROR_NoError)
	{
		puts_P(PSTR("Attached Device Not a Valid CDC Class Device.\r\n"));
		LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
		return;
	}

	if (USB_Host_SetDeviceConfiguration(1) != HOST_SENDCONTROL_Successful)
	{
		puts_P(PSTR("Error Setting Device Configuration.\r\n"));
		LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
		return;
	}

	VirtualSerial_CDC_Interface.State.LineEncoding.BaudRateBPS = 9600;
	VirtualSerial_CDC_Interface.State.LineEncoding.CharFormat  = CDC_LINEENCODING_OneStopBit;
	VirtualSerial_CDC_Interface.State.LineEncoding.ParityType  = CDC_PARITY_None;
	VirtualSerial_CDC_Interface.State.LineEncoding.DataBits    = 8;

	if (CDC_Host_SetLineEncoding(&VirtualSerial_CDC_Interface))
	{
		puts_P(PSTR("Error Setting Device Line Encoding.\r\n"));
		LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
		return;
	}

	puts_P(PSTR("CDC Device Enumerated.\r\n"));
	LEDs_SetAllLEDs(LEDMASK_USB_READY);
}

/** Event handler for the USB_HostError event. This indicates that a hardware error occurred while in host mode. */
void EVENT_USB_Host_HostError(const uint8_t ErrorCode)
{
	USB_Disable();

	printf_P(PSTR(ESC_FG_RED "Host Mode Error\r\n"
	                         " -- Error Code %d\r\n" ESC_FG_WHITE), ErrorCode);

	LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
	for(;;);
}

/** Event handler for the USB_DeviceEnumerationFailed event. This indicates that a problem occurred while
 *  enumerating an attached USB device.
 */
void EVENT_USB_Host_DeviceEnumerationFailed(const uint8_t ErrorCode,
                                            const uint8_t SubErrorCode)
{
	printf_P(PSTR(ESC_FG_RED "Dev Enum Error\r\n"
	                         " -- Error Code %d\r\n"
	                         " -- Sub Error Code %d\r\n"
	                         " -- In State %d\r\n" ESC_FG_WHITE), ErrorCode, SubErrorCode, USB_HostState);

	LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
}