aboutsummaryrefslogtreecommitdiffstats
path: root/Demos/Host/ClassDriver/MouseHostWithParser/MouseHostWithParser.h
blob: 3d174ef8d54f457cb662455e1e872c2af460819b (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
/*
             LUFA Library
     Copyright (C) Dean Camera, 2019.

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

/*
  Copyright 2019  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
 *
 *  Header file for MouseHost.c.
 */

#ifndef _MOUSE_HOST_H_
#define _MOUSE_HOST_H_

	/* Includes: */
		#include <avr/io.h>
		#include <avr/wdt.h>
		#include <avr/pgmspace.h>
		#include <avr/power.h>
		#include <avr/interrupt.h>
		#include <stdio.h>

		#include <LUFA/Drivers/Misc/TerminalCodes.h>
		#include <LUFA/Drivers/Peripheral/Serial.h>
		#include <LUFA/Drivers/Board/LEDs.h>
		#include <LUFA/Drivers/USB/USB.h>
		#include <LUFA/Platform/Platform.h>

	/* Macros: */
		/** LED mask for the library LED driver, to indicate that the USB interface is not ready. */
		#define LEDMASK_USB_NOTREADY        LEDS_LED1

		/** LED mask for the library LED driver, to indicate that the USB interface is enumerating. */
		#define LEDMASK_USB_ENUMERATING     (LEDS_LED2 | LEDS_LED3)

		/** LED mask for the library LED driver, to indicate that the USB interface is ready. */
		#define LEDMASK_USB_READY           (LEDS_LED2 | LEDS_LED4)

		/** LED mask for the library LED driver, to indicate that an error has occurred in the USB interface. */
		#define LEDMASK_USB_ERROR           (LEDS_LED1 | LEDS_LED3)

		/** HID Report Descriptor Usage Page value for a toggle button. */
		#define USAGE_PAGE_BUTTON           0x09

		/** HID Report Descriptor Usage Page value for a Generic Desktop Control. */
		#define USAGE_PAGE_GENERIC_DCTRL    0x01

		/** HID Report Descriptor Usage for a Mouse. */
		#define USAGE_MOUSE                 0x02

		/** HID Report Descriptor Usage value for a X axis movement. */
		#define USAGE_X                     0x30

		/** HID Report Descriptor Usage value for a Y axis movement. */
		#define USAGE_Y                     0x31

		/** HID Report Descriptor Usage value for a Scroll Wheel movement. */
		#define USAGE_SCROLL_WHEEL          0x38

	/* Function Prototypes: */
		void SetupHardware(void);
		void MouseHost_Task(void);

		void EVENT_USB_Host_HostError(const uint8_t ErrorCode);
		void EVENT_USB_Host_DeviceAttached(void);
		void EVENT_USB_Host_DeviceUnattached(void);
		void EVENT_USB_Host_DeviceEnumerationFailed(const uint8_t ErrorCode,
		                                            const uint8_t SubErrorCode);
		void EVENT_USB_Host_DeviceEnumerationComplete(void);

		bool CALLBACK_HIDParser_FilterHIDReportItem(HID_ReportItem_t* const CurrentItem);

#endif
alic } /* Generic.Emph */ .highlight .gr { color: #aa0000 } /* Generic.Error */ .highlight .gh { color: #333333 } /* Generic.Heading */ .highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */ .highlight .go { color: #888888 } /* Generic.Output */ .highlight .gp { color: #555555 } /* Generic.Prompt */ .highlight .gs { font-weight: bold } /* Generic.Strong */ .highlight .gu { color: #666666 } /* Generic.Subheading */ .highlight .gt { color: #aa0000 } /* Generic.Traceback */ .highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */ .highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */ .highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */ .highlight .kp { color: #008800 } /* Keyword.Pseudo */ .highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */ .highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */ .highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */ .highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */ .highlight .na { color: #336699 } /* Name.Attribute */ .highlight .nb { color: #003388 } /* Name.Builtin */ .highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */ .highlight .no { color: #003366; font-weight: bold } /* Name.Constant */ .highlight .nd { color: #555555 } /* Name.Decorator */ .highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */ .highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */ .highlight .nl { color: #336699; font-style: italic } /* Name.Label */ .highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */ .highlight .py { color: #336699; font-weight: bold } /* Name.Property */ .highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */ .highlight .nv { color: #336699 } /* Name.Variable */ .highlight .ow { color: #008800 } /* Operator.Word */ .highlight .w { color: #bbbbbb } /* Text.Whitespace */ .highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */ .highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */ .highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */ .highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */ .highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */ .highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */ .highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */ .highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */ .highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */ .highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */ .highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */ .highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */ .highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */ .highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */ .highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */ .highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */ .highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */ .highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */ .highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */ .highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */ .highlight .vc { color: #336699 } /* Name.Variable.Class */ .highlight .vg { color: #dd7700 } /* Name.Variable.Global */ .highlight .vi { color: #3333bb } /* Name.Variable.Instance */ .highlight .vm { color: #336699 } /* Name.Variable.Magic */ .highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
#!/usr/bin/env python3
#
# Copyright (c) 2018 Yousong Zhou <yszhou4tech@gmail.com>
#
# This is free software, licensed under the GNU General Public License v2.
# See /LICENSE for more information.

import argparse
import calendar
import datetime
import errno
import fcntl
import hashlib
import json
import os
import os.path
import re
import shutil
import ssl
import subprocess
import sys
import time
import urllib.request

TMPDIR = os.environ.get('TMP_DIR') or '/tmp'
TMPDIR_DL = os.path.join(TMPDIR, 'dl')


class PathException(Exception): pass
class DownloadGitHubError(Exception): pass


class Path(object):
    """Context class for preparing and cleaning up directories.

    If ```preclean` is ``False``, ``path`` will NOT be removed on context enter

    If ``path`` ``isdir``, then it will be created on context enter.

    If ``keep`` is True, then ``path`` will NOT be removed on context exit
    """

    def __init__(self, path, isdir=True, preclean=False, keep=False):
        self.path = path
        self.isdir = isdir
        self.preclean = preclean
        self.keep = keep

    def __enter__(self):
        if self.preclean:
            self.rm_all(self.path)
        if self.isdir:
            self.mkdir_all(self.path)
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        if not self.keep:
            self.rm_all(self.path)

    @staticmethod
    def mkdir_all(path):
        """Same as mkdir -p."""
        names = os.path.split(path)
        p = ''
        for name in names:
            p = os.path.join(p, name)
            Path._mkdir(p)

    @staticmethod
    def _rmdir_dir(dir_):
        names = Path._listdir(dir_)
        for name in names:
            p = os.path.join(dir_, name)
            Path.rm_all(p)
        Path._rmdir(dir_)

    @staticmethod
    def _mkdir(path):
        Path._os_func(os.mkdir, path, errno.EEXIST)

    @staticmethod
    def _rmdir(path):
        Path._os_func(os.rmdir, path, errno.ENOENT)

    @staticmethod
    def _remove(path):
        Path._os_func(os.remove, path, errno.ENOENT)

    @staticmethod
    def _listdir(path):
        return Path._os_func(os.listdir, path, errno.ENOENT, default=[])

    @staticmethod
    def _os_func(func, path, errno, default=None):
        """Call func(path) in an idempotent way.

        On exception ``ex``, if the type is OSError and ``ex.errno == errno``,
        return ``default``, otherwise, re-raise
        """
        try:
            return func(path)
        except OSError as e:
            if e.errno == errno:
                return default
            else:
                raise

    @staticmethod
    def rm_all(path):
        """Same as rm -r."""
        if os.path.islink(path):
            Path._remove(path)
        elif os.path.isdir(path):
            Path._rmdir_dir(path)
        else:
            Path._remove(path)

    @staticmethod
    def untar(path, into=None):
        """Extract tarball at ``path`` into subdir ``into``.

        return subdir name if and only if there exists one, otherwise raise PathException
        """
        args = ('tar', '-C', into, '-xzf', path, '--no-same-permissions')
        subprocess.check_call(args, preexec_fn=lambda: os.umask(0o22))
        dirs = os.listdir(into)
        if len(dirs) == 1:
            return dirs[0]
        else:
            raise PathException('untar %s: expecting a single subdir, got %s' % (path, dirs))

    @staticmethod
    def tar(path, subdir, into=None, ts=None):
        """Pack ``path`` into tarball ``into``."""
        # --sort=name requires a recent build of GNU tar
        args = ['tar', '--numeric-owner', '--owner=0', '--group=0', '--sort=name']
        args += ['-C', path, '-cf', into, subdir]
        envs = os.environ.copy()
        if ts is not None:
            args.append('--mtime=@%d' % ts)
        if into.endswith('.xz'):
            envs['XZ_OPT'] = '-7e'
            args.append('-J')
        elif into.endswith('.bz2'):
            args.append('-j')
        elif into.endswith('.gz'):
            args.append('-z')
            envs['GZIP'] = '-n'
        else:
            raise PathException('unknown compression type %s' % into)
        subprocess.check_call(args, env=envs)


class GitHubCommitTsCache(object):
    __cachef = 'github.commit.ts.cache'
    __cachen = 2048

    def __init__(self):
        Path.mkdir_all(TMPDIR_DL)
        self.cachef = os.path.join(TMPDIR_DL, self.__cachef)
        self.cache = {}

    def get(self, k):
        """Get timestamp with key ``k``."""
        fileno = os.open(self.cachef, os.O_RDONLY | os.O_CREAT)
        with os.fdopen(fileno) as fin:
            try:
                fcntl.lockf(fileno, fcntl.LOCK_SH)
                self._cache_init(fin)
                if k in self.cache:
                    ts = self.cache[k][0]
                    return ts
            finally:
                fcntl.lockf(fileno, fcntl.LOCK_UN)
        return None

    def set(self, k, v):
        """Update timestamp with ``k``."""
        fileno = os.open(self.cachef, os.O_RDWR | os.O_CREAT)
        with os.fdopen(fileno, 'w+') as f:
            try:
                fcntl.lockf(fileno, fcntl.LOCK_EX)
                self._cache_init(f)
                self.cache[k] = (v, int(time.time()))
                self._cache_flush(f)
            finally:
                fcntl.lockf(fileno, fcntl.LOCK_UN)

    def _cache_init(self, fin):
        for line in fin:
            k, ts, updated = line.split()
            ts = int(ts)
            updated = int(updated)
            self.cache[k] = (ts, updated)

    def _cache_flush(self, fout):
        cache = sorted(self.cache.items(), key=lambda a: a[1][1])
        cache = cache[:self.__cachen]
        self.cache = {}
        os.ftruncate(fout.fileno(), 0)
        fout.seek(0, os.SEEK_SET)
        for k, ent in cache:
            ts = ent[0]
            updated = ent[1]
            line = '{0} {1} {2}\n'.format(k, ts, updated)
            fout.write(line)


class DownloadGitHubTarball(object):
    """Download and repack archive tarabll from GitHub.

    Compared with the method of packing after cloning the whole repo, this
    method is more friendly to users with fragile internet connection.

    However, there are limitations with this method

     - GitHub imposes a 60 reqs/hour limit for unauthenticated API access.
       This affects fetching commit date for reproducible tarballs.  Download
       through the archive link is not affected.

     - GitHub archives do not contain source codes for submodules.

     - GitHub archives seem to respect .gitattributes and ignore pathes with
       export-ignore attributes.

    For the first two issues, the method will fail loudly to allow fallback to
    clone-then-pack method.

    As for the 3rd issue, to make sure that this method only produces identical
    tarballs as the fallback method, we require the expected hash value to be
    supplied.  That means the first tarball will need to be prepared by the
    clone-then-pack method
    """

    __repo_url_regex = re.compile(r'^(?:https|git)://github.com/(?P<owner>[^/]+)/(?P<repo>[^/]+)')

    def __init__(self, args):
        self.dl_dir = args.dl_dir
        self.version = args.version
        self.subdir = args.subdir
        self.source = args.source
        self.url = args.url
        self._init_owner_repo()
        self.xhash = args.hash
        self._init_hasher()
        self.commit_ts = None           # lazy load commit timestamp
        self.commit_ts_cache = GitHubCommitTsCache()
        self.name = 'github-tarball'

    def download(self):
        """Download and repack GitHub archive tarball."""
        self._init_commit_ts()
        with Path(TMPDIR_DL, keep=True) as dir_dl:
            # fetch tarball from GitHub
            tarball_path = os.path.join(dir_dl.path, self.subdir + '.tar.gz.dl')
            with Path(tarball_path, isdir=False):
                self._fetch(tarball_path)
                # unpack
                d = os.path.join(dir_dl.path, self.subdir + '.untar')
                with Path(d, preclean=True) as dir_untar:
                    tarball_prefix = Path.untar(tarball_path, into=dir_untar.path)
                    dir0 = os.path.join(dir_untar.path, tarball_prefix)
                    dir1 = os.path.join(dir_untar.path, self.subdir)
                    # submodules check
                    if self._has_submodule(dir0):
                        raise self._error('Fetching submodules is not yet supported')
                    # rename subdir
                    os.rename(dir0, dir1)
                    # repack
                    into=os.path.join(TMPDIR_DL, self.source)
                    Path.tar(dir_untar.path, self.subdir, into=into, ts=self.commit_ts)
                    try:
                        self._hash_check(into)
                    except Exception:
                        Path.rm_all(into)
                        raise
                    # move to target location
                    file1 = os.path.join(self.dl_dir, self.source)
                    if into != file1:
                        shutil.move(into, file1)

    def _has_submodule(self, dir_):
        m = os.path.join(dir_, '.gitmodules')
        try:
            st = os.stat(m)
            return st.st_size > 0
        except OSError as e:
            return e.errno != errno.ENOENT

    def _init_owner_repo(self):
        m = self.__repo_url_regex.search(self.url)
        if m is None:
            raise self._error('Invalid github url: {}'.format(self.url))
        owner = m.group('owner')
        repo = m.group('repo')
        if repo.endswith('.git'):
            repo = repo[:-4]
        self.owner = owner
        self.repo = repo

    def _init_hasher(self):
        xhash = self.xhash
        if len(xhash) == 64:
            self.hasher = hashlib.sha256()
        elif len(xhash) == 32:
            self.hasher = hashlib.md5()
        else:
            raise self._error('Requires sha256sum for verification')
        self.xhash = xhash

    def _hash_check(self, f):
        with open(f, 'rb') as fin:
            while True:
                d = fin.read(4096)
                if not d:
                    break
                self.hasher.update(d)
        xhash = self.hasher.hexdigest()
        if xhash != self.xhash:
            raise self._error('Wrong hash (probably caused by .gitattributes), expecting {}, got {}'.format(self.xhash, xhash))

    def _init_commit_ts(self):
        if self.commit_ts is not None:
            return
        # GitHub provides 2 APIs[1,2] for fetching commit data.  API[1] is more
        # terse while API[2] provides more verbose info such as commit diff
        # etc.  That's the main reason why API[1] is preferred: the response
        # size is predictable.
        #
        # However, API[1] only accepts complete commit sha1sum as the parameter
        # while API[2] is more liberal accepting also partial commit id and
        # tags, etc.
        #
        # [1] Get a single commit, Repositories, https://developer.github.com/v3/repos/commits/#get-a-single-commit
        # [2] Git Commits, Git Data, https://developer.github.com/v3/git/commits/#get-a-commit
        apis = [
            {
                'url': self._make_repo_url_path('git', 'commits', self.version),
                'attr_path': ('committer', 'date'),
            }, {
                'url': self._make_repo_url_path('commits', self.version),
                'attr_path': ('commit', 'committer', 'date'),
            },
        ]
        version_is_sha1sum = len(self.version) == 40
        if not version_is_sha1sum:
            apis.insert(0, apis.pop())
        reasons = ''
        for api in apis:
            url = api['url']
            attr_path = api['attr_path']
            try:
                ct = self.commit_ts_cache.get(url)
                if ct is not None:
                    self.commit_ts = ct
                    return
                ct = self._init_commit_ts_remote_get(url, attr_path)
                self.commit_ts = ct
                self.commit_ts_cache.set(url, ct)
                return
            except Exception as e:
                reasons += '\n' + ("  {}: {}".format(url, e))
        raise self._error('Cannot fetch commit ts:{}'.format(reasons))

    def _init_commit_ts_remote_get(self, url, attrpath):
        resp = self._make_request(url)
        data = resp.read()
        date = json.loads(data)
        for attr in attrpath:
            date = date[attr]
        date = datetime.datetime.strptime(date, '%Y-%m-%dT%H:%M:%SZ')
        date = date.timetuple()
        ct = calendar.timegm(date)
        return ct

    def _fetch(self, path):
        """Fetch tarball of the specified version ref."""
        ref = self.version
        url = self._make_repo_url_path('tarball', ref)
        resp = self._make_request(url)
        with open(path, 'wb') as fout:
            while True:
                d = resp.read(4096)
                if not d:
                    break
                fout.write(d)

    def _make_repo_url_path(self, *args):
        url = '/repos/{0}/{1}'.format(self.owner, self.repo)
        if args:
            url += '/' + '/'.join(args)
        return url

    def _make_request(self, path):
        """Request GitHub API endpoint on ``path``."""
        url = 'https://api.github.com' + path
        headers = {
            'Accept': 'application/vnd.github.v3+json',
            'User-Agent': 'OpenWrt',
        }
        req = urllib.request.Request(url, headers=headers)
        sslcontext = ssl._create_unverified_context()
        fileobj = urllib.request.urlopen(req, context=sslcontext)
        return fileobj

    def _error(self, msg):
        return DownloadGitHubError('{}: {}'.format(self.source, msg))


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--dl-dir', default=os.getcwd(), help='Download dir')
    parser.add_argument('--url', help='Download URL')
    parser.add_argument('--subdir', help='Source code subdir name')
    parser.add_argument('--version', help='Source code version')
    parser.add_argument('--source', help='Source tarball filename')
    parser.add_argument('--hash', help='Source tarball\'s expected sha256sum')
    args = parser.parse_args()
    try:
        method = DownloadGitHubTarball(args)
        method.download()
    except Exception as ex:
        sys.stderr.write('{}: Download from {} failed\n'.format(args.source, args.url))
        sys.stderr.write('{}\n'.format(ex))
        sys.exit(1)

if __name__ == '__main__':
    main()