From d8399752e65143c131f1fa751c0b71f22b8eccd2 Mon Sep 17 00:00:00 2001 From: poocka Date: Thu, 10 Oct 2019 17:00:59 +0300 Subject: [PATCH] SSDP sender and Hardware Sensors are added --- lib/data/ssdp/queue.h | 533 +++++ lib/data/ssdp/ssdp.h | 50 + lib/data/ssdp/ssdpd.c | 901 ++++++++ lib/data/ssdp/web.c | 216 ++ .../adns3080/ADNS3080Demo/ADNS3080.h | 50 + .../adns3080/ADNS3080Demo/ADNS3080Demo.pde | 389 ++++ .../ADNS3080Demo/ADNS3080ImageGrabber.py | 180 ++ .../adns3080/ADNS3080Demo/README.txt | 24 + .../ADNS3080ImageGrabber.py | 180 ++ .../adns3080/ADNS3080ImageGrabber/README.txt | 11 + .../adns3080/ADNS3080_I2C/ADNS3080.h | 50 + .../adns3080/ADNS3080_I2C/ADNS3080_I2C.pde | 388 ++++ .../adns3080/LPC_ADNS3080/ADNS3080.h | 55 + .../adns3080/LPC_ADNS3080/LPC_ADNS3080.dep | 214 ++ .../adns3080/LPC_ADNS3080/LPC_ADNS3080.ewp | 1849 +++++++++++++++++ .../adns3080/LPC_ADNS3080/LPC_ADNS3080.eww | 10 + .../LPC_ADNS3080/config/LPC2103_Flash.icf | 50 + .../LPC_ADNS3080/config/LPC2103_RAM.icf | 45 + .../LPC_ADNS3080/config/LPC2103_RAM.mac | 4 + .../optic_flow/adns3080/LPC_ADNS3080/delay.c | 30 + .../optic_flow/adns3080/LPC_ADNS3080/delay.h | 7 + .../adns3080/LPC_ADNS3080/digital.c | 24 + .../adns3080/LPC_ADNS3080/digital.h | 7 + .../optic_flow/adns3080/LPC_ADNS3080/main.c | 168 ++ .../optic_flow/adns3080/LPC_ADNS3080/serial.c | 178 ++ .../optic_flow/adns3080/LPC_ADNS3080/serial.h | 13 + .../settings/LPC_ADNS3080.cspy.bat | 15 + .../LPC_ADNS3080/settings/LPC_ADNS3080.dbgdt | 5 + .../LPC_ADNS3080/settings/LPC_ADNS3080.dni | 36 + .../LPC_ADNS3080/settings/LPC_ADNS3080.wsdt | 221 ++ .../optic_flow/adns3080/LPC_ADNS3080/spi.c | 44 + .../optic_flow/adns3080/LPC_ADNS3080/spi.h | 7 + .../optic_flow/adns3080/LPC_ADNS3080/types.h | 13 + .../sensors/optic_flow/adns3080/README.md | 6 + 34 files changed, 5973 insertions(+) create mode 100644 lib/data/ssdp/queue.h create mode 100644 lib/data/ssdp/ssdp.h create mode 100644 lib/data/ssdp/ssdpd.c create mode 100644 lib/data/ssdp/web.c create mode 100644 lib/hardware/sensors/optic_flow/adns3080/ADNS3080Demo/ADNS3080.h create mode 100644 lib/hardware/sensors/optic_flow/adns3080/ADNS3080Demo/ADNS3080Demo.pde create mode 100644 lib/hardware/sensors/optic_flow/adns3080/ADNS3080Demo/ADNS3080ImageGrabber.py create mode 100644 lib/hardware/sensors/optic_flow/adns3080/ADNS3080Demo/README.txt create mode 100644 lib/hardware/sensors/optic_flow/adns3080/ADNS3080ImageGrabber/ADNS3080ImageGrabber.py create mode 100644 lib/hardware/sensors/optic_flow/adns3080/ADNS3080ImageGrabber/README.txt create mode 100644 lib/hardware/sensors/optic_flow/adns3080/ADNS3080_I2C/ADNS3080.h create mode 100644 lib/hardware/sensors/optic_flow/adns3080/ADNS3080_I2C/ADNS3080_I2C.pde create mode 100644 lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/ADNS3080.h create mode 100644 lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/LPC_ADNS3080.dep create mode 100644 lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/LPC_ADNS3080.ewp create mode 100644 lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/LPC_ADNS3080.eww create mode 100644 lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/config/LPC2103_Flash.icf create mode 100644 lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/config/LPC2103_RAM.icf create mode 100644 lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/config/LPC2103_RAM.mac create mode 100644 lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/delay.c create mode 100644 lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/delay.h create mode 100644 lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/digital.c create mode 100644 lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/digital.h create mode 100644 lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/main.c create mode 100644 lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/serial.c create mode 100644 lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/serial.h create mode 100644 lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/settings/LPC_ADNS3080.cspy.bat create mode 100644 lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/settings/LPC_ADNS3080.dbgdt create mode 100644 lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/settings/LPC_ADNS3080.dni create mode 100644 lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/settings/LPC_ADNS3080.wsdt create mode 100644 lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/spi.c create mode 100644 lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/spi.h create mode 100644 lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/types.h create mode 100644 lib/hardware/sensors/optic_flow/adns3080/README.md diff --git a/lib/data/ssdp/queue.h b/lib/data/ssdp/queue.h new file mode 100644 index 00000000..5e81fdd1 --- /dev/null +++ b/lib/data/ssdp/queue.h @@ -0,0 +1,533 @@ +/* $OpenBSD: queue.h,v 1.43 2015/12/28 19:38:40 millert Exp $ */ +/* $NetBSD: queue.h,v 1.11 1996/05/16 05:17:14 mycroft Exp $ */ + +/* + * Copyright (c) 1991, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)queue.h 8.5 (Berkeley) 8/20/94 + */ + +#ifndef _SYS_QUEUE_H_ +#define _SYS_QUEUE_H_ + +/* + * This file defines five types of data structures: singly-linked lists, + * lists, simple queues, tail queues and XOR simple queues. + * + * + * A singly-linked list is headed by a single forward pointer. The elements + * are singly linked for minimum space and pointer manipulation overhead at + * the expense of O(n) removal for arbitrary elements. New elements can be + * added to the list after an existing element or at the head of the list. + * Elements being removed from the head of the list should use the explicit + * macro for this purpose for optimum efficiency. A singly-linked list may + * only be traversed in the forward direction. Singly-linked lists are ideal + * for applications with large datasets and few or no removals or for + * implementing a LIFO queue. + * + * A list is headed by a single forward pointer (or an array of forward + * pointers for a hash table header). The elements are doubly linked + * so that an arbitrary element can be removed without a need to + * traverse the list. New elements can be added to the list before + * or after an existing element or at the head of the list. A list + * may only be traversed in the forward direction. + * + * A simple queue is headed by a pair of pointers, one to the head of the + * list and the other to the tail of the list. The elements are singly + * linked to save space, so elements can only be removed from the + * head of the list. New elements can be added to the list before or after + * an existing element, at the head of the list, or at the end of the + * list. A simple queue may only be traversed in the forward direction. + * + * A tail queue is headed by a pair of pointers, one to the head of the + * list and the other to the tail of the list. The elements are doubly + * linked so that an arbitrary element can be removed without a need to + * traverse the list. New elements can be added to the list before or + * after an existing element, at the head of the list, or at the end of + * the list. A tail queue may be traversed in either direction. + * + * An XOR simple queue is used in the same way as a regular simple queue. + * The difference is that the head structure also includes a "cookie" that + * is XOR'd with the queue pointer (first, last or next) to generate the + * real pointer value. + * + * For details on the use of these macros, see the queue(3) manual page. + */ + +#if defined(QUEUE_MACRO_DEBUG) || (defined(_KERNEL) && defined(DIAGNOSTIC)) +#define _Q_INVALIDATE(a) (a) = ((void *)-1) +#else +#define _Q_INVALIDATE(a) +#endif + +/* + * Singly-linked List definitions. + */ +#define SLIST_HEAD(name, type) \ +struct name { \ + struct type *slh_first; /* first element */ \ +} + +#define SLIST_HEAD_INITIALIZER(head) \ + { NULL } + +#define SLIST_ENTRY(type) \ +struct { \ + struct type *sle_next; /* next element */ \ +} + +/* + * Singly-linked List access methods. + */ +#define SLIST_FIRST(head) ((head)->slh_first) +#define SLIST_END(head) NULL +#define SLIST_EMPTY(head) (SLIST_FIRST(head) == SLIST_END(head)) +#define SLIST_NEXT(elm, field) ((elm)->field.sle_next) + +#define SLIST_FOREACH(var, head, field) \ + for((var) = SLIST_FIRST(head); \ + (var) != SLIST_END(head); \ + (var) = SLIST_NEXT(var, field)) + +#define SLIST_FOREACH_SAFE(var, head, field, tvar) \ + for ((var) = SLIST_FIRST(head); \ + (var) && ((tvar) = SLIST_NEXT(var, field), 1); \ + (var) = (tvar)) + +/* + * Singly-linked List functions. + */ +#define SLIST_INIT(head) { \ + SLIST_FIRST(head) = SLIST_END(head); \ +} + +#define SLIST_INSERT_AFTER(slistelm, elm, field) do { \ + (elm)->field.sle_next = (slistelm)->field.sle_next; \ + (slistelm)->field.sle_next = (elm); \ +} while (0) + +#define SLIST_INSERT_HEAD(head, elm, field) do { \ + (elm)->field.sle_next = (head)->slh_first; \ + (head)->slh_first = (elm); \ +} while (0) + +#define SLIST_REMOVE_AFTER(elm, field) do { \ + (elm)->field.sle_next = (elm)->field.sle_next->field.sle_next; \ +} while (0) + +#define SLIST_REMOVE_HEAD(head, field) do { \ + (head)->slh_first = (head)->slh_first->field.sle_next; \ +} while (0) + +#define SLIST_REMOVE(head, elm, type, field) do { \ + if ((head)->slh_first == (elm)) { \ + SLIST_REMOVE_HEAD((head), field); \ + } else { \ + struct type *curelm = (head)->slh_first; \ + \ + while (curelm->field.sle_next != (elm)) \ + curelm = curelm->field.sle_next; \ + curelm->field.sle_next = \ + curelm->field.sle_next->field.sle_next; \ + } \ + _Q_INVALIDATE((elm)->field.sle_next); \ +} while (0) + +/* + * List definitions. + */ +#define LIST_HEAD(name, type) \ +struct name { \ + struct type *lh_first; /* first element */ \ +} + +#define LIST_HEAD_INITIALIZER(head) \ + { NULL } + +#define LIST_ENTRY(type) \ +struct { \ + struct type *le_next; /* next element */ \ + struct type **le_prev; /* address of previous next element */ \ +} + +/* + * List access methods. + */ +#define LIST_FIRST(head) ((head)->lh_first) +#define LIST_END(head) NULL +#define LIST_EMPTY(head) (LIST_FIRST(head) == LIST_END(head)) +#define LIST_NEXT(elm, field) ((elm)->field.le_next) + +#define LIST_FOREACH(var, head, field) \ + for((var) = LIST_FIRST(head); \ + (var)!= LIST_END(head); \ + (var) = LIST_NEXT(var, field)) + +#define LIST_FOREACH_SAFE(var, head, field, tvar) \ + for ((var) = LIST_FIRST(head); \ + (var) && ((tvar) = LIST_NEXT(var, field), 1); \ + (var) = (tvar)) + +/* + * List functions. + */ +#define LIST_INIT(head) do { \ + LIST_FIRST(head) = LIST_END(head); \ +} while (0) + +#define LIST_INSERT_AFTER(listelm, elm, field) do { \ + if (((elm)->field.le_next = (listelm)->field.le_next) != NULL) \ + (listelm)->field.le_next->field.le_prev = \ + &(elm)->field.le_next; \ + (listelm)->field.le_next = (elm); \ + (elm)->field.le_prev = &(listelm)->field.le_next; \ +} while (0) + +#define LIST_INSERT_BEFORE(listelm, elm, field) do { \ + (elm)->field.le_prev = (listelm)->field.le_prev; \ + (elm)->field.le_next = (listelm); \ + *(listelm)->field.le_prev = (elm); \ + (listelm)->field.le_prev = &(elm)->field.le_next; \ +} while (0) + +#define LIST_INSERT_HEAD(head, elm, field) do { \ + if (((elm)->field.le_next = (head)->lh_first) != NULL) \ + (head)->lh_first->field.le_prev = &(elm)->field.le_next;\ + (head)->lh_first = (elm); \ + (elm)->field.le_prev = &(head)->lh_first; \ +} while (0) + +#define LIST_REMOVE(elm, field) do { \ + if ((elm)->field.le_next != NULL) \ + (elm)->field.le_next->field.le_prev = \ + (elm)->field.le_prev; \ + *(elm)->field.le_prev = (elm)->field.le_next; \ + _Q_INVALIDATE((elm)->field.le_prev); \ + _Q_INVALIDATE((elm)->field.le_next); \ +} while (0) + +#define LIST_REPLACE(elm, elm2, field) do { \ + if (((elm2)->field.le_next = (elm)->field.le_next) != NULL) \ + (elm2)->field.le_next->field.le_prev = \ + &(elm2)->field.le_next; \ + (elm2)->field.le_prev = (elm)->field.le_prev; \ + *(elm2)->field.le_prev = (elm2); \ + _Q_INVALIDATE((elm)->field.le_prev); \ + _Q_INVALIDATE((elm)->field.le_next); \ +} while (0) + +/* + * Simple queue definitions. + */ +#define SIMPLEQ_HEAD(name, type) \ +struct name { \ + struct type *sqh_first; /* first element */ \ + struct type **sqh_last; /* addr of last next element */ \ +} + +#define SIMPLEQ_HEAD_INITIALIZER(head) \ + { NULL, &(head).sqh_first } + +#define SIMPLEQ_ENTRY(type) \ +struct { \ + struct type *sqe_next; /* next element */ \ +} + +/* + * Simple queue access methods. + */ +#define SIMPLEQ_FIRST(head) ((head)->sqh_first) +#define SIMPLEQ_END(head) NULL +#define SIMPLEQ_EMPTY(head) (SIMPLEQ_FIRST(head) == SIMPLEQ_END(head)) +#define SIMPLEQ_NEXT(elm, field) ((elm)->field.sqe_next) + +#define SIMPLEQ_FOREACH(var, head, field) \ + for((var) = SIMPLEQ_FIRST(head); \ + (var) != SIMPLEQ_END(head); \ + (var) = SIMPLEQ_NEXT(var, field)) + +#define SIMPLEQ_FOREACH_SAFE(var, head, field, tvar) \ + for ((var) = SIMPLEQ_FIRST(head); \ + (var) && ((tvar) = SIMPLEQ_NEXT(var, field), 1); \ + (var) = (tvar)) + +/* + * Simple queue functions. + */ +#define SIMPLEQ_INIT(head) do { \ + (head)->sqh_first = NULL; \ + (head)->sqh_last = &(head)->sqh_first; \ +} while (0) + +#define SIMPLEQ_INSERT_HEAD(head, elm, field) do { \ + if (((elm)->field.sqe_next = (head)->sqh_first) == NULL) \ + (head)->sqh_last = &(elm)->field.sqe_next; \ + (head)->sqh_first = (elm); \ +} while (0) + +#define SIMPLEQ_INSERT_TAIL(head, elm, field) do { \ + (elm)->field.sqe_next = NULL; \ + *(head)->sqh_last = (elm); \ + (head)->sqh_last = &(elm)->field.sqe_next; \ +} while (0) + +#define SIMPLEQ_INSERT_AFTER(head, listelm, elm, field) do { \ + if (((elm)->field.sqe_next = (listelm)->field.sqe_next) == NULL)\ + (head)->sqh_last = &(elm)->field.sqe_next; \ + (listelm)->field.sqe_next = (elm); \ +} while (0) + +#define SIMPLEQ_REMOVE_HEAD(head, field) do { \ + if (((head)->sqh_first = (head)->sqh_first->field.sqe_next) == NULL) \ + (head)->sqh_last = &(head)->sqh_first; \ +} while (0) + +#define SIMPLEQ_REMOVE_AFTER(head, elm, field) do { \ + if (((elm)->field.sqe_next = (elm)->field.sqe_next->field.sqe_next) \ + == NULL) \ + (head)->sqh_last = &(elm)->field.sqe_next; \ +} while (0) + +#define SIMPLEQ_CONCAT(head1, head2) do { \ + if (!SIMPLEQ_EMPTY((head2))) { \ + *(head1)->sqh_last = (head2)->sqh_first; \ + (head1)->sqh_last = (head2)->sqh_last; \ + SIMPLEQ_INIT((head2)); \ + } \ +} while (0) + +/* + * XOR Simple queue definitions. + */ +#define XSIMPLEQ_HEAD(name, type) \ +struct name { \ + struct type *sqx_first; /* first element */ \ + struct type **sqx_last; /* addr of last next element */ \ + unsigned long sqx_cookie; \ +} + +#define XSIMPLEQ_ENTRY(type) \ +struct { \ + struct type *sqx_next; /* next element */ \ +} + +/* + * XOR Simple queue access methods. + */ +#define XSIMPLEQ_XOR(head, ptr) ((__typeof(ptr))((head)->sqx_cookie ^ \ + (unsigned long)(ptr))) +#define XSIMPLEQ_FIRST(head) XSIMPLEQ_XOR(head, ((head)->sqx_first)) +#define XSIMPLEQ_END(head) NULL +#define XSIMPLEQ_EMPTY(head) (XSIMPLEQ_FIRST(head) == XSIMPLEQ_END(head)) +#define XSIMPLEQ_NEXT(head, elm, field) XSIMPLEQ_XOR(head, ((elm)->field.sqx_next)) + + +#define XSIMPLEQ_FOREACH(var, head, field) \ + for ((var) = XSIMPLEQ_FIRST(head); \ + (var) != XSIMPLEQ_END(head); \ + (var) = XSIMPLEQ_NEXT(head, var, field)) + +#define XSIMPLEQ_FOREACH_SAFE(var, head, field, tvar) \ + for ((var) = XSIMPLEQ_FIRST(head); \ + (var) && ((tvar) = XSIMPLEQ_NEXT(head, var, field), 1); \ + (var) = (tvar)) + +/* + * XOR Simple queue functions. + */ +#define XSIMPLEQ_INIT(head) do { \ + arc4random_buf(&(head)->sqx_cookie, sizeof((head)->sqx_cookie)); \ + (head)->sqx_first = XSIMPLEQ_XOR(head, NULL); \ + (head)->sqx_last = XSIMPLEQ_XOR(head, &(head)->sqx_first); \ +} while (0) + +#define XSIMPLEQ_INSERT_HEAD(head, elm, field) do { \ + if (((elm)->field.sqx_next = (head)->sqx_first) == \ + XSIMPLEQ_XOR(head, NULL)) \ + (head)->sqx_last = XSIMPLEQ_XOR(head, &(elm)->field.sqx_next); \ + (head)->sqx_first = XSIMPLEQ_XOR(head, (elm)); \ +} while (0) + +#define XSIMPLEQ_INSERT_TAIL(head, elm, field) do { \ + (elm)->field.sqx_next = XSIMPLEQ_XOR(head, NULL); \ + *(XSIMPLEQ_XOR(head, (head)->sqx_last)) = XSIMPLEQ_XOR(head, (elm)); \ + (head)->sqx_last = XSIMPLEQ_XOR(head, &(elm)->field.sqx_next); \ +} while (0) + +#define XSIMPLEQ_INSERT_AFTER(head, listelm, elm, field) do { \ + if (((elm)->field.sqx_next = (listelm)->field.sqx_next) == \ + XSIMPLEQ_XOR(head, NULL)) \ + (head)->sqx_last = XSIMPLEQ_XOR(head, &(elm)->field.sqx_next); \ + (listelm)->field.sqx_next = XSIMPLEQ_XOR(head, (elm)); \ +} while (0) + +#define XSIMPLEQ_REMOVE_HEAD(head, field) do { \ + if (((head)->sqx_first = XSIMPLEQ_XOR(head, \ + (head)->sqx_first)->field.sqx_next) == XSIMPLEQ_XOR(head, NULL)) \ + (head)->sqx_last = XSIMPLEQ_XOR(head, &(head)->sqx_first); \ +} while (0) + +#define XSIMPLEQ_REMOVE_AFTER(head, elm, field) do { \ + if (((elm)->field.sqx_next = XSIMPLEQ_XOR(head, \ + (elm)->field.sqx_next)->field.sqx_next) \ + == XSIMPLEQ_XOR(head, NULL)) \ + (head)->sqx_last = \ + XSIMPLEQ_XOR(head, &(elm)->field.sqx_next); \ +} while (0) + + +/* + * Tail queue definitions. + */ +#define TAILQ_HEAD(name, type) \ +struct name { \ + struct type *tqh_first; /* first element */ \ + struct type **tqh_last; /* addr of last next element */ \ +} + +#define TAILQ_HEAD_INITIALIZER(head) \ + { NULL, &(head).tqh_first } + +#define TAILQ_ENTRY(type) \ +struct { \ + struct type *tqe_next; /* next element */ \ + struct type **tqe_prev; /* address of previous next element */ \ +} + +/* + * Tail queue access methods. + */ +#define TAILQ_FIRST(head) ((head)->tqh_first) +#define TAILQ_END(head) NULL +#define TAILQ_NEXT(elm, field) ((elm)->field.tqe_next) +#define TAILQ_LAST(head, headname) \ + (*(((struct headname *)((head)->tqh_last))->tqh_last)) +/* XXX */ +#define TAILQ_PREV(elm, headname, field) \ + (*(((struct headname *)((elm)->field.tqe_prev))->tqh_last)) +#define TAILQ_EMPTY(head) \ + (TAILQ_FIRST(head) == TAILQ_END(head)) + +#define TAILQ_FOREACH(var, head, field) \ + for((var) = TAILQ_FIRST(head); \ + (var) != TAILQ_END(head); \ + (var) = TAILQ_NEXT(var, field)) + +#define TAILQ_FOREACH_SAFE(var, head, field, tvar) \ + for ((var) = TAILQ_FIRST(head); \ + (var) != TAILQ_END(head) && \ + ((tvar) = TAILQ_NEXT(var, field), 1); \ + (var) = (tvar)) + + +#define TAILQ_FOREACH_REVERSE(var, head, headname, field) \ + for((var) = TAILQ_LAST(head, headname); \ + (var) != TAILQ_END(head); \ + (var) = TAILQ_PREV(var, headname, field)) + +#define TAILQ_FOREACH_REVERSE_SAFE(var, head, headname, field, tvar) \ + for ((var) = TAILQ_LAST(head, headname); \ + (var) != TAILQ_END(head) && \ + ((tvar) = TAILQ_PREV(var, headname, field), 1); \ + (var) = (tvar)) + +/* + * Tail queue functions. + */ +#define TAILQ_INIT(head) do { \ + (head)->tqh_first = NULL; \ + (head)->tqh_last = &(head)->tqh_first; \ +} while (0) + +#define TAILQ_INSERT_HEAD(head, elm, field) do { \ + if (((elm)->field.tqe_next = (head)->tqh_first) != NULL) \ + (head)->tqh_first->field.tqe_prev = \ + &(elm)->field.tqe_next; \ + else \ + (head)->tqh_last = &(elm)->field.tqe_next; \ + (head)->tqh_first = (elm); \ + (elm)->field.tqe_prev = &(head)->tqh_first; \ +} while (0) + +#define TAILQ_INSERT_TAIL(head, elm, field) do { \ + (elm)->field.tqe_next = NULL; \ + (elm)->field.tqe_prev = (head)->tqh_last; \ + *(head)->tqh_last = (elm); \ + (head)->tqh_last = &(elm)->field.tqe_next; \ +} while (0) + +#define TAILQ_INSERT_AFTER(head, listelm, elm, field) do { \ + if (((elm)->field.tqe_next = (listelm)->field.tqe_next) != NULL)\ + (elm)->field.tqe_next->field.tqe_prev = \ + &(elm)->field.tqe_next; \ + else \ + (head)->tqh_last = &(elm)->field.tqe_next; \ + (listelm)->field.tqe_next = (elm); \ + (elm)->field.tqe_prev = &(listelm)->field.tqe_next; \ +} while (0) + +#define TAILQ_INSERT_BEFORE(listelm, elm, field) do { \ + (elm)->field.tqe_prev = (listelm)->field.tqe_prev; \ + (elm)->field.tqe_next = (listelm); \ + *(listelm)->field.tqe_prev = (elm); \ + (listelm)->field.tqe_prev = &(elm)->field.tqe_next; \ +} while (0) + +#define TAILQ_REMOVE(head, elm, field) do { \ + if (((elm)->field.tqe_next) != NULL) \ + (elm)->field.tqe_next->field.tqe_prev = \ + (elm)->field.tqe_prev; \ + else \ + (head)->tqh_last = (elm)->field.tqe_prev; \ + *(elm)->field.tqe_prev = (elm)->field.tqe_next; \ + _Q_INVALIDATE((elm)->field.tqe_prev); \ + _Q_INVALIDATE((elm)->field.tqe_next); \ +} while (0) + +#define TAILQ_REPLACE(head, elm, elm2, field) do { \ + if (((elm2)->field.tqe_next = (elm)->field.tqe_next) != NULL) \ + (elm2)->field.tqe_next->field.tqe_prev = \ + &(elm2)->field.tqe_next; \ + else \ + (head)->tqh_last = &(elm2)->field.tqe_next; \ + (elm2)->field.tqe_prev = (elm)->field.tqe_prev; \ + *(elm2)->field.tqe_prev = (elm2); \ + _Q_INVALIDATE((elm)->field.tqe_prev); \ + _Q_INVALIDATE((elm)->field.tqe_next); \ +} while (0) + +#define TAILQ_CONCAT(head1, head2, field) do { \ + if (!TAILQ_EMPTY(head2)) { \ + *(head1)->tqh_last = (head2)->tqh_first; \ + (head2)->tqh_first->field.tqe_prev = (head1)->tqh_last; \ + (head1)->tqh_last = (head2)->tqh_last; \ + TAILQ_INIT((head2)); \ + } \ +} while (0) + +#endif /* !_SYS_QUEUE_H_ */ diff --git a/lib/data/ssdp/ssdp.h b/lib/data/ssdp/ssdp.h new file mode 100644 index 00000000..0d855a5f --- /dev/null +++ b/lib/data/ssdp/ssdp.h @@ -0,0 +1,50 @@ +/* SSDP responder + * + * Copyright (c) 2017 Joachim Nilsson + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND 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, DIRECT, 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.a + */ +#ifndef SSDP_H_ +#define SSDP_H_ + +#include + +/* Notify should be less than half the cache timeout */ +#define NOTIFY_INTERVAL 300 +#define REFRESH_INTERVAL 600 +#define CACHE_TIMEOUT 1800 +#define MAX_NUM_IFACES 100 +#define MAX_PKT_SIZE 2000 +#define MC_SSDP_GROUP "239.255.255.250" +#define MC_SSDP_PORT 1900 +#define LOCATION_PORT (MC_SSDP_PORT + 1) +#define LOCATION_DESC "/description.xml" + +#define SSDP_ST_ALL "ssdp:all" + +#define logit(lvl, fmt, args...) syslog(lvl, fmt, ##args) + +#define ENABLE_SOCKOPT(sd, level, opt) \ + do { \ + int val = 1; \ + if (setsockopt(sd, level, opt, &val, sizeof(val)) < 0) \ + warn("Failed enabling %s for web service", #opt); \ + } while (0); + +extern int debug; +extern char uuid[]; + +void web_init(void); +int register_socket(int in, int out, struct sockaddr *addr, struct sockaddr *mask, void (*cb)(int sd)); + +#endif /* SSDP_H_ */ diff --git a/lib/data/ssdp/ssdpd.c b/lib/data/ssdp/ssdpd.c new file mode 100644 index 00000000..f6a12973 --- /dev/null +++ b/lib/data/ssdp/ssdpd.c @@ -0,0 +1,901 @@ +/* SSDP responder + * + * Copyright (c) 2017 Joachim Nilsson + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND 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, DIRECT, 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.a + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include /* MIN() */ +#include + +#include "ssdp.h" +#include "queue.h" + +struct ifsock { + LIST_ENTRY(ifsock) link; + + int stale; + int mod; + + /* + * Sockets for inbound and outbound + * + * - The inbound is the multicast socket, shared between all ifaces + * - The outbound is bound to the iface address and a random port + */ + int in, out; + + /* Interface address and netmask */ + struct sockaddr_in addr; + struct sockaddr_in mask; + + void (*cb)(int); +}; + +LIST_HEAD(, ifsock) il = LIST_HEAD_INITIALIZER(); + +static char *supported_types[] = { + SSDP_ST_ALL, + "upnp:rootdevice", + "urn:schemas-upnp-org:device:InternetGatewayDevice:1", + uuid, + NULL +}; + +int debug = 0; +int running = 1; + +char uuid[42]; +char hostname[64]; +char *os = NULL, *ver = NULL; +char server_string[64] = "POSIX UPnP/1.0 " PACKAGE_NAME "/" PACKAGE_VERSION; + +/* Find interface in same subnet as sa */ +static struct ifsock *find_outbound(struct sockaddr *sa) +{ + in_addr_t cand; + struct ifsock *ifs; + struct sockaddr_in *addr = (struct sockaddr_in *)sa; + + cand = addr->sin_addr.s_addr; + LIST_FOREACH(ifs, &il, link) { + in_addr_t a, m; + + a = ifs->addr.sin_addr.s_addr; + m = ifs->mask.sin_addr.s_addr; + if (a == htonl(INADDR_ANY) || m == htonl(INADDR_ANY)) + continue; + + if ((a & m) == (cand & m)) + return ifs; + } + + return NULL; +} + +/* Exact match, must be same ifaddr as sa */ +static struct ifsock *find_iface(struct sockaddr *sa) +{ + struct ifsock *ifs; + struct sockaddr_in *addr = (struct sockaddr_in *)sa; + + if (!sa) + return NULL; + + LIST_FOREACH(ifs, &il, link) { + if (ifs->addr.sin_addr.s_addr == addr->sin_addr.s_addr) + return ifs; + } + + return NULL; +} + +int register_socket(int in, int out, struct sockaddr *addr, struct sockaddr *mask, void (*cb)(int sd)) +{ + struct ifsock *ifs; + struct sockaddr_in *address = (struct sockaddr_in *)addr; + struct sockaddr_in *netmask = (struct sockaddr_in *)mask; + + ifs = calloc(1, sizeof(*ifs)); + if (!ifs) { + char *host = inet_ntoa(address->sin_addr); + + logit(LOG_ERR, "Failed registering host %s socket: %s", host, strerror(errno)); + return -1; + } + + ifs->in = in; + ifs->out = out; + ifs->mod = 1; + ifs->cb = cb; + ifs->addr = *address; + if (mask) + ifs->mask = *netmask; + LIST_INSERT_HEAD(&il, ifs, link); + + return 0; +} + +static int open_socket(char *ifname, struct sockaddr *addr, int port) +{ + int sd, val, rc; + char loop; + struct ip_mreqn mreq; + struct sockaddr_in sin, *address = (struct sockaddr_in *)addr; + + sd = socket(AF_INET, SOCK_DGRAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0); + if (sd < 0) + return -1; + + sin.sin_family = AF_INET; + sin.sin_port = htons(port); + sin.sin_addr = address->sin_addr; + if (bind(sd, (struct sockaddr *)&sin, sizeof(sin)) < 0) { + close(sd); + logit(LOG_ERR, "Failed binding to %s:%d: %s", inet_ntoa(address->sin_addr), port, strerror(errno)); + return -1; + } +#if 0 + ENABLE_SOCKOPT(sd, SOL_SOCKET, SO_REUSEADDR); +#ifdef SO_REUSEPORT + ENABLE_SOCKOPT(sd, SOL_SOCKET, SO_REUSEPORT); +#endif +#endif + memset(&mreq, 0, sizeof(mreq)); + mreq.imr_address = address->sin_addr; + mreq.imr_multiaddr.s_addr = inet_addr(MC_SSDP_GROUP); + if (setsockopt(sd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq))) { + close(sd); + logit(LOG_ERR, "Failed joining group %s: %s", MC_SSDP_GROUP, strerror(errno)); + return -1; + } + + val = 2; /* Default 2, but should be configurable */ + rc = setsockopt(sd, IPPROTO_IP, IP_MULTICAST_TTL, &val, sizeof(val)); + if (rc < 0) { + close(sd); + logit(LOG_ERR, "Failed setting multicast TTL: %s", strerror(errno)); + return -1; + } + + loop = 0; + rc = setsockopt(sd, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop)); + if (rc < 0) { + close(sd); + logit(LOG_ERR, "Failed disabing multicast loop: %s", strerror(errno)); + return -1; + } + + rc = setsockopt(sd, IPPROTO_IP, IP_MULTICAST_IF, &address->sin_addr, sizeof(address->sin_addr)); + if (rc < 0) { + close(sd); + logit(LOG_ERR, "Failed setting multicast interface: %s", strerror(errno)); + return -1; + } + + logit(LOG_DEBUG, "Adding new interface %s with address %s", ifname, inet_ntoa(address->sin_addr)); + + return sd; +} + +static int close_socket(void) +{ + int ret = 0; + struct ifsock *ifs, *tmp; + + LIST_FOREACH_SAFE(ifs, &il, link, tmp) { + LIST_REMOVE(ifs, link); + if (ifs->out != -1) + ret |= close(ifs->out); + else + ret |= close(ifs->in); + free(ifs); + } + + return ret; +} + +static int filter_addr(struct sockaddr *sa) +{ + struct ifsock *ifs; + struct sockaddr_in *sin = (struct sockaddr_in *)sa; + + if (!sa) + return 1; + + if (sa->sa_family != AF_INET) + return 1; + + if (sin->sin_addr.s_addr == htonl(INADDR_ANY)) + return 1; + + if (sin->sin_addr.s_addr == htonl(INADDR_LOOPBACK)) + return 1; + + ifs = find_outbound(sa); + if (ifs) { + if (ifs->addr.sin_addr.s_addr != htonl(INADDR_ANY)) + return 1; + } + + return 0; +} + +static int filter_iface(char *ifname, char *iflist[], size_t num) +{ + size_t i; + + if (!num) { + logit(LOG_DEBUG, "No interfaces to filter, using all with an IP address."); + return 0; + } + + logit(LOG_DEBUG, "Filter %s? Comparing %zd entries ...", ifname, num); + for (i = 0; i < num; i++) { + logit(LOG_DEBUG, "Filter %s? Comparing with %s ...", ifname, iflist[i]); + if (!strcmp(ifname, iflist[i])) + return 0; + } + + return 1; +} + +static void compose_addr(struct sockaddr_in *sin, char *group, int port) +{ + memset(sin, 0, sizeof(*sin)); + sin->sin_family = AF_INET; + sin->sin_port = htons(port); + sin->sin_addr.s_addr = inet_addr(group); +} + +static void compose_response(char *type, char *host, char *buf, size_t len) +{ + char usn[256]; + char date[42]; + time_t now; + + /* RFC1123 date, as specified in RFC2616 */ + now = time(NULL); + strftime(date, sizeof(date), "%a, %d %b %Y %T %Z", gmtime(&now)); + + if (type) { + if (!strcmp(type, uuid)) + type = NULL; + else + snprintf(usn, sizeof(usn), "%s::%s", uuid, type); + } + + if (!type) + strncpy(usn, uuid, sizeof(usn)); + + snprintf(buf, len, "HTTP/1.1 200 OK\r\n" + "Server: %s\r\n" + "Date: %s\r\n" + "Location: http://%s:%d%s\r\n" + "ST: %s\r\n" + "EXT: \r\n" + "USN: %s\r\n" + "Cache-Control: max-age=%d\r\n" + "\r\n", + server_string, + date, + host, LOCATION_PORT, LOCATION_DESC, + type, + usn, + CACHE_TIMEOUT); +} + +static void compose_search(char *type, char *buf, size_t len) +{ + snprintf(buf, len, "M-SEARCH * HTTP/1.1\r\n" + "Host: %s:%d\r\n" + "MAN: \"ssdp:discover\"\r\n" + "MX: 1\r\n" + "ST: %s\r\n" + "User-Agent: %s\r\n" + "\r\n", + MC_SSDP_GROUP, MC_SSDP_PORT, + type, + server_string); +} + +static void compose_notify(char *type, char *host, char *buf, size_t len) +{ + char usn[256]; + + if (type) { + if (!strcmp(type, SSDP_ST_ALL)) + type = NULL; + else + snprintf(usn, sizeof(usn), "%s::%s", uuid, type); + } + + if (!type) { + type = usn; + strncpy(usn, uuid, sizeof(usn)); + } + + snprintf(buf, len, "NOTIFY * HTTP/1.1\r\n" + "Host: %s:%d\r\n" + "Server: %s\r\n" + "Location: http://%s:%d%s\r\n" + "NT: %s\r\n" + "NTS: ssdp:alive\r\n" + "USN: %s\r\n" + "Cache-Control: max-age=%d\r\n" + "\r\n", + MC_SSDP_GROUP, MC_SSDP_PORT, + server_string, + host, LOCATION_PORT, LOCATION_DESC, + type, + usn, + CACHE_TIMEOUT); +} + +size_t pktlen(unsigned char *buf) +{ + size_t hdr = sizeof(struct udphdr); + + return strlen((char *)buf + hdr) + hdr; +} + +static void send_search(struct ifsock *ifs, char *type) +{ + ssize_t num; + char buf[MAX_PKT_SIZE]; + struct sockaddr dest; + + memset(buf, 0, sizeof(buf)); + compose_search(type, buf, sizeof(buf)); + compose_addr((struct sockaddr_in *)&dest, MC_SSDP_GROUP, MC_SSDP_PORT); + + logit(LOG_DEBUG, "Sending M-SEARCH ..."); + num = sendto(ifs->out, buf, strlen(buf), 0, &dest, sizeof(struct sockaddr_in)); + if (num < 0) + logit(LOG_WARNING, "Failed sending SSDP M-SEARCH"); +} + +static void send_message(struct ifsock *ifs, char *type, struct sockaddr *sa) +{ + int s; + size_t i, len, note = 0; + ssize_t num; + char host[NI_MAXHOST]; + char buf[MAX_PKT_SIZE]; + struct sockaddr dest; + struct sockaddr_in *sin = (struct sockaddr_in *)sa; + + gethostname(hostname, sizeof(hostname)); + s = getnameinfo((struct sockaddr *)&ifs->addr, sizeof(struct sockaddr_in), host, sizeof(host), NULL, 0, NI_NUMERICHOST); + if (s) { + logit(LOG_WARNING, "Failed getnameinfo(): %s", gai_strerror(s)); + return; + } + + if (ifs->addr.sin_addr.s_addr == htonl(INADDR_ANY)) + return; + if (ifs->out == -1) + return; + + if (!strcmp(type, SSDP_ST_ALL)) + type = NULL; + + memset(buf, 0, sizeof(buf)); + if (sin) + compose_response(type, host, buf, sizeof(buf)); + else + compose_notify(type, host, buf, sizeof(buf)); + + if (!sin) { + note = 1; + compose_addr((struct sockaddr_in *)&dest, MC_SSDP_GROUP, MC_SSDP_PORT); + sin = (struct sockaddr_in *)&dest; + } + + logit(LOG_DEBUG, "Sending %s from %s ...", !note ? "reply" : "notify", host); + num = sendto(ifs->out, buf, strlen(buf), 0, sin, sizeof(struct sockaddr_in)); + if (num < 0) + logit(LOG_WARNING, "Failed sending SSDP %s, type: %s: %s", !note ? "reply" : "notify", type, strerror(errno)); +} + +static void ssdp_recv(int sd) +{ + ssize_t len; + struct sockaddr sa; + socklen_t salen; + char buf[MAX_PKT_SIZE + 1]; + + memset(buf, 0, sizeof(buf)); + len = recvfrom(sd, buf, sizeof(buf) - 1, MSG_DONTWAIT, &sa, &salen); + if (len > 0) { + if (sa.sa_family != AF_INET) + return; + + if (strstr(buf, "M-SEARCH *")) { + size_t i; + char *ptr, *type; + struct ifsock *ifs; + struct sockaddr_in *sin = (struct sockaddr_in *)&sa; + + ifs = find_outbound(&sa); + if (!ifs) { + logit(LOG_DEBUG, "No matching socket for client %s", inet_ntoa(sin->sin_addr)); + return; + } + logit(LOG_DEBUG, "Matching socket for client %s", inet_ntoa(sin->sin_addr)); + + type = strcasestr(buf, "\r\nST:"); + if (!type) { + logit(LOG_DEBUG, "No Search Type (ST:) found in M-SEARCH *, assuming " SSDP_ST_ALL); + type = SSDP_ST_ALL; + send_message(ifs, type, &sa); + return; + } + + type = strchr(type, ':'); + if (!type) + return; + type++; + while (isspace(*type)) + type++; + + ptr = strstr(type, "\r\n"); + if (!ptr) + return; + *ptr = 0; + + for (i = 0; supported_types[i]; i++) { + if (!strcmp(supported_types[i], type)) { + logit(LOG_DEBUG, "M-SEARCH * ST: %s from %s port %d", type, + inet_ntoa(sin->sin_addr), ntohs(sin->sin_port)); + send_message(ifs, type, &sa); + return; + } + } + + logit(LOG_DEBUG, "M-SEARCH * for unsupported ST: %s from %s", type, + inet_ntoa(sin->sin_addr)); + } + } +} + +static int multicast_init(void) +{ + int sd; + struct sockaddr sa; + struct sockaddr_in *sin = (struct sockaddr_in *)&sa; + + sd = socket(AF_INET, SOCK_DGRAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0); + if (sd < 0) { + logit(LOG_ERR, "Failed opening multicast socket: %s", strerror(errno)); + return -1; + } + + memset(&sa, 0, sizeof(sa)); + sin->sin_family = AF_INET; + sin->sin_addr.s_addr = inet_addr(MC_SSDP_GROUP); + sin->sin_port = htons(MC_SSDP_PORT); + + if (bind(sd, &sa, sizeof(*sin)) < 0) { + close(sd); + logit(LOG_ERR, "Failed binding to %s:%d: %s", inet_ntoa(sin->sin_addr), MC_SSDP_PORT, strerror(errno)); + return -1; + } + + register_socket(sd, -1, &sa, NULL, ssdp_recv); + + return sd; +} + +static int multicast_join(int sd, struct sockaddr *sa) +{ + struct ip_mreqn mreq; + struct sockaddr_in *sin = (struct sockaddr_in *)sa; + + memset(&mreq, 0, sizeof(mreq)); + mreq.imr_address = sin->sin_addr; + mreq.imr_multiaddr.s_addr = inet_addr(MC_SSDP_GROUP); + if (setsockopt(sd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq))) { + if (EADDRINUSE == errno) + return 0; + + logit(LOG_ERR, "Failed joining group %s: %s", MC_SSDP_GROUP, strerror(errno)); + return -1; + } + + return 0; +} + +static void mark(void) +{ + struct ifsock *ifs; + + LIST_FOREACH(ifs, &il, link) { + if (ifs->out != -1) + ifs->stale = 1; + else + ifs->stale = 0; + } +} + +static int sweep(void) +{ + int modified = 0; + struct ifsock *ifs, *tmp; + + LIST_FOREACH_SAFE(ifs, &il, link, tmp) { + if (!ifs->stale) + continue; + + modified++; + logit(LOG_DEBUG, "Removing stale ifs %s", inet_ntoa(ifs->addr.sin_addr)); + + LIST_REMOVE(ifs, link); + close(ifs->out); + free(ifs); + } + + return modified; +} + +static int ssdp_init(int in, char *iflist[], size_t num) +{ + int modified; + size_t i; + struct ifaddrs *ifaddrs, *ifa; + + logit(LOG_INFO, "Updating interfaces ..."); + + if (getifaddrs(&ifaddrs) < 0) { + logit(LOG_ERR, "Failed getifaddrs(): %s", strerror(errno)); + return -1; + } + + /* Mark all outbound interfaces as stale */ + mark(); + + /* First pass, clear stale marker from exact matches */ + for (ifa = ifaddrs; ifa; ifa = ifa->ifa_next) { + struct ifsock *ifs; + + /* Do we already have it? */ + ifs = find_iface(ifa->ifa_addr); + if (ifs) { + ifs->stale = 0; + continue; + } + } + + /* Clean out any stale interface addresses */ + modified = sweep(); + + /* Second pass, add new ones */ + for (ifa = ifaddrs; ifa; ifa = ifa->ifa_next) { + int sd; + + /* Interface filtering, optional command line argument */ + if (filter_iface(ifa->ifa_name, iflist, num)) { + logit(LOG_DEBUG, "Skipping %s, not in iflist.", ifa->ifa_name); + continue; + } + + /* Do we have another in the same subnet? */ + if (filter_addr(ifa->ifa_addr)) + continue; + + sd = open_socket(ifa->ifa_name, ifa->ifa_addr, MC_SSDP_PORT); + if (sd < 0) + continue; + + multicast_join(in, ifa->ifa_addr); + + if (register_socket(in, sd, ifa->ifa_addr, ifa->ifa_netmask, ssdp_recv)) { + close(sd); + break; + } + modified++; + } + + freeifaddrs(ifaddrs); + + return modified; +} + +static void handle_message(int sd) +{ + struct ifsock *ifs; + + LIST_FOREACH(ifs, &il, link) { + if (ifs->in != sd) + continue; + + if (ifs->cb) + ifs->cb(sd); + } +} + +static void wait_message(time_t tmo) +{ + int num = 1, timeout; + size_t ifnum = 0; + struct pollfd pfd[MAX_NUM_IFACES]; + struct ifsock *ifs; + + LIST_FOREACH(ifs, &il, link) { + if (ifs->out != -1) + continue; + + pfd[ifnum].fd = ifs->in; + pfd[ifnum].events = POLLIN | POLLHUP; + ifnum++; + } + + while (1) { + size_t i; + + timeout = tmo - time(NULL); + if (timeout < 0) + break; + + num = poll(pfd, ifnum, timeout * 1000); + if (num < 0) { + if (EINTR == errno) + break; + + err(1, "Unrecoverable error"); + } + + if (num == 0) + break; + + for (i = 0; num > 0 && i < ifnum; i++) { + if (pfd[i].revents & POLLIN) { + handle_message(pfd[i].fd); + num--; + } + } + } +} + +static void announce(int mod) +{ + struct ifsock *ifs; + + logit(LOG_INFO, "Sending SSDP NOTIFY new:%d ...", mod); + + LIST_FOREACH(ifs, &il, link) { + size_t i; + + if (mod && !ifs->mod) + continue; + ifs->mod = 0; + +// send_search(ifs, "upnp:rootdevice"); + for (i = 0; supported_types[i]; i++) { + /* UUID sent in SSDP_ST_ALL, first announce */ + if (!strcmp(supported_types[i], uuid)) + continue; + + send_message(ifs, supported_types[i], NULL); + } + } +} + +static void lsb_init(void) +{ + FILE *fp; + char *ptr; + char line[80]; + const char *file = "/etc/lsb-release"; + + fp = fopen(file, "r"); + if (!fp) { + fallback: + logit(LOG_WARNING, "No %s found on system, using built-in server string.", file); + return; + } + + while (fgets(line, sizeof(line), fp)) { + line[strlen(line) - 1] = 0; + + ptr = strstr(line, "DISTRIB_ID"); + if (ptr && (ptr = strchr(ptr, '='))) + os = strdup(++ptr); + + ptr = strstr(line, "DISTRIB_RELEASE"); + if (ptr && (ptr = strchr(ptr, '='))) + ver = strdup(++ptr); + } + fclose(fp); + + if (os && ver) + snprintf(server_string, sizeof(server_string), "%s/%s UPnP/1.0 %s/%s", + os, ver, PACKAGE_NAME, PACKAGE_VERSION); + else + goto fallback; + + logit(LOG_DEBUG, "Server: %s", server_string); +} + +/* https://en.wikipedia.org/wiki/Universally_unique_identifier */ +static void uuidgen(void) +{ + FILE *fp; + char buf[42]; + const char *file = _PATH_VARDB PACKAGE_NAME ".cache"; + + fp = fopen(file, "r"); + if (!fp) { + fp = fopen(file, "w"); + if (!fp) + logit(LOG_WARNING, "Cannot create UUID cache, %s: %s", file, strerror(errno)); + + generate: + srand(time(NULL)); + snprintf(buf, sizeof(buf), "uuid:%8.8x-%4.4x-%4.4x-%4.4x-%6.6x%6.6x", + rand() & 0xFFFFFFFF, + rand() & 0xFFFF, + (rand() & 0x0FFF) | 0x4000, /* M 4 MSB version => version 4 */ + (rand() & 0x1FFF) | 0x8000, /* N: 3 MSB variant => variant 1 */ + rand() & 0xFFFFFF, rand() & 0xFFFFFF); + + if (fp) { + logit(LOG_DEBUG, "Creating new UUID cache file, %s", file); + fprintf(fp, "%s\n", buf); + fclose(fp); + } + } else { + if (!fgets(buf, sizeof(buf), fp)) { + fclose(fp); + goto generate; + } + buf[strlen(buf) - 1] = 0; + fclose(fp); + } + + strcpy(uuid, buf); + logit(LOG_DEBUG, "URN: %s", uuid); +} + +static void exit_handler(int signo) +{ + (void)signo; + running = 0; +} + +static void signal_init(void) +{ + signal(SIGTERM, exit_handler); + signal(SIGINT, exit_handler); + signal(SIGHUP, exit_handler); + signal(SIGQUIT, exit_handler); +} + +static int usage(int code) +{ + printf("Usage: %s [-dhv] [-i SEC] [IFACE [IFACE ...]]\n" + "\n" + " -d Developer debug mode\n" + " -h This help text\n" + " -i SEC SSDP notify interval (30-900), default %d sec\n" + " -r SEC Interface refresh interval (5-1800), default %d sec\n" + " -v Show program version\n" + "\n" + "Bug report address: %-40s\n", PACKAGE_NAME, NOTIFY_INTERVAL, REFRESH_INTERVAL, PACKAGE_BUGREPORT); + + return code; +} + +int main(int argc, char *argv[]) +{ + int i, c, sd; + int log_level = LOG_NOTICE; + int log_opts = LOG_CONS | LOG_PID; + int interval = NOTIFY_INTERVAL; + int refresh = REFRESH_INTERVAL; + time_t now, rtmo = 0, itmo = 0; + + while ((c = getopt(argc, argv, "dhi:r:v")) != EOF) { + switch (c) { + case 'd': + debug = 1; + break; + + case 'h': + return usage(0); + + case 'i': + interval = atoi(optarg); + if (interval < 30 || interval > 900) + errx(1, "Invalid announcement interval (30-900)."); + break; + + case 'r': + refresh = atoi(optarg); + if (refresh < 5 || refresh > 1800) + errx(1, "Invalid refresh interval (5-1800)."); + break; + + case 'v': + puts(PACKAGE_VERSION); + return 0; + + default: + break; + } + } + + signal_init(); + + if (debug) { + log_level = LOG_DEBUG; + log_opts |= LOG_PERROR; + } + + openlog(PACKAGE_NAME, log_opts, LOG_DAEMON); + setlogmask(LOG_UPTO(log_level)); + + uuidgen(); + lsb_init(); + web_init(); + + sd = multicast_init(); + if (sd < 0) + err(1, "Failed creating multicast socket"); + + while (running) { + now = time(NULL); + + if (rtmo <= now) { + if (ssdp_init(sd, &argv[optind], argc - optind) > 0) + announce(1); + rtmo = now + refresh; + } + + if (itmo <= now) { + announce(0); + itmo = now + interval; + } + + wait_message(MIN(rtmo, itmo)); + } + + closelog(); + return close_socket(); +} + +/** + * Local Variables: + * indent-tabs-mode: t + * c-file-style: "linux" + * End: + */ diff --git a/lib/data/ssdp/web.c b/lib/data/ssdp/web.c new file mode 100644 index 00000000..93dba2f7 --- /dev/null +++ b/lib/data/ssdp/web.c @@ -0,0 +1,216 @@ +/* Micro web server for serving SSDP .xml file + * + * Copyright (c) 2017 Joachim Nilsson + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND 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, DIRECT, 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.a + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ssdp.h" + +const char *xml = + "\r\n" + "\r\n" + " \r\n" + " 1\r\n" + " 0\r\n" + " \r\n" + " \r\n" + " urn:schemas-upnp-org:device:InternetGatewayDevice:1\r\n" + " %s\r\n" + " %s\r\n%s" + " %s\r\n" + " uuid:%s\r\n" + " http://%s\r\n" + " \r\n" + "\r\n" + "\r\n"; + + +/* Peek into SOCK_STREAM on accepted client socket to figure out inbound interface */ +static struct sockaddr_in *stream_peek(int sd, char *ifname) +{ + struct ifaddrs *ifaddr, *ifa; + static struct sockaddr_in sin; + socklen_t len = sizeof(sin); + + if (-1 == getsockname(sd, (struct sockaddr *)&sin, &len)) + return NULL; + + if (-1 == getifaddrs(&ifaddr)) + return NULL; + + for (ifa = ifaddr; ifa; ifa = ifa->ifa_next) { + size_t len = sizeof(struct in_addr); + struct sockaddr_in *iin; + + if (!ifa->ifa_addr) + continue; + + if (ifa->ifa_addr->sa_family != AF_INET) + continue; + + iin = (struct sockaddr_in *)ifa->ifa_addr; + if (!memcmp(&sin.sin_addr, &iin->sin_addr, len)) { + strncpy(ifname, ifa->ifa_name, IF_NAMESIZE); + break; + } + } + + freeifaddrs(ifaddr); + + return &sin; +} + +static void respond(int sd, struct sockaddr_in *sin) +{ + struct pollfd pfd = { + .fd = sd, + .events = POLLIN, + }; + char *head = "HTTP/1.1 200 OK\r\n" + "Content-Type: text/xml\r\n" + "Connection: close\r\n" + "\r\n"; + char hostname[64], url[128] = ""; + char mesg[1024], *reqline[3]; + int rc, rcvd, fd, bytes_read; + + /* Check for early disconnect or client timeout */ + rc = poll(&pfd, 1, 1000); + if (rc <= 0) + goto error; + + memset(mesg, 0, sizeof(mesg)); + rcvd = recv(sd, mesg, sizeof(mesg), 0); + if (rcvd <= 0) { + logit(LOG_WARNING, "web recv() error: %s", strerror(errno)); + goto error; + } + + logit(LOG_DEBUG, "%s", mesg); + reqline[0] = strtok(mesg, " \t\n"); + if (strncmp(reqline[0], "GET", 4) == 0) { + reqline[1] = strtok(NULL, " \t"); + reqline[2] = strtok(NULL, " \t\n"); + if (strncmp(reqline[2], "HTTP/1.0", 8) != 0 && strncmp(reqline[2], "HTTP/1.1", 8) != 0) { + if (write(sd, "HTTP/1.1 400 Bad Request\r\n", 26) < 0) + logit(LOG_WARNING, "Failed returning status 400 to client: %s", strerror(errno)); + goto error; + } + + /* XXX: Add support for icon as well */ + if (!strstr(reqline[1], LOCATION_DESC)) { + if (write(sd, "HTTP/1.1 404 Not Found\r\n", 24) < 0) + logit(LOG_WARNING, "Failed returning status 404 to client: %s", strerror(errno)); + goto error; + } + + gethostname(hostname, sizeof(hostname)); +#ifdef MANUFACTURER_URL + snprintf(url, sizeof(url), " %s\r\n", MANUFACTURER_URL); +#endif + logit(LOG_DEBUG, "Sending XML reply ..."); + send(sd, head, strlen(head), 0); + snprintf(mesg, sizeof(mesg), xml, + hostname, + MANUFACTURER, + url, + MODEL, + uuid, + inet_ntoa(sin->sin_addr)); + if (send(sd, mesg, strlen(mesg), 0) < 0) + logit(LOG_WARNING, "Failed sending file to client: %s", strerror(errno)); + } + +error: + shutdown(sd, SHUT_RDWR); + close(sd); +} + +void web_recv(int sd) +{ + int client; + char ifname[IF_NAMESIZE] = "UNKNOWN"; + struct sockaddr_in *sin; + + client = accept(sd, NULL, NULL); + if (client < 0) { + logit(LOG_ERR, "accept() error: %s", strerror(errno)); + return; + } + + sin = stream_peek(client, ifname); + if (!sin) { + logit(LOG_ERR, "Failed resolving client interface: %s", strerror(errno)); + return; + } + + respond(client, sin); + shutdown(client, SHUT_RDWR); + close(client); +} + +void web_init(void) +{ + int sd; + struct sockaddr sa; + struct sockaddr_in *sin; + + memset(&sa, 0, sizeof(sa)); + sa.sa_family = AF_INET; + sin = (struct sockaddr_in *)&sa; + sin->sin_addr.s_addr = htonl(INADDR_ANY); + sin->sin_port = htons(LOCATION_PORT); + + sd = socket(sa.sa_family, SOCK_STREAM | SOCK_NONBLOCK, 0); + if (sd == -1) + err(1, "Failed creating web socket"); + + ENABLE_SOCKOPT(sd, SOL_SOCKET, SO_REUSEADDR); +#ifdef SO_REUSEPORT + ENABLE_SOCKOPT(sd, SOL_SOCKET, SO_REUSEPORT); +#endif + + if (bind(sd, &sa, sizeof(sa)) < 0) + err(1, "Failed binding web socket"); + + if (listen(sd, 10) != 0) + err(1, "Failed setting web listen backlog"); + + register_socket(sd, -1, &sa, NULL, web_recv); +} + +/** + * Local Variables: + * indent-tabs-mode: t + * c-file-style: "linux" + * End: + */ diff --git a/lib/hardware/sensors/optic_flow/adns3080/ADNS3080Demo/ADNS3080.h b/lib/hardware/sensors/optic_flow/adns3080/ADNS3080Demo/ADNS3080.h new file mode 100644 index 00000000..86b2ca1d --- /dev/null +++ b/lib/hardware/sensors/optic_flow/adns3080/ADNS3080Demo/ADNS3080.h @@ -0,0 +1,50 @@ +// ADNS3080 hardware config +#define ADNS3080_PIXELS_X 30 +#define ADNS3080_PIXELS_Y 30 +#define ADNS3080_CLOCK_SPEED 24000000 + +// Register Map for the ADNS3080 Optical OpticalFlow Sensor +#define ADNS3080_PRODUCT_ID 0x00 +#define ADNS3080_REVISION_ID 0x01 +#define ADNS3080_MOTION 0x02 +#define ADNS3080_DELTA_X 0x03 +#define ADNS3080_DELTA_Y 0x04 +#define ADNS3080_SQUAL 0x05 +#define ADNS3080_PIXEL_SUM 0x06 +#define ADNS3080_MAXIMUM_PIXEL 0x07 +#define ADNS3080_CONFIGURATION_BITS 0x0a +#define ADNS3080_EXTENDED_CONFIG 0x0b +#define ADNS3080_DATA_OUT_LOWER 0x0c +#define ADNS3080_DATA_OUT_UPPER 0x0d +#define ADNS3080_SHUTTER_LOWER 0x0e +#define ADNS3080_SHUTTER_UPPER 0x0f +#define ADNS3080_FRAME_PERIOD_LOWER 0x10 +#define ADNS3080_FRAME_PERIOD_UPPER 0x11 +#define ADNS3080_MOTION_CLEAR 0x12 +#define ADNS3080_FRAME_CAPTURE 0x13 +#define ADNS3080_SROM_ENABLE 0x14 +#define ADNS3080_FRAME_PERIOD_MAX_BOUND_LOWER 0x19 +#define ADNS3080_FRAME_PERIOD_MAX_BOUND_UPPER 0x1a +#define ADNS3080_FRAME_PERIOD_MIN_BOUND_LOWER 0x1b +#define ADNS3080_FRAME_PERIOD_MIN_BOUND_UPPER 0x1c +#define ADNS3080_SHUTTER_MAX_BOUND_LOWER 0x1e +#define ADNS3080_SHUTTER_MAX_BOUND_UPPER 0x1e +#define ADNS3080_SROM_ID 0x1f +#define ADNS3080_OBSERVATION 0x3d +#define ADNS3080_INVERSE_PRODUCT_ID 0x3f +#define ADNS3080_PIXEL_BURST 0x40 +#define ADNS3080_MOTION_BURST 0x50 +#define ADNS3080_SROM_LOAD 0x60 + +// Configuration Bits +#define ADNS3080_LED_MODE_ALWAYS_ON 0x00 +#define ADNS3080_LED_MODE_WHEN_REQUIRED 0x01 + +#define ADNS3080_RESOLUTION_400 400 +#define ADNS3080_RESOLUTION_1600 1600 + +// Extended Configuration bits +#define ADNS3080_SERIALNPU_OFF 0x02 + +#define ADNS3080_FRAME_RATE_MAX 6469 +#define ADNS3080_FRAME_RATE_MIN 2000 diff --git a/lib/hardware/sensors/optic_flow/adns3080/ADNS3080Demo/ADNS3080Demo.pde b/lib/hardware/sensors/optic_flow/adns3080/ADNS3080Demo/ADNS3080Demo.pde new file mode 100644 index 00000000..2632c34f --- /dev/null +++ b/lib/hardware/sensors/optic_flow/adns3080/ADNS3080Demo/ADNS3080Demo.pde @@ -0,0 +1,389 @@ +// Test the ADNS3080 Optical Flow Sensor +// based on: Example of AP_OpticalFlow library by Randy Mackay. DIYDrones.com +// + +#include "SPI.h" +#include "ADNS3080.h" + +#define AP_SPI_DATAIN 12 //MISO +#define AP_SPI_DATAOUT 11 //MOSI +#define AP_SPI_CLOCK 13 //SCK +#define ADNS3080_CHIP_SELECT 10 //SS +#define ADNS3080_RESET 9 //RESET + +byte orig_spi_settings_spcr; +byte orig_spi_settings_spsr; +int _cs_pin=ADNS3080_CHIP_SELECT; +int _reset_pin=1; // set to 1 if you have reset connected +unsigned int last_update; +boolean _overflow=false; +boolean _motion=false; +int raw_dx; +int raw_dy; +unsigned int surface_quality; + +void setup() +{ + Serial.begin(115200); + Serial.println("www.bot-thoughts.com\nOptical Flow test program V1.0"); + Serial.println("Based on APM/ArduCopter AP_OpticalFlow library"); + Serial.println("by Randy Mackay"); + delay(1000); + + // flowSensor initialization + if( initOF() == false ) + Serial.println("Failed to initialise ADNS3080"); + + delay(1000); +} + +void loop() +{ + int value; + + display_menu(); + + // wait for user to enter something + while( !Serial.available() ) { + delay(20); + } + + // get character from user + value = Serial.read(); + + switch( value ) { + + case 'c' : + //display_config(); + break; + + case 'f' : + //set_frame_rate(); + break; + + case 'i' : + // display image + display_image(); + break; + + case 'I' : + display_image_continuously(); + break; + + case 'm' : + display_motion(); + break; + + case 'r' : + // set resolution + //set_resolution(); + break; + + case 's' : + //set_shutter_speed(); + break; + + case 'z' : + //flowSensor.clear_motion(); + break; + + case '\r' : // ignore return type characters + case '\n' : + break; + + default: + Serial.println("unrecognised command"); + Serial.println(); + break; + } +} + + +///////////////////////////////////////////////////////////////////////////////////////////////////////////// +// DISPLAY FUNCTIONS +///////////////////////////////////////////////////////////////////////////////////////////////////////////// + +// Prints out a list of functions. +void display_menu() +{ + Serial.println(); + Serial.println("please choose from the following options:"); +// Serial.println(" c - display all config"); +// Serial.println(" f - set frame rate"); + Serial.println(" i - display image"); + Serial.println(" I - display image continuously"); + Serial.println(" m - display motion"); +// Serial.println(" r - set resolution"); +// Serial.println(" s - set shutter speed"); +// Serial.println(" z - clear all motion"); +// Serial.println(" a - frame rate auto/manual"); + Serial.println(); +} + + +// Captures and displays image from flowSensor +void display_image() +{ + Serial.println("image data --------------"); + print_pixel_data(&Serial); + Serial.println("-------------------------"); +} + + +// display_image - captures and displays image from flowSensor flowSensor +void display_image_continuously() +{ + int i; + Serial.println("press any key to return to menu"); + + Serial.flush(); + + while( !Serial.available() ) { + display_image(); + i=0; + while( i<20 && !Serial.available() ) { + delay(100); // give the viewer a bit of time to catchup + i++; + } + } + + Serial.flush(); +} + + +// show x,y and squal values constantly until user presses a key +// +void display_motion() +{ + boolean first_time = true; + Serial.flush(); + + // display instructions on how to exit + Serial.println("press x to return to menu.."); + delay(1000); + + while( !Serial.available() ) { + updateOF(); + + // check for errors + if( _overflow ) + Serial.println("overflow!!"); + + // x,y,squal + Serial.print("dx: "); + Serial.print(raw_dx,DEC); + Serial.print("\tdy: "); + Serial.print(raw_dy,DEC); + Serial.print("\tsqual:"); + Serial.print(surface_quality,DEC); + Serial.println(); + first_time = false; + + // short delay + delay(100); + } + + // flush the serial + Serial.flush(); +} + +///////////////////////////////////////////////////////////////////////////////////////////////////////////// +// ADNS3080 SPECIFIC FUNCTIONS +///////////////////////////////////////////////////////////////////////////////////////////////////////////// + +// reset sensor by holding a pin high (or is it low?) for 10us. +void reset() +{ + // return immediately if the reset pin is not defined + if( _reset_pin == 0) + return; + + digitalWrite(_reset_pin,HIGH); // reset sensor + delayMicroseconds(10); + digitalWrite(_reset_pin,LOW); // return sensor to normal +} + + +// Read a register from the sensor +byte read_register(byte address) +{ + byte result = 0, junk = 0; + + backup_spi_settings(); + + // take the chip select low to select the device + digitalWrite(_cs_pin, LOW); + + // send the device the register you want to read: + junk = SPI.transfer(address); + + // small delay + delayMicroseconds(50); + + // send a value of 0 to read the first byte returned: + result = SPI.transfer(0x00); + + // take the chip select high to de-select: + digitalWrite(_cs_pin, HIGH); + + restore_spi_settings(); + + return result; +} + + +// init - initialise sensor +// initCommAPI parameter controls whether SPI interface is initialised (set to false if other devices are on the SPI bus and have already initialised the interface) +boolean initOF() +{ + int retry = 0; + + pinMode(AP_SPI_DATAOUT,OUTPUT); + pinMode(AP_SPI_DATAIN,INPUT); + pinMode(AP_SPI_CLOCK,OUTPUT); + pinMode(_cs_pin,OUTPUT); + if( _reset_pin != 0) + pinMode(ADNS3080_RESET,OUTPUT); + + digitalWrite(_cs_pin,HIGH); // disable device (Chip select is active low) + + // reset the device + reset(); + + // start the SPI library: + SPI.begin(); + + // check the sensor is functioning + if( retry < 3 ) { + if( read_register(ADNS3080_PRODUCT_ID) == 0x17 ) + return true; + retry++; + } + + return false; +} + + +// +// backup_spi_settings - checks current SPI settings (clock speed, etc), sets values to what we need +// +byte backup_spi_settings() +{ + // store current spi values + orig_spi_settings_spcr = SPCR & (DORD | CPOL | CPHA); + orig_spi_settings_spsr = SPSR & SPI2X; + + // set the values that we need + SPI.setBitOrder(MSBFIRST); + SPI.setDataMode(SPI_MODE3); + SPI.setClockDivider(SPI_CLOCK_DIV8); // sensor running at 2Mhz. this is it's maximum speed + + return orig_spi_settings_spcr; +} + + +// restore_spi_settings - restores SPI settings (clock speed, etc) to what their values were before the sensor used the bus +byte restore_spi_settings() +{ + byte temp; + + // restore SPSR + temp = SPSR; + temp &= ~SPI2X; + temp |= orig_spi_settings_spsr; + SPSR = temp; + + // restore SPCR + temp = SPCR; + temp &= ~(DORD | CPOL | CPHA); // zero out the important bits + temp |= orig_spi_settings_spcr; // restore important bits + SPCR = temp; + + return temp; +} + + +// write a value to one of the sensor's registers +void write_register(byte address, byte value) +{ + byte junk = 0; + + backup_spi_settings(); + + // take the chip select low to select the device + digitalWrite(_cs_pin, LOW); + + // send register address + junk = SPI.transfer(address | 0x80 ); + + // small delay + delayMicroseconds(50); + + // send data + junk = SPI.transfer(value); + + // take the chip select high to de-select: + digitalWrite(_cs_pin, HIGH); + + restore_spi_settings(); +} + + +// get_pixel_data - captures an image from the sensor and stores it to the pixe_data array +void print_pixel_data(Stream *serPort) +{ + int i,j; + boolean isFirstPixel = true; + byte regValue; + byte pixelValue; + + // write to frame capture register to force capture of frame + write_register(ADNS3080_FRAME_CAPTURE,0x83); + + // wait 3 frame periods + 10 nanoseconds for frame to be captured + delayMicroseconds(1510); // min frame speed is 2000 frames/second so 1 frame = 500 nano seconds. so 500 x 3 + 10 = 1510 + + // display the pixel data + for( i=0; iprintln("failed to find first pixel"); + } + isFirstPixel = false; + pixelValue = ( regValue << 2); + serPort->print(pixelValue,DEC); + if( j!= ADNS3080_PIXELS_X-1 ) + serPort->print(","); + delayMicroseconds(50); + } + serPort->println(); + } + + // hardware reset to restore sensor to normal operation + reset(); +} + +bool updateOF() +{ + byte motion_reg; + surface_quality = (unsigned int)read_register(ADNS3080_SQUAL); + delayMicroseconds(50); // small delay + + // check for movement, update x,y values + motion_reg = read_register(ADNS3080_MOTION); + _overflow = ((motion_reg & 0x10) != 0); // check if we've had an overflow + if( (motion_reg & 0x80) != 0 ) { + raw_dx = ((char)read_register(ADNS3080_DELTA_X)); + delayMicroseconds(50); // small delay + raw_dy = ((char)read_register(ADNS3080_DELTA_Y)); + _motion = true; + }else{ + raw_dx = 0; + raw_dy = 0; + } + last_update = millis(); + + return true; +} + diff --git a/lib/hardware/sensors/optic_flow/adns3080/ADNS3080Demo/ADNS3080ImageGrabber.py b/lib/hardware/sensors/optic_flow/adns3080/ADNS3080Demo/ADNS3080ImageGrabber.py new file mode 100644 index 00000000..84cb45d5 --- /dev/null +++ b/lib/hardware/sensors/optic_flow/adns3080/ADNS3080Demo/ADNS3080ImageGrabber.py @@ -0,0 +1,180 @@ +# File: ADNS3080ImageGrabber.py + +import serial +import string +import math +import time +from Tkinter import * +from threading import Timer + +comPort = 'COM8' #default com port +comPortBaud = 115200 + +class App: + grid_size = 15 + num_pixels = 30 + image_started = FALSE + image_current_row = 0; + ser = serial.Serial() + pixel_dictionary = {} + + def __init__(self, master): + + # set main window's title + master.title("ADNS3080ImageGrabber") + + frame = Frame(master) + frame.grid(row=0,column=0) + + self.comPortStr = StringVar() + self.comPort = Entry(frame,textvariable=self.comPortStr) + self.comPort.grid(row=0,column=0) + self.comPort.delete(0, END) + self.comPort.insert(0,comPort) + + self.button = Button(frame, text="Open", fg="red", command=self.open_serial) + self.button.grid(row=0,column=1) + + self.entryStr = StringVar() + self.entry = Entry(frame,textvariable=self.entryStr) + self.entry.grid(row=0,column=2) + self.entry.delete(0, END) + self.entry.insert(0,"I") + + self.send_button = Button(frame, text="Send", command=self.send_to_serial) + self.send_button.grid(row=0,column=3) + + self.canvas = Canvas(master, width=self.grid_size*self.num_pixels, height=self.grid_size*self.num_pixels) + self.canvas.grid(row=1) + + ## start attempts to read from serial port + self.read_loop() + + def __del__(self): + self.stop_read_loop() + + def open_serial(self): + # close the serial port + if( self.ser.isOpen() ): + try: + self.ser.close() + except: + i=i # do nothing + # open the serial port + try: + self.ser = serial.Serial(port=self.comPortStr.get(),baudrate=comPortBaud, timeout=1) + print("serial port '" + self.comPortStr.get() + "' opened!") + except: + print("failed to open serial port '" + self.comPortStr.get() + "'") + + def send_to_serial(self): + if self.ser.isOpen(): + self.ser.write(self.entryStr.get()) + print "sent '" + self.entryStr.get() + "' to " + self.ser.portstr + else: + print "Serial port not open!" + + def read_loop(self): + try: + self.t.cancel() + except: + aVar = 1 # do nothing + #print("reading") + if( self.ser.isOpen() ) : + self.read_from_serial(); + + self.t = Timer(0.0,self.read_loop) + self.t.start() + + def stop_read_loop(self): + try: + self.t.cancel() + except: + print("failed to cancel timer") + # do nothing + + def read_from_serial(self): + if( self.ser.isOpen() ): + while( self.ser.inWaiting() > 0 ): + + self.line_processed = FALSE + line = self.ser.readline() + + # process the line read + + if( line.find("-------------------------") == 0 ): + self.line_processed = TRUE + self.image_started = FALSE + self.image_current_row = 0 + + if( self.image_started == TRUE ): + if( self.image_current_row >= self.num_pixels ): + self.image_started == FALSE + else: + words = string.split(line,",") + if len(words) >= 30: + self.line_processed = TRUE + x = 0 + for v in words: + try: + colour = int(v) + except: + colour = 0; + #self.display_pixel(x,self.image_current_row,colour) + self.display_pixel(self.num_pixels-1-self.image_current_row,self.num_pixels-1-x,colour) + x += 1 + self.image_current_row += 1 + else: + print("line " + str(self.image_current_row) + "incomplete (" + str(len(words)) + " of " + str(self.num_pixels) + "), ignoring") + #print("bad line: " + line); + + if( line.find("image data") >= 0 ): + self.line_processed = TRUE + self.image_started = TRUE + self.image_current_row = 0 + # clear canvas + #self.canvas.delete(ALL) # remove all items + + #display the line if we couldn't understand it + if( self.line_processed == FALSE ): + print( line ) + + def display_default_image(self): + # display the grid + for x in range(0, self.num_pixels-1): + for y in range(0, self.num_pixels-1): + colour = x * y / 3.53 + self.display_pixel(x,y,colour) + + def display_pixel(self, x, y, colour): + if( x >= 0 and x < self.num_pixels and y >= 0 and y < self.num_pixels ) : + + #find the old pixel if it exists and delete it + if self.pixel_dictionary.has_key(x+y*self.num_pixels) : + self.old_pixel = self.pixel_dictionary[x+y*self.num_pixels] + self.canvas.delete(self.old_pixel) + del(self.old_pixel) + + fillColour = "#%02x%02x%02x" % (colour, colour, colour) + #draw a new pixel and add to pixel_array + self.new_pixel = self.canvas.create_rectangle(x*self.grid_size, y*self.grid_size, (x+1)*self.grid_size, (y+1)*self.grid_size, fill=fillColour) + self.pixel_dictionary[x+y*self.num_pixels] = self.new_pixel + + +## main loop ## + +root = Tk() +#root.withdraw() +#serPort = SerialHandler(comPort,comPortBaud) + +# create main display +app = App(root) +app.display_default_image() + +print("entering main loop!") + +root.mainloop() + +app.stop_read_loop() + +print("exiting") diff --git a/lib/hardware/sensors/optic_flow/adns3080/ADNS3080Demo/README.txt b/lib/hardware/sensors/optic_flow/adns3080/ADNS3080Demo/README.txt new file mode 100644 index 00000000..f4eedd8f --- /dev/null +++ b/lib/hardware/sensors/optic_flow/adns3080/ADNS3080Demo/README.txt @@ -0,0 +1,24 @@ +Instructions for running the ADNS3080ImageGrabber.py + +0. Connect your ADNS3080 (DIYDrones) sensor to your Arduino: + + Arduino -> ADNS3080 +-------- -------- + 5V -> 5V + GND -> GND + D9 -> RST (optional) + D10 -> NCS + D11 -> MOSI + D12 -> MISO + D13 -> SCLK + N/C -> NPD, LED, 3V + +1. Open ADNS3080Demo.pde with Arduino IDE, compile and upload to your Arduino +2. Install Python 2.7 from http://www.python.org/getit/ +3. Start the Python IDLE editor +4. Open ADNS3080ImageGrabber.py from IDLE +5. Select Run->Run Module - the Python Shell and then ADNS3080ImageGrabber applications should appear +6. On the ADNS3080ImageGrabber screen, change the default com port, "COM8" to the correct port (sorry, doesn't auto detect) +7. Wait a few moments, then push the Send button to start/stop grabbing images from the sensor (a new image should appear every 2 seconds) + +Note: you should see the the ADNS3080Demo's menu and any errors appear in the Python Shell \ No newline at end of file diff --git a/lib/hardware/sensors/optic_flow/adns3080/ADNS3080ImageGrabber/ADNS3080ImageGrabber.py b/lib/hardware/sensors/optic_flow/adns3080/ADNS3080ImageGrabber/ADNS3080ImageGrabber.py new file mode 100644 index 00000000..84cb45d5 --- /dev/null +++ b/lib/hardware/sensors/optic_flow/adns3080/ADNS3080ImageGrabber/ADNS3080ImageGrabber.py @@ -0,0 +1,180 @@ +# File: ADNS3080ImageGrabber.py + +import serial +import string +import math +import time +from Tkinter import * +from threading import Timer + +comPort = 'COM8' #default com port +comPortBaud = 115200 + +class App: + grid_size = 15 + num_pixels = 30 + image_started = FALSE + image_current_row = 0; + ser = serial.Serial() + pixel_dictionary = {} + + def __init__(self, master): + + # set main window's title + master.title("ADNS3080ImageGrabber") + + frame = Frame(master) + frame.grid(row=0,column=0) + + self.comPortStr = StringVar() + self.comPort = Entry(frame,textvariable=self.comPortStr) + self.comPort.grid(row=0,column=0) + self.comPort.delete(0, END) + self.comPort.insert(0,comPort) + + self.button = Button(frame, text="Open", fg="red", command=self.open_serial) + self.button.grid(row=0,column=1) + + self.entryStr = StringVar() + self.entry = Entry(frame,textvariable=self.entryStr) + self.entry.grid(row=0,column=2) + self.entry.delete(0, END) + self.entry.insert(0,"I") + + self.send_button = Button(frame, text="Send", command=self.send_to_serial) + self.send_button.grid(row=0,column=3) + + self.canvas = Canvas(master, width=self.grid_size*self.num_pixels, height=self.grid_size*self.num_pixels) + self.canvas.grid(row=1) + + ## start attempts to read from serial port + self.read_loop() + + def __del__(self): + self.stop_read_loop() + + def open_serial(self): + # close the serial port + if( self.ser.isOpen() ): + try: + self.ser.close() + except: + i=i # do nothing + # open the serial port + try: + self.ser = serial.Serial(port=self.comPortStr.get(),baudrate=comPortBaud, timeout=1) + print("serial port '" + self.comPortStr.get() + "' opened!") + except: + print("failed to open serial port '" + self.comPortStr.get() + "'") + + def send_to_serial(self): + if self.ser.isOpen(): + self.ser.write(self.entryStr.get()) + print "sent '" + self.entryStr.get() + "' to " + self.ser.portstr + else: + print "Serial port not open!" + + def read_loop(self): + try: + self.t.cancel() + except: + aVar = 1 # do nothing + #print("reading") + if( self.ser.isOpen() ) : + self.read_from_serial(); + + self.t = Timer(0.0,self.read_loop) + self.t.start() + + def stop_read_loop(self): + try: + self.t.cancel() + except: + print("failed to cancel timer") + # do nothing + + def read_from_serial(self): + if( self.ser.isOpen() ): + while( self.ser.inWaiting() > 0 ): + + self.line_processed = FALSE + line = self.ser.readline() + + # process the line read + + if( line.find("-------------------------") == 0 ): + self.line_processed = TRUE + self.image_started = FALSE + self.image_current_row = 0 + + if( self.image_started == TRUE ): + if( self.image_current_row >= self.num_pixels ): + self.image_started == FALSE + else: + words = string.split(line,",") + if len(words) >= 30: + self.line_processed = TRUE + x = 0 + for v in words: + try: + colour = int(v) + except: + colour = 0; + #self.display_pixel(x,self.image_current_row,colour) + self.display_pixel(self.num_pixels-1-self.image_current_row,self.num_pixels-1-x,colour) + x += 1 + self.image_current_row += 1 + else: + print("line " + str(self.image_current_row) + "incomplete (" + str(len(words)) + " of " + str(self.num_pixels) + "), ignoring") + #print("bad line: " + line); + + if( line.find("image data") >= 0 ): + self.line_processed = TRUE + self.image_started = TRUE + self.image_current_row = 0 + # clear canvas + #self.canvas.delete(ALL) # remove all items + + #display the line if we couldn't understand it + if( self.line_processed == FALSE ): + print( line ) + + def display_default_image(self): + # display the grid + for x in range(0, self.num_pixels-1): + for y in range(0, self.num_pixels-1): + colour = x * y / 3.53 + self.display_pixel(x,y,colour) + + def display_pixel(self, x, y, colour): + if( x >= 0 and x < self.num_pixels and y >= 0 and y < self.num_pixels ) : + + #find the old pixel if it exists and delete it + if self.pixel_dictionary.has_key(x+y*self.num_pixels) : + self.old_pixel = self.pixel_dictionary[x+y*self.num_pixels] + self.canvas.delete(self.old_pixel) + del(self.old_pixel) + + fillColour = "#%02x%02x%02x" % (colour, colour, colour) + #draw a new pixel and add to pixel_array + self.new_pixel = self.canvas.create_rectangle(x*self.grid_size, y*self.grid_size, (x+1)*self.grid_size, (y+1)*self.grid_size, fill=fillColour) + self.pixel_dictionary[x+y*self.num_pixels] = self.new_pixel + + +## main loop ## + +root = Tk() +#root.withdraw() +#serPort = SerialHandler(comPort,comPortBaud) + +# create main display +app = App(root) +app.display_default_image() + +print("entering main loop!") + +root.mainloop() + +app.stop_read_loop() + +print("exiting") diff --git a/lib/hardware/sensors/optic_flow/adns3080/ADNS3080ImageGrabber/README.txt b/lib/hardware/sensors/optic_flow/adns3080/ADNS3080ImageGrabber/README.txt new file mode 100644 index 00000000..8de7393b --- /dev/null +++ b/lib/hardware/sensors/optic_flow/adns3080/ADNS3080ImageGrabber/README.txt @@ -0,0 +1,11 @@ +Instructions for running the ADNS3080ImageGrabber.py + +1. Start Arduino and upload the AP_OpticalFlow_test.pde to the APM +2. Install Python 2.7 from http://www.python.org/getit/ +3. Start the Python IDLE editor +4. File, Open, .../arduino-0022/libraries/AP_OpticalFlow/examples/ADNS3080ImageGrabber/ADNS3080ImageGrabber.py +5. Run, Run Module - the Python Shell and then ADNS3080ImageGrabber applications should appear +6. on the ADNS3080ImageGrabber screen, change the default com port, "COM8" to the correct port (sorry, doesn't auto detect) +7. wait a few moments, then push the Send button to start/stop grabbing images from the sensor (a new image should appear every 2 seconds) + +Note: you should see the the AP_OpticalFlow_ADNS3080's menu and any errors appear in the Python Shell \ No newline at end of file diff --git a/lib/hardware/sensors/optic_flow/adns3080/ADNS3080_I2C/ADNS3080.h b/lib/hardware/sensors/optic_flow/adns3080/ADNS3080_I2C/ADNS3080.h new file mode 100644 index 00000000..86b2ca1d --- /dev/null +++ b/lib/hardware/sensors/optic_flow/adns3080/ADNS3080_I2C/ADNS3080.h @@ -0,0 +1,50 @@ +// ADNS3080 hardware config +#define ADNS3080_PIXELS_X 30 +#define ADNS3080_PIXELS_Y 30 +#define ADNS3080_CLOCK_SPEED 24000000 + +// Register Map for the ADNS3080 Optical OpticalFlow Sensor +#define ADNS3080_PRODUCT_ID 0x00 +#define ADNS3080_REVISION_ID 0x01 +#define ADNS3080_MOTION 0x02 +#define ADNS3080_DELTA_X 0x03 +#define ADNS3080_DELTA_Y 0x04 +#define ADNS3080_SQUAL 0x05 +#define ADNS3080_PIXEL_SUM 0x06 +#define ADNS3080_MAXIMUM_PIXEL 0x07 +#define ADNS3080_CONFIGURATION_BITS 0x0a +#define ADNS3080_EXTENDED_CONFIG 0x0b +#define ADNS3080_DATA_OUT_LOWER 0x0c +#define ADNS3080_DATA_OUT_UPPER 0x0d +#define ADNS3080_SHUTTER_LOWER 0x0e +#define ADNS3080_SHUTTER_UPPER 0x0f +#define ADNS3080_FRAME_PERIOD_LOWER 0x10 +#define ADNS3080_FRAME_PERIOD_UPPER 0x11 +#define ADNS3080_MOTION_CLEAR 0x12 +#define ADNS3080_FRAME_CAPTURE 0x13 +#define ADNS3080_SROM_ENABLE 0x14 +#define ADNS3080_FRAME_PERIOD_MAX_BOUND_LOWER 0x19 +#define ADNS3080_FRAME_PERIOD_MAX_BOUND_UPPER 0x1a +#define ADNS3080_FRAME_PERIOD_MIN_BOUND_LOWER 0x1b +#define ADNS3080_FRAME_PERIOD_MIN_BOUND_UPPER 0x1c +#define ADNS3080_SHUTTER_MAX_BOUND_LOWER 0x1e +#define ADNS3080_SHUTTER_MAX_BOUND_UPPER 0x1e +#define ADNS3080_SROM_ID 0x1f +#define ADNS3080_OBSERVATION 0x3d +#define ADNS3080_INVERSE_PRODUCT_ID 0x3f +#define ADNS3080_PIXEL_BURST 0x40 +#define ADNS3080_MOTION_BURST 0x50 +#define ADNS3080_SROM_LOAD 0x60 + +// Configuration Bits +#define ADNS3080_LED_MODE_ALWAYS_ON 0x00 +#define ADNS3080_LED_MODE_WHEN_REQUIRED 0x01 + +#define ADNS3080_RESOLUTION_400 400 +#define ADNS3080_RESOLUTION_1600 1600 + +// Extended Configuration bits +#define ADNS3080_SERIALNPU_OFF 0x02 + +#define ADNS3080_FRAME_RATE_MAX 6469 +#define ADNS3080_FRAME_RATE_MIN 2000 diff --git a/lib/hardware/sensors/optic_flow/adns3080/ADNS3080_I2C/ADNS3080_I2C.pde b/lib/hardware/sensors/optic_flow/adns3080/ADNS3080_I2C/ADNS3080_I2C.pde new file mode 100644 index 00000000..abd99b9b --- /dev/null +++ b/lib/hardware/sensors/optic_flow/adns3080/ADNS3080_I2C/ADNS3080_I2C.pde @@ -0,0 +1,388 @@ +// Test the ADNS3080 Optical Flow Sensor +// based on: Example of AP_OpticalFlow library by Randy Mackay. DIYDrones.com +// + +#include "SPI.h" +#include "ADNS3080.h" + +#define AP_SPI_DATAIN 12 //MISO +#define AP_SPI_DATAOUT 11 //MOSI +#define AP_SPI_CLOCK 13 //SCK +#define ADNS3080_CHIP_SELECT 10 //SS +#define ADNS3080_RESET 9 //RESET + +byte orig_spi_settings_spcr; +byte orig_spi_settings_spsr; +int _cs_pin=ADNS3080_CHIP_SELECT; +int _reset_pin=1; // set to 1 if you have reset connected +unsigned int last_update; +boolean _overflow=false; +boolean _motion=false; +int raw_dx; +int raw_dy; +unsigned int surface_quality; + +void setup() +{ + Serial.begin(115200); + Serial.println("www.bot-thoughts.com\nOptical Flow test program V1.0\n"); + + delay(1000); + + // flowSensor initialization + if( initOF() == false ) + Serial.println("Failed to initialise ADNS3080"); + + delay(1000); +} + +void loop() +{ + int value; + + display_menu(); + + // wait for user to enter something + while( !Serial.available() ) { + delay(20); + } + + // get character from user + value = Serial.read(); + + switch( value ) { + + case 'c' : + //display_config(); + break; + + case 'f' : + //set_frame_rate(); + break; + + case 'i' : + // display image + display_image(); + break; + + case 'I' : + display_image_continuously(); + break; + + case 'm' : + display_motion(); + break; + + case 'r' : + // set resolution + //set_resolution(); + break; + + case 's' : + //set_shutter_speed(); + break; + + case 'z' : + //flowSensor.clear_motion(); + break; + + case '\r' : // ignore return type characters + case '\n' : + break; + + default: + Serial.println("unrecognised command"); + Serial.println(); + break; + } +} + + +///////////////////////////////////////////////////////////////////////////////////////////////////////////// +// DISPLAY FUNCTIONS +///////////////////////////////////////////////////////////////////////////////////////////////////////////// + +// Prints out a list of functions. +void display_menu() +{ + Serial.println(); + Serial.println("please choose from the following options:"); +// Serial.println(" c - display all config"); +// Serial.println(" f - set frame rate"); + Serial.println(" i - display image"); + Serial.println(" I - display image continuously"); + Serial.println(" m - display motion"); +// Serial.println(" r - set resolution"); +// Serial.println(" s - set shutter speed"); +// Serial.println(" z - clear all motion"); +// Serial.println(" a - frame rate auto/manual"); + Serial.println(); +} + + +// Captures and displays image from flowSensor +void display_image() +{ + Serial.println("image data --------------"); + print_pixel_data(&Serial); + Serial.println("-------------------------"); +} + + +// display_image - captures and displays image from flowSensor flowSensor +void display_image_continuously() +{ + int i; + Serial.println("press any key to return to menu"); + + Serial.flush(); + + while( !Serial.available() ) { + display_image(); + i=0; + while( i<20 && !Serial.available() ) { + delay(100); // give the viewer a bit of time to catchup + i++; + } + } + + Serial.flush(); +} + + +// show x,y and squal values constantly until user presses a key +// +void display_motion() +{ + boolean first_time = true; + Serial.flush(); + + // display instructions on how to exit + Serial.println("press x to return to menu.."); + delay(1000); + + while( !Serial.available() ) { + updateOF(); + + // check for errors + if( _overflow ) + Serial.println("overflow!!"); + + // x,y,squal + Serial.print("dx: "); + Serial.print(raw_dx,DEC); + Serial.print("\tdy: "); + Serial.print(raw_dy,DEC); + Serial.print("\tsqual:"); + Serial.print(surface_quality,DEC); + Serial.println(); + first_time = false; + + // short delay + delay(100); + } + + // flush the serial + Serial.flush(); +} + +///////////////////////////////////////////////////////////////////////////////////////////////////////////// +// ADNS3080 SPECIFIC FUNCTIONS +///////////////////////////////////////////////////////////////////////////////////////////////////////////// + +// reset sensor by holding a pin high (or is it low?) for 10us. +void reset() +{ + // return immediately if the reset pin is not defined + if( _reset_pin == 0) + return; + + digitalWrite(_reset_pin,HIGH); // reset sensor + delayMicroseconds(10); + digitalWrite(_reset_pin,LOW); // return sensor to normal +} + + +// Read a register from the sensor +byte read_register(byte address) +{ + byte result = 0, junk = 0; + + backup_spi_settings(); + + // take the chip select low to select the device + digitalWrite(_cs_pin, LOW); + + // send the device the register you want to read: + junk = SPI.transfer(address); + + // small delay + delayMicroseconds(50); + + // send a value of 0 to read the first byte returned: + result = SPI.transfer(0x00); + + // take the chip select high to de-select: + digitalWrite(_cs_pin, HIGH); + + restore_spi_settings(); + + return result; +} + + +// init - initialise sensor +// initCommAPI parameter controls whether SPI interface is initialised (set to false if other devices are on the SPI bus and have already initialised the interface) +boolean initOF() +{ + int retry = 0; + + pinMode(AP_SPI_DATAOUT,OUTPUT); + pinMode(AP_SPI_DATAIN,INPUT); + pinMode(AP_SPI_CLOCK,OUTPUT); + pinMode(_cs_pin,OUTPUT); + if( _reset_pin != 0) + pinMode(ADNS3080_RESET,OUTPUT); + + digitalWrite(_cs_pin,HIGH); // disable device (Chip select is active low) + + // reset the device + reset(); + + // start the SPI library: + SPI.begin(); + + // check the sensor is functioning + if( retry < 3 ) { + if( read_register(ADNS3080_PRODUCT_ID) == 0x17 ) + return true; + retry++; + } + + return false; +} + + +// +// backup_spi_settings - checks current SPI settings (clock speed, etc), sets values to what we need +// +byte backup_spi_settings() +{ + // store current spi values + orig_spi_settings_spcr = SPCR & (DORD | CPOL | CPHA); + orig_spi_settings_spsr = SPSR & SPI2X; + + // set the values that we need + SPI.setBitOrder(MSBFIRST); + SPI.setDataMode(SPI_MODE3); + SPI.setClockDivider(SPI_CLOCK_DIV8); // sensor running at 2Mhz. this is it's maximum speed + + return orig_spi_settings_spcr; +} + + +// restore_spi_settings - restores SPI settings (clock speed, etc) to what their values were before the sensor used the bus +byte restore_spi_settings() +{ + byte temp; + + // restore SPSR + temp = SPSR; + temp &= ~SPI2X; + temp |= orig_spi_settings_spsr; + SPSR = temp; + + // restore SPCR + temp = SPCR; + temp &= ~(DORD | CPOL | CPHA); // zero out the important bits + temp |= orig_spi_settings_spcr; // restore important bits + SPCR = temp; + + return temp; +} + + +// write a value to one of the sensor's registers +void write_register(byte address, byte value) +{ + byte junk = 0; + + backup_spi_settings(); + + // take the chip select low to select the device + digitalWrite(_cs_pin, LOW); + + // send register address + junk = SPI.transfer(address | 0x80 ); + + // small delay + delayMicroseconds(50); + + // send data + junk = SPI.transfer(value); + + // take the chip select high to de-select: + digitalWrite(_cs_pin, HIGH); + + restore_spi_settings(); +} + + +// get_pixel_data - captures an image from the sensor and stores it to the pixe_data array +void print_pixel_data(Stream *serPort) +{ + int i,j; + boolean isFirstPixel = true; + byte regValue; + byte pixelValue; + + // write to frame capture register to force capture of frame + write_register(ADNS3080_FRAME_CAPTURE,0x83); + + // wait 3 frame periods + 10 nanoseconds for frame to be captured + delayMicroseconds(1510); // min frame speed is 2000 frames/second so 1 frame = 500 nano seconds. so 500 x 3 + 10 = 1510 + + // display the pixel data + for( i=0; iprintln("failed to find first pixel"); + } + isFirstPixel = false; + pixelValue = ( regValue << 2); + serPort->print(pixelValue,DEC); + if( j!= ADNS3080_PIXELS_X-1 ) + serPort->print(","); + delayMicroseconds(50); + } + serPort->println(); + } + + // hardware reset to restore sensor to normal operation + reset(); +} + +bool updateOF() +{ + byte motion_reg; + surface_quality = (unsigned int)read_register(ADNS3080_SQUAL); + delayMicroseconds(50); // small delay + + // check for movement, update x,y values + motion_reg = read_register(ADNS3080_MOTION); + _overflow = ((motion_reg & 0x10) != 0); // check if we've had an overflow + if( (motion_reg & 0x80) != 0 ) { + raw_dx = ((char)read_register(ADNS3080_DELTA_X)); + delayMicroseconds(50); // small delay + raw_dy = ((char)read_register(ADNS3080_DELTA_Y)); + _motion = true; + }else{ + raw_dx = 0; + raw_dy = 0; + } + last_update = millis(); + + return true; +} + diff --git a/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/ADNS3080.h b/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/ADNS3080.h new file mode 100644 index 00000000..b759d654 --- /dev/null +++ b/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/ADNS3080.h @@ -0,0 +1,55 @@ +#ifndef _ADNS3030_H +#define _ADNS3030_H + +// ADNS3080 hardware config +#define ADNS3080_PIXELS_X 30 +#define ADNS3080_PIXELS_Y 30 +#define ADNS3080_CLOCK_SPEED 24000000 + +// Register Map for the ADNS3080 Optical OpticalFlow Sensor +#define ADNS3080_PRODUCT_ID 0x00 +#define ADNS3080_REVISION_ID 0x01 +#define ADNS3080_MOTION 0x02 +#define ADNS3080_DELTA_X 0x03 +#define ADNS3080_DELTA_Y 0x04 +#define ADNS3080_SQUAL 0x05 +#define ADNS3080_PIXEL_SUM 0x06 +#define ADNS3080_MAXIMUM_PIXEL 0x07 +#define ADNS3080_CONFIGURATION_BITS 0x0a +#define ADNS3080_EXTENDED_CONFIG 0x0b +#define ADNS3080_DATA_OUT_LOWER 0x0c +#define ADNS3080_DATA_OUT_UPPER 0x0d +#define ADNS3080_SHUTTER_LOWER 0x0e +#define ADNS3080_SHUTTER_UPPER 0x0f +#define ADNS3080_FRAME_PERIOD_LOWER 0x10 +#define ADNS3080_FRAME_PERIOD_UPPER 0x11 +#define ADNS3080_MOTION_CLEAR 0x12 +#define ADNS3080_FRAME_CAPTURE 0x13 +#define ADNS3080_SROM_ENABLE 0x14 +#define ADNS3080_FRAME_PERIOD_MAX_BOUND_LOWER 0x19 +#define ADNS3080_FRAME_PERIOD_MAX_BOUND_UPPER 0x1a +#define ADNS3080_FRAME_PERIOD_MIN_BOUND_LOWER 0x1b +#define ADNS3080_FRAME_PERIOD_MIN_BOUND_UPPER 0x1c +#define ADNS3080_SHUTTER_MAX_BOUND_LOWER 0x1e +#define ADNS3080_SHUTTER_MAX_BOUND_UPPER 0x1e +#define ADNS3080_SROM_ID 0x1f +#define ADNS3080_OBSERVATION 0x3d +#define ADNS3080_INVERSE_PRODUCT_ID 0x3f +#define ADNS3080_PIXEL_BURST 0x40 +#define ADNS3080_MOTION_BURST 0x50 +#define ADNS3080_SROM_LOAD 0x60 + +// Configuration Bits +#define ADNS3080_LED_MODE_ALWAYS_ON 0x00 +#define ADNS3080_LED_MODE_WHEN_REQUIRED 0x01 + +#define ADNS3080_RESOLUTION_400 400 +#define ADNS3080_RESOLUTION_1600 1600 + +// Extended Configuration bits +#define ADNS3080_SERIALNPU_OFF 0x02 + +#define ADNS3080_FRAME_RATE_MAX 6469 +#define ADNS3080_FRAME_RATE_MIN 2000 + +#endif \ No newline at end of file diff --git a/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/LPC_ADNS3080.dep b/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/LPC_ADNS3080.dep new file mode 100644 index 00000000..299b13fd --- /dev/null +++ b/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/LPC_ADNS3080.dep @@ -0,0 +1,214 @@ + + + + 2 + 3344214345 + + Debug + + $TOOLKIT_DIR$\inc\c\ysizet.h + $PROJ_DIR$\digital.h + $PROJ_DIR$\Debug\Exe\LPC_ADNS3080.hex + $TOOLKIT_DIR$\inc\c\ystdio.h + $PROJ_DIR$\Debug\Obj\main.o + $PROJ_DIR$\Debug\Exe\c.out + $TOOLKIT_DIR$\inc\c\yvals.h + $TOOLKIT_DIR$\inc\c\DLib_Threads.h + $TOOLKIT_DIR$\inc\NXP\iolpc2102.h + $PROJ_DIR$\Debug\Obj\main.pbi + $PROJ_DIR$\Debug\Obj\LPC_ADNS3080.pbd + $PROJ_DIR$\main.c + $TOOLKIT_DIR$\inc\c\io_macros.h + $TOOLKIT_DIR$\inc\NXP\iolpc2103.h + $TOOLKIT_DIR$\inc\c\stdio.h + $TOOLKIT_DIR$\inc\c\DLib_Config_Normal.h + $TOOLKIT_DIR$\inc\c\intrinsics.h + $TOOLKIT_DIR$\lib\dl4t_tln.a + $TOOLKIT_DIR$\inc\c\xencoding_limits.h + $TOOLKIT_DIR$\inc\c\DLib_Defaults.h + $TOOLKIT_DIR$\inc\c\ycheck.h + $TOOLKIT_DIR$\inc\c\DLib_Product.h + $TOOLKIT_DIR$\inc\NXP\iolpc2104.h + $PROJ_DIR$\Debug\Obj\serial.pbi + $PROJ_DIR$\Debug\Obj\digital.o + $PROJ_DIR$\Debug\Obj\digital.pbi + $PROJ_DIR$\Debug\Obj\delay.o + $PROJ_DIR$\spi.h + $PROJ_DIR$\digital.c + $PROJ_DIR$\types.h + $PROJ_DIR$\Debug\Obj\spi.pbi + $TOOLKIT_DIR$\lib\m4t_tl.a + $PROJ_DIR$\spi.c + $PROJ_DIR$\serial.h + $PROJ_DIR$\Debug\Obj\spi.o + $PROJ_DIR$\Debug\Obj\serial.o + $TOOLKIT_DIR$\lib\shs_l.a + $PROJ_DIR$\delay.c + $TOOLKIT_DIR$\lib\rt4t_al.a + $PROJ_DIR$\delay.h + $PROJ_DIR$\serial.c + $PROJ_DIR$\ADNS3080.h + $PROJ_DIR$\config\LPC2103_Flash.icf + $PROJ_DIR$\Debug\Obj\delay.pbi + $TOOLKIT_DIR$\inc\NXP\iolpc210x.h + + + [ROOT_NODE] + + + ILINK + 5 + + + + + $PROJ_DIR$\Debug\Exe\c.out + + + OBJCOPY + 2 + + + + + ILINK + 42 26 24 4 35 34 36 38 31 17 + + + + + $PROJ_DIR$\Debug\Obj\LPC_ADNS3080.pbd + + + BILINK + 43 25 9 23 30 + + + + + $PROJ_DIR$\main.c + + + ICCARM + 4 + + + BICOMP + 9 + + + + + ICCARM + 16 20 14 6 19 15 21 18 7 0 3 13 8 12 29 33 39 1 27 41 + + + BICOMP + 16 20 14 6 19 21 18 7 0 3 13 8 12 29 33 39 1 27 41 + + + + + $PROJ_DIR$\digital.c + + + ICCARM + 24 + + + BICOMP + 25 + + + + + ICCARM + 13 8 12 29 + + + BICOMP + 13 8 12 29 + + + + + $PROJ_DIR$\spi.c + + + ICCARM + 34 + + + BICOMP + 30 + + + + + ICCARM + 13 8 12 29 + + + BICOMP + 13 8 12 29 + + + + + $PROJ_DIR$\delay.c + + + ICCARM + 26 + + + BICOMP + 43 + + + + + ICCARM + 13 8 12 + + + BICOMP + 13 8 12 + + + + + $PROJ_DIR$\serial.c + + + ICCARM + 35 + + + BICOMP + 23 + + + + + ICCARM + 16 20 14 6 19 15 21 18 7 0 3 44 22 12 + + + BICOMP + 16 20 14 6 19 21 18 7 0 3 44 22 12 + + + + + + Release + + + [MULTI_TOOL] + ILINK + + + + + diff --git a/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/LPC_ADNS3080.ewp b/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/LPC_ADNS3080.ewp new file mode 100644 index 00000000..6ec784bf --- /dev/null +++ b/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/LPC_ADNS3080.ewp @@ -0,0 +1,1849 @@ + + + + 2 + + Debug + + ARM + + 1 + + General + 3 + + 21 + 1 + 1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ICCARM + 2 + + 28 + 1 + 1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + AARM + 2 + + 8 + 1 + 1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + OBJCOPY + 0 + + 1 + 1 + 1 + + + + + + + + + CUSTOM + 3 + + + + + + + BICOMP + 0 + + + + BUILDACTION + 1 + + + + + + + ILINK + 0 + + 14 + 1 + 1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + IARCHIVE + 0 + + 0 + 1 + 1 + + + + + + + BILINK + 0 + + + + + Release + + ARM + + 0 + + General + 3 + + 21 + 1 + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ICCARM + 2 + + 28 + 1 + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + AARM + 2 + + 8 + 1 + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + OBJCOPY + 0 + + 1 + 1 + 0 + + + + + + + + + CUSTOM + 3 + + + + + + + BICOMP + 0 + + + + BUILDACTION + 1 + + + + + + + ILINK + 0 + + 14 + 1 + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + IARCHIVE + 0 + + 0 + 1 + 0 + + + + + + + BILINK + 0 + + + + + $PROJ_DIR$\delay.c + + + $PROJ_DIR$\delay.h + + + $PROJ_DIR$\digital.c + + + $PROJ_DIR$\digital.h + + + $PROJ_DIR$\main.c + + + $PROJ_DIR$\serial.c + + + $PROJ_DIR$\serial.h + + + $PROJ_DIR$\spi.c + + + $PROJ_DIR$\spi.h + + + $PROJ_DIR$\types.h + + + + diff --git a/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/LPC_ADNS3080.eww b/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/LPC_ADNS3080.eww new file mode 100644 index 00000000..ef6beb22 --- /dev/null +++ b/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/LPC_ADNS3080.eww @@ -0,0 +1,10 @@ + + + + + $WS_DIR$\LPC_ADNS3080.ewp + + + + + diff --git a/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/config/LPC2103_Flash.icf b/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/config/LPC2103_Flash.icf new file mode 100644 index 00000000..6709b362 --- /dev/null +++ b/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/config/LPC2103_Flash.icf @@ -0,0 +1,50 @@ +/*###ICF### Section handled by ICF editor, don't touch! ****/ +/*-Editor annotation file-*/ +/* IcfEditorFile="$TOOLKIT_DIR$\config\ide\IcfEditor\a_v1_0.xml" */ +/*-Specials-*/ +define symbol __ICFEDIT_intvec_start__ = 0x00000000; +/*-Memory Regions-*/ +define symbol __ICFEDIT_region_ROM_start__ = 0x00000000; +define symbol __ICFEDIT_region_ROM_end__ = 0x00007FFF; +define symbol __ICFEDIT_region_RAM_start__ = 0x40000000; +define symbol __ICFEDIT_region_RAM_end__ = 0x40001FDF; +/*-Sizes-*/ +define symbol __ICFEDIT_size_cstack__ = 0x200; +define symbol __ICFEDIT_size_svcstack__ = 0x10; +define symbol __ICFEDIT_size_irqstack__ = 0x50; +define symbol __ICFEDIT_size_fiqstack__ = 0x10; +define symbol __ICFEDIT_size_undstack__ = 0x10; +define symbol __ICFEDIT_size_abtstack__ = 0x10; +define symbol __ICFEDIT_size_heap__ = 0x500; +/**** End of ICF editor section. ###ICF###*/ + +define symbol __CRP_start__ = 0x000001FC; +define symbol __CRP_end__ = 0x000001FF; + +/* Memory used by RealMonitor */ +define symbol __RM_start__ = 0x40000040; +define symbol __RM_end__ = 0x4000011F; + +define memory mem with size = 4G; +define region ROM_region = mem:[from __ICFEDIT_region_ROM_start__ to __ICFEDIT_region_ROM_end__] - mem:[from __CRP_start__ to __CRP_end__]; +define region RAM_region = mem:[from __ICFEDIT_region_RAM_start__ to __ICFEDIT_region_RAM_end__] - mem:[from __RM_start__ to __RM_end__]; +define region CRP_region = mem:[from __CRP_start__ to __CRP_end__]; + +define block CSTACK with alignment = 8, size = __ICFEDIT_size_cstack__ { }; +define block SVC_STACK with alignment = 8, size = __ICFEDIT_size_svcstack__ { }; +define block IRQ_STACK with alignment = 8, size = __ICFEDIT_size_irqstack__ { }; +define block FIQ_STACK with alignment = 8, size = __ICFEDIT_size_fiqstack__ { }; +define block UND_STACK with alignment = 8, size = __ICFEDIT_size_undstack__ { }; +define block ABT_STACK with alignment = 8, size = __ICFEDIT_size_abtstack__ { }; +define block HEAP with alignment = 8, size = __ICFEDIT_size_heap__ { }; + +initialize by copy { readwrite }; +do not initialize { section .noinit }; + +place at address mem:__ICFEDIT_intvec_start__ { readonly section .intvec }; + +place in ROM_region { readonly }; +place in RAM_region { readwrite, + block CSTACK, block SVC_STACK, block IRQ_STACK, block FIQ_STACK, + block UND_STACK, block ABT_STACK, block HEAP }; +place in CRP_region { section .crp }; diff --git a/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/config/LPC2103_RAM.icf b/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/config/LPC2103_RAM.icf new file mode 100644 index 00000000..4bb789b9 --- /dev/null +++ b/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/config/LPC2103_RAM.icf @@ -0,0 +1,45 @@ +/*###ICF### Section handled by ICF editor, don't touch! ****/ +/*-Editor annotation file-*/ +/* IcfEditorFile="$TOOLKIT_DIR$\config\ide\IcfEditor\a_v1_0.xml" */ +/*-Specials-*/ +define symbol __ICFEDIT_intvec_start__ = 0x00000000; +/*-Memory Regions-*/ +define symbol __ICFEDIT_region_ROM_start__ = 0x00000000; +define symbol __ICFEDIT_region_ROM_end__ = 0x00000000; +define symbol __ICFEDIT_region_RAM_start__ = 0x40000040; +define symbol __ICFEDIT_region_RAM_end__ = 0x40001FDF; +/*-Sizes-*/ +define symbol __ICFEDIT_size_cstack__ = 0x200; +define symbol __ICFEDIT_size_svcstack__ = 0x10; +define symbol __ICFEDIT_size_irqstack__ = 0x50; +define symbol __ICFEDIT_size_fiqstack__ = 0x10; +define symbol __ICFEDIT_size_undstack__ = 0x10; +define symbol __ICFEDIT_size_abtstack__ = 0x10; +define symbol __ICFEDIT_size_heap__ = 0x500; +/**** End of ICF editor section. ###ICF###*/ + +/* Memory used by RealMonitor */ +define symbol __RM_start__ = 0x40000040; +define symbol __RM_end__ = 0x4000011F; + +define memory mem with size = 4G; +define region ROM_region = mem:[from __ICFEDIT_region_ROM_start__ to __ICFEDIT_region_ROM_end__]; +define region RAM_region = mem:[from __ICFEDIT_region_RAM_start__ to __ICFEDIT_region_RAM_end__] - mem:[from __RM_start__ to __RM_end__]; + +define block CSTACK with alignment = 8, size = __ICFEDIT_size_cstack__ { }; +define block SVC_STACK with alignment = 8, size = __ICFEDIT_size_svcstack__ { }; +define block IRQ_STACK with alignment = 8, size = __ICFEDIT_size_irqstack__ { }; +define block FIQ_STACK with alignment = 8, size = __ICFEDIT_size_fiqstack__ { }; +define block UND_STACK with alignment = 8, size = __ICFEDIT_size_undstack__ { }; +define block ABT_STACK with alignment = 8, size = __ICFEDIT_size_abtstack__ { }; +define block HEAP with alignment = 8, size = __ICFEDIT_size_heap__ { }; + +initialize by copy { readwrite }; +do not initialize { section .noinit }; + +place at address mem:__ICFEDIT_intvec_start__ { readonly section .intvec }; + +place in RAM_region { readonly }; +place in RAM_region { readwrite, + block CSTACK, block SVC_STACK, block IRQ_STACK, block FIQ_STACK, + block UND_STACK, block ABT_STACK, block HEAP }; diff --git a/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/config/LPC2103_RAM.mac b/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/config/LPC2103_RAM.mac new file mode 100644 index 00000000..8551a3d3 --- /dev/null +++ b/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/config/LPC2103_RAM.mac @@ -0,0 +1,4 @@ +execUserPreload() +{ + __writeMemory32(0x00000002, 0xE01FC040, "Memory"); // MEMMAP = 2; +} diff --git a/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/delay.c b/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/delay.c new file mode 100644 index 00000000..f1f2722d --- /dev/null +++ b/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/delay.c @@ -0,0 +1,30 @@ +#include + +#define MR0I (1<<0) +#define MR0R (1<<1) +#define MR0S (1<<2) + +/** this is pretty half-ass and inaccurate but I'll get to that later */ +void delayMicroseconds(unsigned int us) +{ + // Should probably subtract # of usec it takes to run the following + // 60MHz => 0.01667 usec / instruction + + /* initialize timer */ + T0PR = 15; // Prescaler -- 60MHz /4 = 15MHz /15 = 1MHz + T0TCR = 0x02; // Reset counter and prescale + T0CTCR = 0x0; // Timer0 increments with every rising PCLK + T0MR0 = us; // Set cycle time -- 1MHz so 1usec per LSB + T0MCR = MR0S; // On match0, stop timer + T0EMR = 0x00; // On match do nothing. + T0TCR = 1; // Enable timer + + while (T0TC != us); // stop when T0TC == usec + } + +/** yes I realize this isn't spot-on accurate yet */ +void delay(unsigned int ms) +{ + for (int i=0; i < ms; i++) + delayMicroseconds(1000); +} diff --git a/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/delay.h b/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/delay.h new file mode 100644 index 00000000..a75bc269 --- /dev/null +++ b/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/delay.h @@ -0,0 +1,7 @@ +#ifndef __DELAY_H +#define __DELAY_H + +void delayMicroseconds(unsigned int us); +void delay(unsigned int ms); + +#endif \ No newline at end of file diff --git a/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/digital.c b/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/digital.c new file mode 100644 index 00000000..f8025152 --- /dev/null +++ b/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/digital.c @@ -0,0 +1,24 @@ +#include +#include "types.h" + +/** set a pin as either HIGH or LOW */ +void digitalWrite(int pin, byte value) +{ + if (pin >= 0 && pin < 32) { + if (value == HIGH) { + IOSET = (1<= 0 && pin < 32) { + value = IOPIN & (1< +#include +#include +#include "types.h" +#include "serial.h" +#include "delay.h" +#include "digital.h" +#include "spi.h" +#include "ADNS3080.h" + +#define CSPIN 7 // P0.7 is the SS pin + +unsigned int surface_quality; +int raw_dx; +int raw_dy; +boolean _motion; +boolean _overflow; + +void write_register(byte address, byte value); +byte read_register(byte address); +boolean initOF(void); +boolean updateOF(); + +int main() +{ + ///////// System Clock Initialization ///////// + // Fosc = 12MHz + // MSEL=4, PSEL=1 + // PLLCFG=0100100=0x24=36 + // cclk = 60MHz + // Fcco = 240MHz + PLLCFG = 0x24; + // Enable PLL + PLLCON = 0x1; + PLLFEED = 0xAA; + PLLFEED = 0x55; + // Wait for PLL to achieve lock + while(!(PLLSTAT & 0x400)); + // Connect PLL + PLLCON=0x3; + PLLFEED=0xAA; + PLLFEED=0x55; + + ///////// Peripheral Clock Initialization ///////// + // Set periphery divider + // 0x00 => /4 + // 0x01 => /1 + // 0x02 => /2 + APBDIV_bit.APBDIV = 0x02; + + serialInit(UART0, 115200); + + if (initOF() == false) { + serialPuts(UART0, "SPI Init Error\n"); + } + + while (1) { + updateOF(); + if (_motion == false) + serialPuts(UART0, "no "); + serialPuts(UART0, "motion\n"); + if (_overflow == true) + serialPuts(UART0, "overflow\n"); + serialPuts(UART0, "squal: "); + serialPuti(UART0, surface_quality); + serialPutc(UART0, '\n'); + serialPuti(UART0, raw_dx); + serialPutc(UART0, '\n'); + serialPuti(UART0, raw_dx); + serialPutc(UART0, '\n'); + delay(1000); + } + +} + + + +/** Read a register from the sensor */ +byte read_register(byte address) +{ + byte result = 0; + + // take the chip select low to select the device + digitalWrite(CSPIN, LOW); + + // send the device the register you want to read: + SPI0_transfer(address); + + // small delay + delay(50); + + // send a value of 0 to read the first byte returned: + result = SPI0_transfer(0x00); + + // take the chip select high to de-select: + digitalWrite(CSPIN, HIGH); + + return result; +} + +/** write a value to one of the sensor's registers */ +void write_register(byte address, byte value) +{ + // take the chip select low to select the device + digitalWrite(CSPIN, LOW); + + // send register address + SPI0_transfer(address | 0x80 ); + + // small delay + delay(50); + + // send data + SPI0_transfer(value); + + // take the chip select high to de-select: + digitalWrite(CSPIN, HIGH); +} + + +// init - initialise sensor +// initCommAPI parameter controls whether SPI interface is initialised (set to false if other devices are on the SPI bus and have already initialised the interface) +boolean initOF() +{ + int retry = 0; + + digitalWrite(CSPIN,HIGH); // disable device (Chip select is active low) + SPI0_Init(); + + // reset the device + //reset(); + + // check the sensor is functioning + if( retry < 3 ) { + if( read_register(ADNS3080_PRODUCT_ID) == 0x17 ) + return true; + retry++; + } + + return false; +} + +/** update motion */ +boolean updateOF() +{ + byte motion_reg; + surface_quality = (unsigned int)read_register(ADNS3080_SQUAL); + delay(50); // small delay + + // check for movement, update x,y values + motion_reg = read_register(ADNS3080_MOTION); + _overflow = ((motion_reg & 0x10) != 0); // check if we've had an overflow + if( (motion_reg & 0x80) != 0 ) { + raw_dx = ((char)read_register(ADNS3080_DELTA_X)); + delay(50); // small delay + raw_dy = ((char)read_register(ADNS3080_DELTA_Y)); + delay(50); + _motion = true; + }else{ + raw_dx = 0; + raw_dy = 0; + } + //last_update = millis(); + + return true; +} + diff --git a/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/serial.c b/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/serial.c new file mode 100644 index 00000000..e5e129ae --- /dev/null +++ b/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/serial.c @@ -0,0 +1,178 @@ +#include +#include +#include + +#define TEMT (1<<6) + +void serialInit(unsigned char dev, unsigned int baud) +{ + unsigned char error=0; + unsigned int fdr, dll, dlm; + + /* settings from http://prototalk.net/forums/showthread.php?t=11 */ + /* based on 30MHz PCLK */ + + /* this is inelegant but who cares */ + switch (baud) { + case 115200 : // verified on PC + fdr=0xe5; + dlm=0x0; + dll=0x0c; + break; + case 57600 : // verified on PC + fdr=0x75; + dlm=0x0; + dll=0x13; + break; + case 38400 : // verified on PC + fdr=0x72; + dlm=0x0; + dll=0x26; + break; + case 28800 : // verified on PC + fdr=0xd5; + dlm=0x00; + dll=0x2f; + break; + case 19200 : // verified on PC + fdr=0x83; + dlm=0x0; + dll=0x47; + break; + case 14400 : // verified on PC + fdr=0x52; + dlm=0x0; + dll=0x5d; + break; + case 9600 : // verified on PC + fdr=0xb1; + dlm=0; + dll=0xb3; + break; + case 4800 : // verified on PC + fdr=0x52; + dlm=0x01; + dll=0x17; + break; + case 2400 : // verified on PC + fdr=0x31; + dlm=0x02; + dll=0x4a; + break; + case 1200 : // verified on PC + fdr=0x21; + dlm=0x04; + dll=0x12; + break; + case 300 : // verified on PC + fdr=0x10; + dlm=0x18; + dll=0x6a; + break; + default: + error = 1; + break; + } + + if (error == 0) { + switch (dev) { + case 0 : + /* Initialize Pin Select Block for Tx and Rx */ + PINSEL0=0x5; // 3:2,1:0 = %01 + /* Enable FIFO's and reset them */ + U0FCR=0x7; + /* Set DLAB and word length set to 8bits */ + U0LCR=0x83; // 8 bits, 1 stop, no parity, DLAB = 1 + /* Set baud rate */ + U0FDR = fdr; + U0DLL = dll; + U0DLM = dlm; + /* Clear DLAB */ + U0LCR=0x03; // 8 bits, 1 stop, no parity, DLAB = 0 + break; + case 1 : + /* Initialize Pin Select Block for Tx and Rx */ + PINSEL0=0x50000; // 19:18, 17:16 = %01 + /* Enable FIFO's and reset them */ + U1FCR=0x7; + /* Set DLAB and word length set to 8bits */ + U1LCR=0x83; // 8 bits, 1 stop, no parity, DLAB = 1 + /* Set baud rate */ + U1FDR = fdr; + U1DLL = dll; + U1DLM = dlm; + /* Clear DLAB */ + U1LCR=0x03; // 8 bits, 1 stop, no parity, DLAB = 0 + default : + break; + } + } + +} // serialInit() + + +unsigned char serialEmptyTX(unsigned char dev) +{ + unsigned char result; + + switch (dev) { + case 0 : + result = (U0LSR & TEMT); + break; + case 1 : + result = (U1LSR & TEMT); + break; + default : + break; + } + return result; +} + + +void serialPutc(unsigned char dev, char c) +{ + switch (dev) { + case 0 : + U0THR=c; + break; + case 1 : + U1THR=c; + default : + break; + } + while (!serialEmptyTX(dev)) + return; +} + +void serialPuti(unsigned char dev, int i) +{ + char digit = 0; + int place = 10000000; + + // Deal with negatives + if (i < 0) { + serialPutc(dev, '-'); + i = -i; + } + + // Strip off the leading zeros + while (i/place == 0 && place > 1) + place /= 10; + + // Print the rest of the integer + while (place) { + digit = i / place; + i %= place; + serialPutc(dev, digit+'0'); + place /= 10; + } +} + + +void serialPuts(unsigned char dev, char *c) +{ + while (*c) + serialPutc(dev, *c++); +} + + diff --git a/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/serial.h b/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/serial.h new file mode 100644 index 00000000..8d3879a5 --- /dev/null +++ b/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/serial.h @@ -0,0 +1,13 @@ +#ifndef __UART_H +#define __UART_H + +#define UART0 0 +#define UART1 1 + +void serialInit(unsigned char dev, unsigned int baud); +void serialPutc(unsigned char dev, char c); +void serialPuti(unsigned char dev, int i); +void serialPuts(unsigned char dev, char *c); +unsigned char serialEmptyTX(unsigned char dev); + +#endif \ No newline at end of file diff --git a/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/settings/LPC_ADNS3080.cspy.bat b/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/settings/LPC_ADNS3080.cspy.bat new file mode 100644 index 00000000..3f8f84d6 --- /dev/null +++ b/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/settings/LPC_ADNS3080.cspy.bat @@ -0,0 +1,15 @@ +@REM This batch file has been generated by the IAR Embedded Workbench +@REM C-SPY Debugger, as an aid to preparing a command line for running +@REM the cspybat command line utility using the appropriate settings. +@REM +@REM You can launch cspybat by typing the name of this batch file followed +@REM by the name of the debug file (usually an ELF/DWARF or UBROF file). +@REM Note that this file is generated every time a new debug session +@REM is initialized, so you may want to move or rename the file before +@REM making changes. +@REM + + +"C:\Program Files\IAR Systems\Embedded Workbench 6.0 Kickstart\common\bin\cspybat" "C:\Program Files\IAR Systems\Embedded Workbench 6.0 Kickstart\arm\bin\armproc.dll" "C:\Program Files\IAR Systems\Embedded Workbench 6.0 Kickstart\arm\bin\armsim2.dll" %1 --plugin "C:\Program Files\IAR Systems\Embedded Workbench 6.0 Kickstart\arm\bin\armbat.dll" --backend -B "--endian=little" "--cpu=ARM7TDMI-S" "--fpu=None" "-p" "C:\Program Files\IAR Systems\Embedded Workbench 6.0 Kickstart\arm\CONFIG\debugger\NXP\iolpc2103.ddf" "--semihosting" "--device=LPC2103" + + diff --git a/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/settings/LPC_ADNS3080.dbgdt b/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/settings/LPC_ADNS3080.dbgdt new file mode 100644 index 00000000..e068f91d --- /dev/null +++ b/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/settings/LPC_ADNS3080.dbgdt @@ -0,0 +1,5 @@ + + + + + diff --git a/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/settings/LPC_ADNS3080.dni b/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/settings/LPC_ADNS3080.dni new file mode 100644 index 00000000..c2210b02 --- /dev/null +++ b/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/settings/LPC_ADNS3080.dni @@ -0,0 +1,36 @@ +[Stack] +FillEnabled=0 +OverflowWarningsEnabled=1 +WarningThreshold=90 +SpWarningsEnabled=1 +WarnLogOnly=1 +UseTrigger=1 +TriggerName=main +LimitSize=0 +ByteLimit=50 +[InterruptLog] +LogEnabled=0 +SumEnabled=0 +GraphEnabled=0 +ShowTimeLog=1 +ShowTimeSum=1 +SumSortOrder=0 +[Disassemble mode] +mode=0 +[Breakpoints2] +Count=0 +[Interrupts] +Enabled=1 +[MemoryMap] +Enabled=0 +Base=0 +UseAuto=0 +TypeViolation=1 +UnspecRange=1 +ActionState=1 +[Aliases] +Count=0 +SuppressDialog=0 +[Trace1] +Enabled=0 +ShowSource=1 diff --git a/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/settings/LPC_ADNS3080.wsdt b/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/settings/LPC_ADNS3080.wsdt new file mode 100644 index 00000000..0db388de --- /dev/null +++ b/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/settings/LPC_ADNS3080.wsdt @@ -0,0 +1,221 @@ + + + + + + LPC_ADNS3080/Debug + + + + + + + 312 + 27 + 27 + 27 + + + + 20 + 1010 + 269 + 67 + + + + + + + TabID-4046-9934 + Workspace + Workspace + + + LPC_ADNS3080 + + + + + 0 + + + + + TabID-27989-10509 + Build + Build + + + + 0 + + + + + + TextEditor + $WS_DIR$\main.c + 0 + 35 + 424 + 424 + + + TextEditor + $WS_DIR$\delay.c + 0 + 0 + 354 + 354 + + + TextEditor + $WS_DIR$\delay.h + 0 + 0 + 78 + 78 + + + TextEditor + $WS_DIR$\digital.c + 0 + 0 + 45 + 45 + + + TextEditor + $WS_DIR$\digital.h + 0 + 0 + 105 + 105 + + + TextEditor + $WS_DIR$\types.h + 0 + 0 + 146 + 146 + + + TextEditor + $WS_DIR$\spi.h + 0 + 0 + 84 + 84 + + + TextEditor + $WS_DIR$\spi.c + 0 + 9 + 778 + 778 + + 7 + + TextEditor + $WS_DIR$\ADNS3080.h + 0 + 0 + 40 + 40 + + + TextEditor + $WS_DIR$\serial.h + 0 + 0 + 168 + 168 + + + TextEditor + $WS_DIR$\serial.c + 0 + 108 + 2653 + 2653 + + + 0 + + + 1000000 + 1000000 + + + 1 + + + + + + + iaridepm.enu1 + + + + + + + + + + -2 + -2 + 564 + 386 + -2 + -2 + 200 + 200 + 174520 + 214823 + 338569 + 607948 + + + + + + + + + + + + + + + + -2 + -2 + 323 + 1148 + -2 + -2 + 1150 + 325 + 1003490 + 349087 + 174520 + 214823 + + + + + + + + + + + + + diff --git a/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/spi.c b/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/spi.c new file mode 100644 index 00000000..186cc19b --- /dev/null +++ b/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/spi.c @@ -0,0 +1,44 @@ +#include +#include "types.h" + +#define SPIF (1<<7) + +/** Init SP0 for use with the ADNS3080 */ +// TODO: Add speed option +// TODO: Add SPI1 +void SPI0_Init() +{ + /* configure pin connect block + * 15:14 == 00 ->> GPIO (master mode) P0.7 + * 13:12 == 01 ->> MOSI0, P0.6 + * 11:10 == 01 ->> MISO0, P0.5 + * 9:8 == 01 ->> SCK0, P0.4 + */ + PINSEL0 |= 0x1500; + // pin direction is controlled automatically if not GPIO + IODIR |= (1<<7); // P0.7 ->> SS + + /* Set SPI speed in SPI Clock Counter Register + * The SPI0 rate may be calculated as: PC LK / SPCCR0 value. The PCLK rate is + * CCLK /APB divider rate as determined by the APBDIV register contents. + * Assuming pclk = 60MHz/2 = 30MHz, /16 = 1.875MHz, 2Mhz max speed for ADNS3080 + * SPCCR must be even and > 8 + */ + S0SPCCR=16; + + /* Device selected as master in SPI Control Register */ + S0SPCR=0x20; +} + + +/** Transfer a byte of data over SPI0 */ +byte SPI0_transfer(byte data) +{ + /* write data out */ + S0SPDR=data; + /* wait for transfer to compelte*/ + while(!(S0SPSR & SPIF)); + + /* read data */ + return S0SPDR; +} \ No newline at end of file diff --git a/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/spi.h b/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/spi.h new file mode 100644 index 00000000..cb2a1fba --- /dev/null +++ b/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/spi.h @@ -0,0 +1,7 @@ +#ifndef _SPI_H +#define _SPI_H + +void SPI0_Init(void); +byte SPI0_transfer(byte data); + +#endif \ No newline at end of file diff --git a/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/types.h b/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/types.h new file mode 100644 index 00000000..6f0b0670 --- /dev/null +++ b/lib/hardware/sensors/optic_flow/adns3080/LPC_ADNS3080/types.h @@ -0,0 +1,13 @@ +#ifndef _TYPES_H +#define _TYPES_H + +#define HIGH 1 +#define LOW 0 + +#define true 1 +#define false 1 + +typedef unsigned char byte; +typedef unsigned char boolean; + +#endif diff --git a/lib/hardware/sensors/optic_flow/adns3080/README.md b/lib/hardware/sensors/optic_flow/adns3080/README.md new file mode 100644 index 00000000..37f4f8ce --- /dev/null +++ b/lib/hardware/sensors/optic_flow/adns3080/README.md @@ -0,0 +1,6 @@ +Software for ADNS3080 optical flow sensor + +* ```ADNS3080Demo/``` - demo firmware for the ADNS3080 based heavily on an older version of [ArduPilot](https://github.com/diydrones/ardupilot) OpticalFlowcode by Randy Mackay. +* ```ADNS3080ImageGrabber/``` - python script to grab image from sensor over serial +* ```LPC_ADNS3080/``` - demo for LPC2103 (ARM7) +* ```ADNS3080_I2C/``` - test from ArduoPilot (Randy Mackay)