diff --git a/.gitignore b/.gitignore index ca86d3acd..4a051ff57 100644 --- a/.gitignore +++ b/.gitignore @@ -25,6 +25,7 @@ *.c64 *.cc2538dk *.remote +*.jn516x *.srf06-cc26xx *.ev-aducrf101mkxz *.report diff --git a/.travis.yml b/.travis.yml index b426b7c8b..7a9affd3c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -74,6 +74,22 @@ before_script: cc65 --version ; fi + ## Install NXP toolchain + - if [ ${BUILD_ARCH:-0} = jn516x ] ; then + $WGET http://simonduq.github.io/resources/ba-elf-gcc-4.7.4-part1.tar.bz2 && + $WGET http://simonduq.github.io/resources/ba-elf-gcc-4.7.4-part2.tar.bz2 && + $WGET http://simonduq.github.io/resources/jn516x-sdk-4163.tar.bz2 && + mkdir /tmp/jn516x-sdk /tmp/ba-elf-gcc && + tar xjf jn516x-sdk-*.tar.bz2 -C /tmp/jn516x-sdk && + tar xjf ba-elf-gcc-*part1.tar.bz2 -C /tmp/ba-elf-gcc && + tar xjf ba-elf-gcc-*part2.tar.bz2 -C /tmp/ba-elf-gcc && + sudo cp -f -r /tmp/jn516x-sdk /usr/ && + sudo cp -f -r /tmp/ba-elf-gcc /usr/ && + export PATH=/usr/ba-elf-gcc/bin:$PATH && + rm -rf /tmp/ba-elf-gcc* /tmp/jn516x-sdk* && + ba-elf-gcc --version ; + fi + ## Compile cooja.jar only when it's going to be needed - if [ ${BUILD_CATEGORY:-sim} = sim ] ; then java -version && @@ -121,5 +137,6 @@ env: - BUILD_TYPE='compile-arm-apcs-ports' BUILD_CATEGORY='compile' BUILD_ARCH='arm-apcs' - BUILD_TYPE='compile-6502-ports' BUILD_CATEGORY='compile' BUILD_ARCH='6502' - BUILD_TYPE='compile-arm-ports' BUILD_CATEGORY='compile' BUILD_ARCH='arm-aapcs' + - BUILD_TYPE='compile-nxp-ports' BUILD_CATEGORY='compile' BUILD_ARCH='jn516x' - BUILD_TYPE='slip-radio' MAKE_TARGETS='cooja' - BUILD_TYPE='llsec' MAKE_TARGETS='cooja' diff --git a/examples/jn516x/README.md b/examples/jn516x/README.md new file mode 100644 index 000000000..06ccc0da7 --- /dev/null +++ b/examples/jn516x/README.md @@ -0,0 +1,5 @@ +Examples for the JN516x platform. +* dr1175: simple Contiki application for the DR1175 evaluation board. Prints out sensor values periodically. +* rime: simple Rime example. Works with ContikiMAC (default) or NullRDC +* RPL: RPL examples, including border router, simple node, and coap resources. More information under rpl/README.md + \ No newline at end of file diff --git a/examples/jn516x/dr1175-sensors/Makefile b/examples/jn516x/dr1175-sensors/Makefile new file mode 100644 index 000000000..3fbf3a246 --- /dev/null +++ b/examples/jn516x/dr1175-sensors/Makefile @@ -0,0 +1,12 @@ +CONTIKI=../../.. +CONTIKI_PROJECT = node +CFLAGS += -DPROJECT_CONF_H=\"project-conf.h\" + +TARGET ?= jn516x +JN516x_WITH_DR1175 = 1 + +CONTIKI_WITH_RIME = 1 + +all: $(CONTIKI_PROJECT) + +include $(CONTIKI)/Makefile.include diff --git a/examples/jn516x/dr1175-sensors/README.md b/examples/jn516x/dr1175-sensors/README.md new file mode 100644 index 000000000..0b49024c2 --- /dev/null +++ b/examples/jn516x/dr1175-sensors/README.md @@ -0,0 +1,2 @@ +Sensor test for DR1175 evaluation board (light + temp/humidity). +Reads and prints out various sensor samples every second. diff --git a/examples/jn516x/dr1175-sensors/node.c b/examples/jn516x/dr1175-sensors/node.c new file mode 100644 index 000000000..bf1b4c89b --- /dev/null +++ b/examples/jn516x/dr1175-sensors/node.c @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2015, SICS Swedish ICT. + * 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 Institute 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 INSTITUTE 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 INSTITUTE 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. + * + */ +/** + * \author Atis Elsts + * \file + * Sensor test for DR1175 evaluation board (light + temp/humidity). + */ + +#include "contiki.h" + +#include "light-sensor.h" +#include "ht-sensor.h" +#include "leds.h" + +/*---------------------------------------------------------------------------*/ +PROCESS(test_process, "Sensor test process"); +AUTOSTART_PROCESSES(&test_process); +/*---------------------------------------------------------------------------*/ +PROCESS_THREAD(test_process, ev, data) +{ + static struct etimer et; + static uint8_t led_status; + uint8_t r, g, b; + int val; + + PROCESS_BEGIN(); + + puts("initializing sensors..."); + + /* Make sensor active for measuring */ + SENSORS_ACTIVATE(light_sensor); + SENSORS_ACTIVATE(ht_sensor); + + /* Set level for LEDSs */ + leds_set_level(255, LEDS_RED | LEDS_GREEN | LEDS_BLUE | LEDS_WHITE); + + while(1) { + etimer_set(&et, CLOCK_SECOND * 1); + + PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et)); + + puts("reading sensors..."); + + val = ht_sensor.value(HT_SENSOR_HUM); + printf("humidity: %d\n", val); + + val = ht_sensor.value(HT_SENSOR_TEMP); + printf("temperature: %d\n", val); + + led_status++; + r = ((led_status & 0x1) ? LEDS_RED : 0); + g = ((led_status & 0x2) ? LEDS_GREEN : 0); + b = ((led_status & 0x4) ? LEDS_BLUE : 0); + + leds_toggle((leds_get() ^ (r | g | b)) | LEDS_WHITE); + + puts(""); + } + PROCESS_END(); +} +/*---------------------------------------------------------------------------*/ diff --git a/examples/jn516x/dr1175-sensors/project-conf.h b/examples/jn516x/dr1175-sensors/project-conf.h new file mode 100644 index 000000000..906efff45 --- /dev/null +++ b/examples/jn516x/dr1175-sensors/project-conf.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2015, SICS Swedish ICT. + * 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 Institute 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 INSTITUTE 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 INSTITUTE 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. + * + */ +/** + * \author Atis Elsts + */ + +#ifndef __PROJECT_CONF_H__ +#define __PROJECT_CONF_H__ + +#undef NETSTACK_CONF_RDC +#undef NETSTACK_CONF_FRAMER +#undef NETSTACK_CONF_MAC +#undef NETSTACK_CONF_NETWORK + +#define NETSTACK_CONF_RDC nullrdc_driver +#define NETSTACK_CONF_FRAMER framer_802154 +#define NETSTACK_CONF_MAC csma_driver +#define NETSTACK_CONF_NETWORK rime_driver + +#endif /* __PROJECT_CONF_H__ */ diff --git a/examples/jn516x/rime/Makefile b/examples/jn516x/rime/Makefile new file mode 100644 index 000000000..02262937e --- /dev/null +++ b/examples/jn516x/rime/Makefile @@ -0,0 +1,11 @@ +CONTIKI=../../.. +CONTIKI_PROJECT = node +CFLAGS += -DPROJECT_CONF_H=\"project-conf.h\" + +TARGET ?= jn516x + +CONTIKI_WITH_RIME = 1 + +all: $(CONTIKI_PROJECT) + +include $(CONTIKI)/Makefile.include diff --git a/examples/jn516x/rime/README.md b/examples/jn516x/rime/README.md new file mode 100644 index 000000000..1f693c6ae --- /dev/null +++ b/examples/jn516x/rime/README.md @@ -0,0 +1 @@ +A simple Rime + ContikiMAC code example. diff --git a/examples/jn516x/rime/node.c b/examples/jn516x/rime/node.c new file mode 100644 index 000000000..261fd61ad --- /dev/null +++ b/examples/jn516x/rime/node.c @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2015, SICS Swedish ICT. + * 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 Institute 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 INSTITUTE 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 INSTITUTE 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. + * + */ +/** + * \author Atis Elsts + * \file + * ContikiMAC + Rime stack test for JN516x platform. + */ + +#include "contiki-conf.h" +#include "net/rime/rime.h" + +#if 0 +#define RX_ADDR1 140 +#define RX_ADDR2 228 +#else +#define RX_ADDR1 7 +#define RX_ADDR2 0 +#endif + +#define MAX_RETRANSMISSIONS 4 + +/*---------------------------------------------------------------------------*/ +PROCESS(unicast_test_process, "ContikiMAC Node"); +AUTOSTART_PROCESSES(&unicast_test_process); + +static void +recv_runicast(struct runicast_conn *c, const linkaddr_t *from, uint8_t seqno) +{ + printf("runicast message received from %d.%d, seqno %d, len %d: '%s'\n", + from->u8[0], from->u8[1], seqno, packetbuf_datalen(), (char *)packetbuf_dataptr()); +} +static void +sent_runicast(struct runicast_conn *c, const linkaddr_t *to, uint8_t retransmissions) +{ + printf("runicast message sent to %d.%d, retransmissions %d\n", + to->u8[0], to->u8[1], retransmissions); +} +static void +timedout_runicast(struct runicast_conn *c, const linkaddr_t *to, uint8_t retransmissions) +{ + printf("runicast message timed out when sending to %d.%d, retransmissions %d\n", + to->u8[0], to->u8[1], retransmissions); +} +static const struct runicast_callbacks runicast_callbacks = { recv_runicast, + sent_runicast, + timedout_runicast }; +static struct runicast_conn runicast; +/*---------------------------------------------------------------------------*/ +PROCESS_THREAD(unicast_test_process, ev, data) +{ + PROCESS_BEGIN(); + + puts("unicast test start"); + + runicast_open(&runicast, 144, &runicast_callbacks); + + /* Receiver node: do nothing */ + if(linkaddr_node_addr.u8[0] == RX_ADDR1 && + linkaddr_node_addr.u8[1] == RX_ADDR2) { + puts("wait forever"); + } + while(1) { + static struct etimer et; + static int seqno; + + etimer_set(&et, CLOCK_SECOND * 5); + + PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et)); + + if(linkaddr_node_addr.u8[0] == RX_ADDR1 && + linkaddr_node_addr.u8[1] == RX_ADDR2) { + puts("tick..."); + continue; + } + + if(!runicast_is_transmitting(&runicast)) { + linkaddr_t recv = { 0 }; + static char buffer[100] = "hello"; + + packetbuf_copyfrom(buffer, sizeof(buffer)); + recv.u8[0] = RX_ADDR1; + recv.u8[1] = RX_ADDR2; + + printf("%u.%u: sending runicast to address %u.%u\n", + linkaddr_node_addr.u8[0], + linkaddr_node_addr.u8[1], + recv.u8[0], + recv.u8[1]); + + packetbuf_set_attr(PACKETBUF_ATTR_PACKET_ID, ++seqno); + runicast_send(&runicast, &recv, MAX_RETRANSMISSIONS); + } + } + + PROCESS_END(); +} +/*---------------------------------------------------------------------------*/ diff --git a/examples/jn516x/rime/project-conf.h b/examples/jn516x/rime/project-conf.h new file mode 100644 index 000000000..84e1cae06 --- /dev/null +++ b/examples/jn516x/rime/project-conf.h @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2015, SICS Swedish ICT. + * 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 Institute 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 INSTITUTE 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 INSTITUTE 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. + * + */ +/** + * \author Atis Elsts + */ + +#ifndef __PROJECT_CONF_H__ +#define __PROJECT_CONF_H__ + +#undef NETSTACK_CONF_RDC +#undef NETSTACK_CONF_FRAMER +#undef NETSTACK_CONF_MAC +#undef NETSTACK_CONF_NETWORK + +#if 1 +#define NETSTACK_CONF_RDC contikimac_driver +#define NETSTACK_CONF_FRAMER contikimac_framer +#else +#define NETSTACK_CONF_RDC nullrdc_driver +#define NETSTACK_CONF_FRAMER framer_802154 +#endif + +#define NETSTACK_CONF_MAC csma_driver +#define NETSTACK_CONF_NETWORK rime_driver + +#undef UIP_CONF_IPV6 +#define UIP_CONF_IPV6 0 + +#undef RF_CHANNEL +#define RF_CHANNEL 25 + +#undef MICROMAC_CONF_CHANNEL +#define MICROMAC_CONF_CHANNEL RF_CHANNEL + +#undef CC2420_CONF_CHANNEL +#define CC2420_CONF_CHANNEL RF_CHANNEL + +#undef MICROMAC_CONF_AUTOACK +#define MICROMAC_CONF_AUTOACK 1 + +#endif /* __PROJECT_CONF_H__ */ diff --git a/examples/jn516x/rpl/README.md b/examples/jn516x/rpl/README.md new file mode 100644 index 000000000..39a213268 --- /dev/null +++ b/examples/jn516x/rpl/README.md @@ -0,0 +1,43 @@ +# HOWTO - Setting up the RPL Border router and other nodes + +In this folder we have a fully functional demonstrator with the components: + +1. **RPL border router**: to start the wireless network and connect it to other networks. +2. and a **wireless node** that acts as a basic RPL node by default (but can optionally be used configured as DAG Root) + +## RICH RPL Border Router + +Setup the UART flow-control mode for the router from border-router/project-conf.h + +* Enable either **HW flow control** +```C +#define UART_HW_FLOW_CTRL 1 +#define UART_XONXOFF_FLOW_CTRL 0 +``` +* or **SW flow control** +```C +#define UART_HW_FLOW_CTRL 0 +#define UART_XONXOFF_FLOW_CTRL 1 +``` +* You can disable both, but it is not recommended. + +Compile and flash a node with the rpl-border-router.jn516x.bin image. Either a USB dongle or a dev-board would work. + +From a Linux terminal, go to `contiki/examples/jn516x/rpl/border-router` and do either +`make connect-router-hw` if you have **HW flow control** +or `make connect-router-sw` if you have **SW flow control** + +This will start a tunnel interface (tun0) on the host machine. +All traffic towards our network (prefix aaaa::1/64) will now be routed to the border router. + +## RPL Node + +The directory contiki-private/examples/jn516x/rpl/node contains a basic RICH node running TSCH and RPL. +You can compile and program more NXP nodes to run this, forming a larger network. +You should be able to ping the nodes (you can obtain their IPv6 address either directly from their log output +or by enabling DEBUG output in rpl-icmp6.c and looking at DAO prefixes being added. + +## RPL+CoAP Nodes + +coap-*-node are example nodes that expose their sensors as CoAP resources. See README.md files from the sub-directories +for more details. diff --git a/examples/jn516x/rpl/border-router/Makefile b/examples/jn516x/rpl/border-router/Makefile new file mode 100644 index 000000000..53598e492 --- /dev/null +++ b/examples/jn516x/rpl/border-router/Makefile @@ -0,0 +1,31 @@ +CONTIKI_PROJECT = border-router +all: $(CONTIKI_PROJECT) + +TARGET ?= jn516x + +CONTIKI=../../../.. + +CONTIKI_WITH_IPV6 = 1 + +PROJECTDIRS += .. ../tools +PROJECT_SOURCEFILES += rpl-tools.c +CFLAGS += -DPROJECT_CONF_H=\"project-conf.h\" +PROJECT_SOURCEFILES += slip-bridge.c slip.c + +ifeq ($(PREFIX),) + PREFIX = aaaa::1/64 +endif + +include $(CONTIKI)/Makefile.include + +#using XON/XOFF flow control +connect-router-sw: $(CONTIKI)/tools/tunslip6 + sudo $(CONTIKI)/tools/tunslip6 -X -B 1000000 $(PREFIX) + +#using hw flow control +connect-router-hw: $(CONTIKI)/tools/tunslip6 + sudo $(CONTIKI)/tools/tunslip6 -H -B 1000000 $(PREFIX) + +#using no flow control +connect-router-no: $(CONTIKI)/tools/tunslip6 + sudo $(CONTIKI)/tools/tunslip6 -B 1000000 $(PREFIX) diff --git a/examples/jn516x/rpl/border-router/README.md b/examples/jn516x/rpl/border-router/README.md new file mode 100644 index 000000000..c2af3f3b6 --- /dev/null +++ b/examples/jn516x/rpl/border-router/README.md @@ -0,0 +1,10 @@ +A RPL border router. +To indicate the hardware target for the border router, add one of the following +options in the command line: +If rpl-border-router runs on dongle: +JN516x_WITH_DONGLE=1 +If rpl-border-router runs on DR1174: +JN516x_WITH_DR1174=1 +If building for a new platform, first execute : make clean + +See ../README.md for more. \ No newline at end of file diff --git a/examples/jn516x/rpl/border-router/border-router.c b/examples/jn516x/rpl/border-router/border-router.c new file mode 100644 index 000000000..d36130607 --- /dev/null +++ b/examples/jn516x/rpl/border-router/border-router.c @@ -0,0 +1,97 @@ +/* + * 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 Institute 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 INSTITUTE 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 INSTITUTE 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. + * + * This file is part of the Contiki operating system. + * + */ + +#include "contiki.h" +#include "net/rpl/rpl.h" +#include "tools/rpl-tools.h" + +#define DEBUG DEBUG_PRINT +#include "net/ip/uip-debug.h" + +static uip_ipaddr_t prefix; +static uint8_t prefix_set; + +PROCESS(border_router_process, "Border router process"); + +AUTOSTART_PROCESSES(&border_router_process); + +/*---------------------------------------------------------------------------*/ +void +request_prefix(void) +{ + /* mess up uip_buf with a dirty request... */ + uip_buf[0] = '?'; + uip_buf[1] = 'P'; +/* uip_buf[2] = '\n'; */ + uip_len = 2; + slip_send(); + uip_len = 0; +} +/*---------------------------------------------------------------------------*/ +void +set_prefix_64(uip_ipaddr_t *prefix_64) +{ + memcpy(&prefix, prefix_64, 16); + prefix_set = 1; +} +/*---------------------------------------------------------------------------*/ +PROCESS_THREAD(border_router_process, ev, data) +{ + static struct etimer et; + + PROCESS_BEGIN(); + +/* While waiting for the prefix to be sent through the SLIP connection, the future + * border router can join an existing DAG as a parent or child, or acquire a default + * router that will later take precedence over the SLIP fallback interface. + * Prevent that by turning the radio off until we are initialized as a DAG root. + */ + prefix_set = 0; + + PROCESS_PAUSE(); + + PRINTF("RPL-Border router started\n"); + + /* Request prefix until it has been received */ + while(!prefix_set) { + etimer_set(&et, CLOCK_SECOND); + request_prefix(); + PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et)); + PRINTF("Waiting for prefix\n"); + } + + PRINTF("Obtained prefix: "); + uip_debug_ipaddr_print(&prefix); + PRINTF("\n"); + + rpl_tools_init(&prefix); + + PROCESS_END(); +} +/*---------------------------------------------------------------------------*/ diff --git a/examples/jn516x/rpl/border-router/project-conf.h b/examples/jn516x/rpl/border-router/project-conf.h new file mode 100644 index 000000000..2489905a6 --- /dev/null +++ b/examples/jn516x/rpl/border-router/project-conf.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2015, SICS Swedish ICT. + * 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 Institute 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 INSTITUTE 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 INSTITUTE 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. + * + */ + +/** + * \author Simon Duquennoy + */ + +#ifndef BR_PROJECT_CONF_H_ +#define BR_PROJECT_CONF_H_ + +#ifndef UIP_FALLBACK_INTERFACE +#define UIP_FALLBACK_INTERFACE rpl_interface +#endif + +/* Needed for slip-bridge */ +#undef SLIP_BRIDGE_CONF_NO_PUTCHAR +#define SLIP_BRIDGE_CONF_NO_PUTCHAR 0 + +#include "../common-conf.h" + +#endif /* PROJECT_CONF_H_ */ diff --git a/examples/jn516x/rpl/border-router/slip-bridge.c b/examples/jn516x/rpl/border-router/slip-bridge.c new file mode 100644 index 000000000..e3b0f814b --- /dev/null +++ b/examples/jn516x/rpl/border-router/slip-bridge.c @@ -0,0 +1,161 @@ +/* + * Copyright (c) 2010, SICS Swedish ICT. + * 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 Institute 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 INSTITUTE 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 INSTITUTE 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. + * + */ + +/** + * \file + * Slip fallback interface + * \author + * Niclas Finne + * Joakim Eriksson + * Joel Hoglund + * Nicolas Tsiftes + */ + +#include "net/ip/uip.h" +#include "net/ipv6/uip-ds6.h" +#include "dev/slip.h" +#if CONTIKI_TARGET_JN516X +#include "dev/uart0.h" +#else +#include "dev/uart1.h" +#endif +#include + +#define UIP_IP_BUF ((struct uip_ip_hdr *)&uip_buf[UIP_LLH_LEN]) + +#define DEBUG DEBUG_NONE +#include "net/ip/uip-debug.h" + +#ifndef BAUD2UBR +#define BAUD2UBR(X) (X) +#endif + +void set_prefix_64(uip_ipaddr_t *); + +static uip_ipaddr_t last_sender; +/*---------------------------------------------------------------------------*/ +static void +slip_input_callback(void) +{ + PRINTF("SIN: %u\n", uip_len); + if(uip_buf[0] == '!') { + PRINTF("Got configuration message of type %c\n", uip_buf[1]); + uip_len = 0; + if(uip_buf[1] == 'P') { + uip_ipaddr_t prefix; + /* Here we set a prefix !!! */ + memset(&prefix, 0, 16); + memcpy(&prefix, &uip_buf[2], 8); + PRINTF("Setting prefix "); + PRINT6ADDR(&prefix); + PRINTF("\n"); + set_prefix_64(&prefix); + } + } else if(uip_buf[0] == '?') { + PRINTF("Got request message of type %c\n", uip_buf[1]); + if(uip_buf[1] == 'M') { + char *hexchar = "0123456789abcdef"; + int j; + /* this is just a test so far... just to see if it works */ + uip_buf[0] = '!'; + for(j = 0; j < 8; j++) { + uip_buf[2 + j * 2] = hexchar[uip_lladdr.addr[j] >> 4]; + uip_buf[3 + j * 2] = hexchar[uip_lladdr.addr[j] & 15]; + } + uip_len = 18; + slip_send(); + } + uip_len = 0; + } + /* Save the last sender received over SLIP to avoid bouncing the + packet back if no route is found */ + uip_ipaddr_copy(&last_sender, &UIP_IP_BUF->srcipaddr); +} +/*---------------------------------------------------------------------------*/ +static void +init(void) +{ + slip_arch_init(BAUD2UBR(115200)); + process_start(&slip_process, NULL); + slip_set_input_callback(slip_input_callback); +} +/*---------------------------------------------------------------------------*/ +static void +output(void) +{ + if(uip_ipaddr_cmp(&last_sender, &UIP_IP_BUF->srcipaddr)) { + /* Do not bounce packets back over SLIP if the packet was received + over SLIP */ + PRINTF("slip-bridge: Destination off-link but no route src="); + PRINT6ADDR(&UIP_IP_BUF->srcipaddr); + PRINTF(" dst="); + PRINT6ADDR(&UIP_IP_BUF->destipaddr); + PRINTF("\n"); + } else { + PRINTF("SUT: %u\n", uip_len); + slip_send(); + printf("\n"); + } +} +/*---------------------------------------------------------------------------*/ +#if !SLIP_BRIDGE_CONF_NO_PUTCHAR +#undef putchar +int +putchar(int c) +{ +#define SLIP_END 0300 + static char debug_frame = 0; + + if(!debug_frame) { /* Start of debug output */ + slip_arch_writeb(SLIP_END); + slip_arch_writeb('\r'); /* Type debug line == '\r' */ + debug_frame = 1; + } + + /* Need to also print '\n' because for example COOJA will not show + any output before line end */ + slip_arch_writeb((char)c); + + /* + * Line buffered output, a newline marks the end of debug output and + * implicitly flushes debug output. + */ + if(c == '\n') { + slip_arch_writeb(SLIP_END); + debug_frame = 0; + } + return c; +} +#endif +/*---------------------------------------------------------------------------*/ +const struct uip_fallback_interface rpl_interface = { + init, output +}; +/*---------------------------------------------------------------------------*/ diff --git a/examples/jn516x/rpl/coap-dongle-node/Makefile b/examples/jn516x/rpl/coap-dongle-node/Makefile new file mode 100644 index 000000000..1a4afa652 --- /dev/null +++ b/examples/jn516x/rpl/coap-dongle-node/Makefile @@ -0,0 +1,21 @@ +CONTIKI_PROJECT = dongle-node +all: $(CONTIKI_PROJECT) + +TARGET ?= jn516x +JN516x_WITH_DONGLE = 1 + +CONTIKI=../../../.. + +CONTIKI_WITH_IPV6 = 1 + +PROJECTDIRS += .. ../tools +PROJECT_SOURCEFILES += rpl-tools.c +CFLAGS += -DPROJECT_CONF_H=\"project-conf.h\" + +CFLAGS += -DWITH_COAP +CFLAGS += -DUIP_CONF_TCP=0 +APPS = json +APPS += er-coap +APPS += rest-engine + +include $(CONTIKI)/Makefile.include diff --git a/examples/jn516x/rpl/coap-dongle-node/README.md b/examples/jn516x/rpl/coap-dongle-node/README.md new file mode 100644 index 000000000..2a4ed6183 --- /dev/null +++ b/examples/jn516x/rpl/coap-dongle-node/README.md @@ -0,0 +1,16 @@ +dongle-node is an example of a RICH node containing a JN516x microcontroller on a USB dongle. +The dongle is part of the NXP JN516x Evaluation Kit (see http://www.nxp.com/documents/leaflet/75017368.pdf) +The dongle-node connects to the network in the same way as described in `examples\jn5168/rpl/README.md` + +The dongle contains 2 LEDs that are available as a CoAP resource. They can be accessed via a CoAP client at the IPv6 interface +of the border router (e.g. via Copper plug-in on Firefox). +The following list gives an overview of the resources: + +URI Description +--- ----------- +Dongle\LED-toggle When doing a PUT/POST method on this resource (no payload needed), the LEDs will run through + the following states with wrap-around: + - GREEN LED on + - RED LED on + - All LEDs off + - RED and GREEN LED alternatively on with 1 sec period time diff --git a/examples/jn516x/rpl/coap-dongle-node/dongle-node.c b/examples/jn516x/rpl/coap-dongle-node/dongle-node.c new file mode 100644 index 000000000..c49bc9e7c --- /dev/null +++ b/examples/jn516x/rpl/coap-dongle-node/dongle-node.c @@ -0,0 +1,145 @@ +/* + * Copyright (c) 2015 NXP B.V. + * 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 NXP B.V. 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 NXP B.V. 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 NXP B.V. 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. + * + * This file is part of the Contiki operating system. + * + * Author: Theo van Daele + * + */ +#include "contiki.h" +#include "net/ip/uip.h" +#include "tools/rpl-tools.h" +#include "rest-engine.h" +#include "sys/ctimer.h" +#include +#include "dev/leds.h" + +static void ct_callback(void *ptr); +static void put_post_led_toggle_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); + +static char content[REST_MAX_CHUNK_SIZE]; +static int content_len = 0; +static struct ctimer ct; + +#define CONTENT_PRINTF(...) { if(content_len < sizeof(content)) { content_len += snprintf(content + content_len, sizeof(content) - content_len, __VA_ARGS__); } } + +/* On dongle, LEDs are connected anti-parallel to DIO pins. */ + +#define TOGGLE_TIME CLOCK_SECOND +/*---------------------------------------------------------------------------*/ +PROCESS(start_app, "START_APP"); +AUTOSTART_PROCESSES(&start_app); +/*---------------------------------------------------------------------------*/ + +/* Call back for led toggle timer to toggle leds */ +static void +ct_callback(void *ptr) +{ + static uint8 toggle_status = 0; + if(toggle_status) { + leds_set(LEDS_RED); + } else { + leds_set(LEDS_GREEN); + } ctimer_restart(&ct); + toggle_status ^= 0x01; +} +/*********** CoAP sensor/ resource ************************************************/ +RESOURCE(resource_led_toggle, + "title=\"Led_toggle\"", + NULL, + put_post_led_toggle_handler, + put_post_led_toggle_handler, + NULL); +static void +put_post_led_toggle_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) +{ + static int led_state = 0; + const uint8_t *request_content; + int request_content_len; + unsigned int accept = -1; + + /* Given the way the LEDs are connected to the DIO ports, the LEDs are controlled via direct DIO access. */ + content_len = 0; + switch(led_state) { + case (0): + ctimer_stop(&ct); + leds_set(LEDS_GREEN); /* Only LEDS_GREEN on */ + CONTENT_PRINTF("Message from resource: Green LED on"); + led_state = 1; + break; + case (1): + leds_set(LEDS_RED); /* Only LEDS_RED on */ + CONTENT_PRINTF("Message from resource: Red LED on"); + led_state = 2; + break; + case (2): + leds_set(0); /* All LEDS off */ + CONTENT_PRINTF("Message from resource: All LEDs off"); + led_state = 3; + break; + case 3: + /* Both leds toggle */ + CONTENT_PRINTF("Message from resource: LEDs toggle"); + ctimer_restart(&ct); + led_state = 0; + default: + break; + } + /* Return message */ + REST.get_header_accept(request, &accept); + if(accept == -1 || accept == REST.type.TEXT_PLAIN) { + REST.set_header_content_type(response, REST.type.TEXT_PLAIN); + REST.set_response_payload(response, (uint8_t *)content, content_len); + } +} +/*---------------------------------------------------------------------------*/ +PROCESS_THREAD(start_app, ev, data) +{ + PROCESS_BEGIN(); + static int is_coordinator = 0; + + /* Switch off dongle leds */ + + /* Initialise ct timer, but don't let it run yet */ + ctimer_set(&ct, TOGGLE_TIME, ct_callback, NULL); + ctimer_stop(&ct); + + /* Start net stack */ + if(is_coordinator) { + uip_ipaddr_t prefix; + uip_ip6addr(&prefix, 0xaaaa, 0, 0, 0, 0, 0, 0, 0); + rpl_tools_init(&prefix); + } else { + rpl_tools_init(NULL); + } printf("Starting RPL node\n"); + + rest_init_engine(); + rest_activate_resource(&resource_led_toggle, "Dongle/LED-toggle"); + + PROCESS_END(); +} diff --git a/examples/jn516x/rpl/coap-dongle-node/project-conf.h b/examples/jn516x/rpl/coap-dongle-node/project-conf.h new file mode 100644 index 000000000..4c2ecd648 --- /dev/null +++ b/examples/jn516x/rpl/coap-dongle-node/project-conf.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2015, SICS Swedish ICT. + * 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 Institute 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 INSTITUTE 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 INSTITUTE 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. + * + */ +/** + * \author Simon Duquennoy + */ + +#ifndef __PROJECT_CONF_H__ +#define __PROJECT_CONF_H__ + +#include "../common-conf.h" + +#endif /* __PROJECT_CONF_H__ */ diff --git a/examples/jn516x/rpl/coap-dr1175-node/Makefile b/examples/jn516x/rpl/coap-dr1175-node/Makefile new file mode 100644 index 000000000..f7960dcd1 --- /dev/null +++ b/examples/jn516x/rpl/coap-dr1175-node/Makefile @@ -0,0 +1,21 @@ +CONTIKI_PROJECT = dr1175-node +all: $(CONTIKI_PROJECT) + +TARGET ?= jn516x +JN516x_WITH_DR1175 = 1 + +CONTIKI=../../../.. + +CONTIKI_WITH_IPV6 = 1 + +PROJECTDIRS += .. ../tools +PROJECT_SOURCEFILES += rpl-tools.c +CFLAGS += -DPROJECT_CONF_H=\"project-conf.h\" + +CFLAGS += -DWITH_COAP +CFLAGS += -DUIP_CONF_TCP=0 +APPS = json +APPS += er-coap +APPS += rest-engine + +include $(CONTIKI)/Makefile.include diff --git a/examples/jn516x/rpl/coap-dr1175-node/README.md b/examples/jn516x/rpl/coap-dr1175-node/README.md new file mode 100644 index 000000000..6be19ab6d --- /dev/null +++ b/examples/jn516x/rpl/coap-dr1175-node/README.md @@ -0,0 +1,24 @@ +dr1175-node is an example of a RICH node containing a JN516x microcontroller on a DR1174 baseboard. +A DR1175 shield is mounted on the baseboard. +The boards are part of the NXP JN516x Evaluation Kit (see http://www.nxp.com/documents/leaflet/75017368.pdf) +The dr1175-node connects to the network in the same way as described in `examples\jn5168/rpl/README.md` + +The resources on the DR1175 are available as CoAP resources. They can be accessed via a CoAP client at the IPv6 interface +of the border router (e.g. via Copper plug-in on Firefox). +The following list gives an overview of the resources: + +URI Description +--- ----------- +DR1175\AllSensors This is an observable resource that shows the status of the humidity, light and temperature sensor. + The resource is automatically updated when a change in the value of the sensor data occurs. +DR1175\ColorLED\RGBValue With this resource, the level and color of the RGB LED can be set. + The output is set as 3 numbers (R, G and B) from 0..255, separated with a space +DR1175\Humidity\Unit This resource will return the unit of the humidity sensor +DR1175\Humidity\Value This resource will return the value of the humidity sensor +DR1175\LightSensor\Unit This resource will return the unit of the light sensor +DR1175\LightSensor\Value This resource will return the value of the light sensor +DR1175\Temperature\Unit This resource will return the unit of the temperature sensor +DR1175\Temperature\Value This resource will return the value of the temperature sensor +DR1175\WhiteLED This resource will set the level of 3 white power LEDs. Level is from 0..255 +DR1174\D3On1174 This resource control LED D3 on the base board +DR1174\D6On1174 This resource control LED D6 on the base board \ No newline at end of file diff --git a/examples/jn516x/rpl/coap-dr1175-node/dr1175-node.c b/examples/jn516x/rpl/coap-dr1175-node/dr1175-node.c new file mode 100644 index 000000000..f6eba5f32 --- /dev/null +++ b/examples/jn516x/rpl/coap-dr1175-node/dr1175-node.c @@ -0,0 +1,395 @@ +/* + * Copyright (c) 2015 NXP B.V. + * 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 NXP B.V. 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 NXP B.V. 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 NXP B.V. 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. + * + * This file is part of the Contiki operating system. + * + * Author: Theo van Daele + * + */ + +#include "contiki.h" +#include "net/ip/uip.h" +#include "tools/rpl-tools.h" +#include "rest-engine.h" +#include "light-sensor.h" +#include "ht-sensor.h" +#include "dev/leds.h" +#include "sys/etimer.h" +#include + +static void event_sensors_dr1175_handler(void); +static void get_sensors_dr1175_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); +static void get_light_sensor_value_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); +static void get_light_sensor_unit_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); +static void get_temperature_value_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); +static void get_temperature_unit_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); +static void get_humidity_value_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); +static void get_humidity_unit_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); +static void put_post_white_led_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); +static void put_post_rgb_led_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); +static void put_post_led_d3_1174_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); +static void put_post_led_d6_1174_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); + +static char content[REST_MAX_CHUNK_SIZE]; +static int content_len = 0; + +#define CONTENT_PRINTF(...) { if(content_len < sizeof(content)) { content_len += snprintf(content + content_len, sizeof(content) - content_len, __VA_ARGS__); } } + +#define CLIP(value, level) if(value > level) { \ + value = level; \ +} +#define SET_LED(LED) if(atoi((const char *)request_content) != 0) { \ + leds_on(LED); \ + } else { \ + leds_off(LED); \ + } +/*---------------------------------------------------------------------------*/ +PROCESS(start_app, "START_APP"); +AUTOSTART_PROCESSES(&start_app, &sensors_process); + +/*---------------------------------------------------------------------------*/ + +/*********** CoAP sensor/ resource *************************************************/ + +/*******************************************************************/ +/* Observable resource and event handler to obtain all sensor data */ +/*******************************************************************/ +EVENT_RESOURCE(resource_sensors_dr1175, /* name */ + "obs;title=\"All_DR1175_sensors\"", /* attributes */ + get_sensors_dr1175_handler, /* GET handler */ + NULL, /* POST handler */ + NULL, /* PUT handler */ + NULL, /* DELETE handler */ + event_sensors_dr1175_handler); /* event handler */ +static void +get_sensors_dr1175_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) +{ + unsigned int accept = -1; + REST.get_header_accept(request, &accept); + if(accept == -1 || accept == REST.type.APPLICATION_JSON) { + content_len = 0; + CONTENT_PRINTF("{\"DR1175\":["); + CONTENT_PRINTF("{\"Humidity\":\"%d\"},", ht_sensor.value(HT_SENSOR_HUM)); + CONTENT_PRINTF("{\"Light\":\"%d\"},", light_sensor.value(0)); + CONTENT_PRINTF("{\"Temp\":\"%d\"}", ht_sensor.value(HT_SENSOR_TEMP)); + CONTENT_PRINTF("]}"); + REST.set_header_content_type(response, REST.type.APPLICATION_JSON); + REST.set_response_payload(response, (uint8_t *)content, content_len); + } +} +static void +event_sensors_dr1175_handler() +{ + /* Registered observers are notified and will trigger the GET handler to create the response. */ + REST.notify_subscribers(&resource_sensors_dr1175); +} +/*****************************************************/ +/* Resource and handler to obtain light sensor value */ +/*****************************************************/ +RESOURCE(resource_light_sensor_value, + "title=\"light sensor value\"", + get_light_sensor_value_handler, + NULL, + NULL, + NULL); +static void +get_light_sensor_value_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) +{ + unsigned int accept = -1; + REST.get_header_accept(request, &accept); + if(accept == -1 || accept == REST.type.TEXT_PLAIN) { + content_len = 0; + CONTENT_PRINTF("%d", light_sensor.value(0)); + REST.set_header_content_type(response, REST.type.TEXT_PLAIN); + REST.set_response_payload(response, (uint8_t *)content, content_len); + } +} +/***************************************************/ +/* Resource and handler to obtain light unit value */ +/***************************************************/ +RESOURCE(resource_light_sensor_unit, + "title=\"light sensor unit\"", + get_light_sensor_unit_handler, + NULL, + NULL, + NULL); +static void +get_light_sensor_unit_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) +{ + unsigned int accept = -1; + REST.get_header_accept(request, &accept); + if(accept == -1 || accept == REST.type.TEXT_PLAIN) { + content_len = 0; + CONTENT_PRINTF("Lux"); + REST.set_header_content_type(response, REST.type.TEXT_PLAIN); + REST.set_response_payload(response, (uint8_t *)content, content_len); + } +} +/***********************************************************/ +/* Resource and handler to obtain temperature sensor value */ +/***********************************************************/ +RESOURCE(resource_temperature_value, + "title=\"temperature value\"", + get_temperature_value_handler, + NULL, + NULL, + NULL); +static void +get_temperature_value_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) +{ + unsigned int accept = -1; + REST.get_header_accept(request, &accept); + if(accept == -1 || accept == REST.type.TEXT_PLAIN) { + content_len = 0; + CONTENT_PRINTF("%d", ht_sensor.value(HT_SENSOR_TEMP)); + REST.set_header_content_type(response, REST.type.TEXT_PLAIN); + REST.set_response_payload(response, (uint8_t *)content, content_len); + } +} +/*********************************************************/ +/* Resource and handler to obtain temperature unit value */ +/*********************************************************/ +RESOURCE(resource_temperature_unit, + "title=\"temperature unit\"", + get_temperature_unit_handler, + NULL, + NULL, + NULL); +static void +get_temperature_unit_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) +{ + unsigned int accept = -1; + REST.get_header_accept(request, &accept); + if(accept == -1 || accept == REST.type.TEXT_PLAIN) { + content_len = 0; + CONTENT_PRINTF("degrees C"); + REST.set_header_content_type(response, REST.type.TEXT_PLAIN); + REST.set_response_payload(response, (uint8_t *)content, content_len); + } +} +/********************************************************/ +/* Resource and handler to obtain humidity sensor value */ +/********************************************************/ +RESOURCE(resource_humidity_value, + "title=\"humidity value\"", + get_humidity_value_handler, + NULL, + NULL, + NULL); +static void +get_humidity_value_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) +{ + unsigned int accept = -1; + REST.get_header_accept(request, &accept); + if(accept == -1 || accept == REST.type.TEXT_PLAIN) { + content_len = 0; + CONTENT_PRINTF("%d", ht_sensor.value(HT_SENSOR_HUM)); + REST.set_header_content_type(response, REST.type.TEXT_PLAIN); + REST.set_response_payload(response, (uint8_t *)content, content_len); + } +} +/******************************************************/ +/* Resource and handler to obtain humidity unit value */ +/******************************************************/ +RESOURCE(resource_humidity_unit, + "title=\"humidity unit\"", + get_humidity_unit_handler, + NULL, + NULL, + NULL); +static void +get_humidity_unit_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) +{ + unsigned int accept = -1; + REST.get_header_accept(request, &accept); + if(accept == -1 || accept == REST.type.TEXT_PLAIN) { + content_len = 0; + CONTENT_PRINTF("relative %%"); + REST.set_header_content_type(response, REST.type.TEXT_PLAIN); + REST.set_response_payload(response, (uint8_t *)content, content_len); + } +} +/***************************************************/ +/* Resource and handler to control White LED level */ +/***************************************************/ +RESOURCE(resource_white_led, + "title=\"WhiteLED <[0..255]>\"", + NULL, + put_post_white_led_handler, + put_post_white_led_handler, + NULL); +static void +put_post_white_led_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) +{ + const uint8_t *request_content = NULL; + int request_content_len; + int level; + + unsigned int accept = -1; + REST.get_header_accept(request, &accept); + if(accept == -1 || accept == REST.type.TEXT_PLAIN) { + request_content_len = REST.get_request_payload(request, &request_content); + level = atoi((const char *)request_content); + CLIP(level, 255) + leds_set_level(level, LEDS_WHITE); + } +} +/*************************************************/ +/* Resource and handler to control RGB LED level */ +/*************************************************/ +RESOURCE(resource_rgb_led, + "title=\"RGB LED <[0..255] [0..255] [0..255]>\"", + NULL, + put_post_rgb_led_handler, + put_post_rgb_led_handler, + NULL); +static void +put_post_rgb_led_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) +{ + const uint8_t *request_content = NULL; + int request_content_len; + char *pch; + int RGB[] = { 0, 0, 0 }; + int index = 0; + + unsigned int accept = -1; + REST.get_header_accept(request, &accept); + if(accept == -1 || accept == REST.type.TEXT_PLAIN) { + request_content_len = REST.get_request_payload(request, &request_content); + pch = strtok((char *)request_content, " "); + while((pch != NULL) && (index != sizeof(RGB) / sizeof(int))) { + /* Convert token to int */ + RGB[index] = atoi(pch); + CLIP(RGB[index], 255) + index++; + /* Get next token */ + pch = strtok(NULL, " "); + } + leds_set_level(RGB[0], LEDS_RED); + leds_set_level(RGB[1], LEDS_GREEN); + leds_set_level(RGB[2], LEDS_BLUE); + } +} +/************************************************/ +/* Resource and handler to control D3 on DR1174 */ +/************************************************/ +RESOURCE(resource_led_d3_1174, + "title=\"LED D3 1174<[0,1]>\"", + NULL, + put_post_led_d3_1174_handler, + put_post_led_d3_1174_handler, + NULL); +static void +put_post_led_d3_1174_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) +{ + const uint8_t *request_content; + int request_content_len; + unsigned int accept = -1; + REST.get_header_accept(request, &accept); + if(accept == -1 || accept == REST.type.TEXT_PLAIN) { + request_content_len = REST.get_request_payload(request, &request_content); + SET_LED(LEDS_GP0); + } +} +/************************************************/ +/* Resource and handler to control D6 on DR1174 */ +/************************************************/ +RESOURCE(resource_led_d6_1174, + "title=\"LED D6 1174<[0,1]>\"", + NULL, + put_post_led_d6_1174_handler, + put_post_led_d6_1174_handler, + NULL); +static void +put_post_led_d6_1174_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) +{ + const uint8_t *request_content; + int request_content_len; + unsigned int accept = -1; + REST.get_header_accept(request, &accept); + if(accept == -1 || accept == REST.type.TEXT_PLAIN) { + request_content_len = REST.get_request_payload(request, &request_content); + SET_LED(LEDS_GP1); + } +} +/*---------------------------------------------------------------------------*/ +PROCESS_THREAD(start_app, ev, data) +{ + PROCESS_BEGIN(); + + static int is_coordinator = 0; + static struct etimer et; + + /* Make sensor active for measuring */ + SENSORS_ACTIVATE(light_sensor); + SENSORS_ACTIVATE(ht_sensor); + + /* Start net stack */ + if(is_coordinator) { + uip_ipaddr_t prefix; + uip_ip6addr(&prefix, 0xaaaa, 0, 0, 0, 0, 0, 0, 0); + rpl_tools_init(&prefix); + } else { + rpl_tools_init(NULL); + } printf("Starting RPL node\n"); + + rest_init_engine(); + rest_activate_resource(&resource_light_sensor_value, "DR1175/LightSensor/Value"); + rest_activate_resource(&resource_light_sensor_unit, "DR1175/LightSensor/Unit"); + rest_activate_resource(&resource_temperature_unit, "DR1175/Temperature/Unit"); + rest_activate_resource(&resource_temperature_value, "DR1175/Temperature/Value"); + rest_activate_resource(&resource_humidity_unit, "DR1175/Humidity/Unit"); + rest_activate_resource(&resource_humidity_value, "DR1175/Humidity/Value"); + rest_activate_resource(&resource_white_led, "DR1175/WhiteLED"); + rest_activate_resource(&resource_rgb_led, "DR1175/ColorLED/RGBValue"); + rest_activate_resource(&resource_led_d3_1174, "DR1175/LED/D3On1174"); + rest_activate_resource(&resource_led_d6_1174, "DR1175/LED/D6On1174"); + rest_activate_resource(&resource_sensors_dr1175, "DR1175/AllSensors"); + + /* Level of LEDS=0, so no light after start-up */ + leds_on(LEDS_WHITE | LEDS_RED | LEDS_GREEN | LEDS_BLUE); + + /* contiki-jn516x-main switches all leds off after process start-up. + Switch on required leds after rescheduling, otherwise level change needs to be + accompanied with leds_on() at least once in resource handler. */ + etimer_set(&et, CLOCK_SECOND / 10); + PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et)); + /* Level of LEDS=0, so no light after start-up. However, they are enabled + A level change will directly be visible. */ + leds_on(LEDS_WHITE | LEDS_RED | LEDS_GREEN | LEDS_BLUE); + + /* If sensor process generates an event, call event_handler of resource. + This will make this resource observable by the client */ + while(1) { + PROCESS_WAIT_EVENT_UNTIL((ev == sensors_event) && + ((data == &light_sensor) || (data == &ht_sensor))); + event_sensors_dr1175_handler(); + } + + PROCESS_END(); +} diff --git a/examples/jn516x/rpl/coap-dr1175-node/project-conf.h b/examples/jn516x/rpl/coap-dr1175-node/project-conf.h new file mode 100644 index 000000000..4c2ecd648 --- /dev/null +++ b/examples/jn516x/rpl/coap-dr1175-node/project-conf.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2015, SICS Swedish ICT. + * 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 Institute 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 INSTITUTE 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 INSTITUTE 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. + * + */ +/** + * \author Simon Duquennoy + */ + +#ifndef __PROJECT_CONF_H__ +#define __PROJECT_CONF_H__ + +#include "../common-conf.h" + +#endif /* __PROJECT_CONF_H__ */ diff --git a/examples/jn516x/rpl/coap-dr1199-node/Makefile b/examples/jn516x/rpl/coap-dr1199-node/Makefile new file mode 100644 index 000000000..5a649e429 --- /dev/null +++ b/examples/jn516x/rpl/coap-dr1199-node/Makefile @@ -0,0 +1,21 @@ +CONTIKI_PROJECT = dr1199-node +all: $(CONTIKI_PROJECT) + +TARGET ?= jn516x +JN516x_WITH_DR1199 = 1 + +CONTIKI=../../../.. + +CONTIKI_WITH_IPV6 = 1 + +PROJECTDIRS += .. ../tools +PROJECT_SOURCEFILES += rpl-tools.c +CFLAGS += -DPROJECT_CONF_H=\"project-conf.h\" + +CFLAGS += -DWITH_COAP +CFLAGS += -DUIP_CONF_TCP=0 +APPS = json +APPS += er-coap +APPS += rest-engine + +include $(CONTIKI)/Makefile.include diff --git a/examples/jn516x/rpl/coap-dr1199-node/README.md b/examples/jn516x/rpl/coap-dr1199-node/README.md new file mode 100644 index 000000000..e9a6ee66b --- /dev/null +++ b/examples/jn516x/rpl/coap-dr1199-node/README.md @@ -0,0 +1,33 @@ +dr1199-node is an example of a RICH node containing a JN516x microcontroller on a DR1174 baseboard. +A DR1199 shield is mounted on the baseboard. +The boards are part of the NXP JN516x Evaluation Kit (see http://www.nxp.com/documents/leaflet/75017368.pdf) +The dr1199-node connects to the network in the same way as described in `examples\jn5168/rpl/README.md` + +The resources on the DR1199 are available as CoAP resources. They can be accessed via a CoAP client at the IPv6 interface +of the border router (e.g. via Copper plug-in on Firefox). +The following list gives an overview of the resources: + +URI Description +--- ----------- +DR1199\AllSensors This is an observable resource that shows the status of all switches and the potentiometer on the board + The resource is automatically updated when a change of the status/value of the switches and potentiometer + takes place. +DR1199\LED\All When writing a '1', LEDs D1..D3 will switch ON + When writing a '0', LEDs D1..D3 will switch OFF +DR1199\LED\D1 When writing a '1', LED D1 will switch ON + When writing a '0', LED D1 will switch OFF +DR1199\LED\D2 When writing a '1', LED D2 will switch ON + When writing a '0', LED D2 will switch OFF +DR1199\LED\D3 When writing a '1', LED D3 will switch ON + When writing a '0', LED D3 will switch OFF +DR1199\D3On1174 This resource control LED D3 on the base board +DR1199\D6On1174 This resource control LED D6 on the base board +DR1199\Potentiometer The resource will show the value of the potentiometer +DR1199\Switch\DIO8 This resource shows the status of the DIO8 switch (on DR1174) +DR1199\Switch\SW1 This resource shows the status of the SW1 switch +DR1199\Switch\SW2 This resource shows the status of the SW2 switch +DR1199\Switch\SW3 This resource shows the status of the SW3 switch +DR1199\Switch\SW4 This resource shows the status of the SW4 switch + + + diff --git a/examples/jn516x/rpl/coap-dr1199-node/dr1199-node.c b/examples/jn516x/rpl/coap-dr1199-node/dr1199-node.c new file mode 100644 index 000000000..91921fed1 --- /dev/null +++ b/examples/jn516x/rpl/coap-dr1199-node/dr1199-node.c @@ -0,0 +1,389 @@ +/* + * Copyright (c) 2015 NXP B.V. + * 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 NXP B.V. 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 NXP B.V. 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 NXP B.V. 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. + * + * This file is part of the Contiki operating system. + * + * Author: Theo van Daele + * + */ +#include "contiki.h" +#include "net/ip/uip.h" +#include "tools/rpl-tools.h" +#include "rest-engine.h" +#include "dev/leds.h" +#include "button-sensor.h" +#include "pot-sensor.h" +#include + +static char content[REST_MAX_CHUNK_SIZE]; +static int content_len = 0; + +static void event_sensors_dr1199_handler(); +static void get_sensors_dr1199_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); +static void get_switch_sw1_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); +static void get_switch_sw2_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); +static void get_switch_sw3_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); +static void get_switch_sw4_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); +static void get_switch_dio8_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); +static void get_pot_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); +static void put_post_led_d1_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); +static void put_post_led_d2_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); +static void put_post_led_d3_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); +static void put_post_led_d3_1174_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); +static void put_post_led_d6_1174_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); +static void put_post_led_all_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset); + +#define CONTENT_PRINTF(...) { if(content_len < sizeof(content)) { content_len += snprintf(content + content_len, sizeof(content) - content_len, __VA_ARGS__); } } + +#define PARSE_SWITCH(POSITION) if(button_sensor.value(0) & (1 << POSITION)) { \ + CONTENT_PRINTF("PRESSED"); \ + } else { \ + CONTENT_PRINTF("RELEASED"); \ + } + +#define SET_LED(LED) if(atoi((const char *)request_content) != 0) { \ + leds_on(LED); \ + } else { \ + leds_off(LED); \ + } + +/*---------------------------------------------------------------------------*/ +PROCESS(start_app, "START_APP"); +AUTOSTART_PROCESSES(&sensors_process, &start_app); + +/*---------------------------------------------------------------------------*/ + +/*********** CoAP sensor/ resource *************************************************/ + +/*******************************************************************/ +/* Observable resource and event handler to obtain all sensor data */ +/*******************************************************************/ +EVENT_RESOURCE(resource_sensors_dr1199, /* name */ + "obs;title=\"All_DR1199_sensors\"", /* attributes */ + get_sensors_dr1199_handler, /* GET handler */ + NULL, /* POST handler */ + NULL, /* PUT handler */ + NULL, /* DELETE handler */ + event_sensors_dr1199_handler); /* event handler */ +static void +get_sensors_dr1199_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) +{ + unsigned int accept = -1; + REST.get_header_accept(request, &accept); + if(accept == -1 || accept == REST.type.APPLICATION_JSON) { + content_len = 0; + CONTENT_PRINTF("{\"DR1199\":["); + CONTENT_PRINTF("{\"Switch\":\"0x%X\"},", button_sensor.value(0)); + CONTENT_PRINTF("{\"Pot\":\"%d\"}", pot_sensor.value(0)); + CONTENT_PRINTF("]}"); + REST.set_header_content_type(response, REST.type.APPLICATION_JSON); + REST.set_response_payload(response, (uint8_t *)content, content_len); + } +} +static void +event_sensors_dr1199_handler() +{ + /* Registered observers are notified and will trigger the GET handler to create the response. */ + REST.notify_subscribers(&resource_sensors_dr1199); +} +/***********************************************/ +/* Resource and handler to obtain switch value */ +/***********************************************/ +RESOURCE(resource_switch_sw1, + "title=\"SW1\"", + get_switch_sw1_handler, + NULL, + NULL, + NULL); +static void +get_switch_sw1_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) +{ + content_len = 0; + unsigned int accept = -1; + REST.get_header_accept(request, &accept); + if(accept == -1 || accept == REST.type.TEXT_PLAIN) { + PARSE_SWITCH(1) + REST.set_header_content_type(response, REST.type.TEXT_PLAIN); + REST.set_response_payload(response, (uint8_t *)content, content_len); + } +} +RESOURCE(resource_switch_sw2, + "title=\"SW2\"", + get_switch_sw2_handler, + NULL, + NULL, + NULL); +static void +get_switch_sw2_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) +{ + content_len = 0; + unsigned int accept = -1; + REST.get_header_accept(request, &accept); + if(accept == -1 || accept == REST.type.TEXT_PLAIN) { + PARSE_SWITCH(2) + REST.set_header_content_type(response, REST.type.TEXT_PLAIN); + REST.set_response_payload(response, (uint8_t *)content, content_len); + } +} +RESOURCE(resource_switch_sw3, + "title=\"SW3\"", + get_switch_sw3_handler, + NULL, + NULL, + NULL); +static void +get_switch_sw3_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) +{ + content_len = 0; + unsigned int accept = -1; + REST.get_header_accept(request, &accept); + if(accept == -1 || accept == REST.type.TEXT_PLAIN) { + PARSE_SWITCH(3) + REST.set_header_content_type(response, REST.type.TEXT_PLAIN); + REST.set_response_payload(response, (uint8_t *)content, content_len); + } +} +RESOURCE(resource_switch_sw4, + "title=\"SW4\"", + get_switch_sw4_handler, + NULL, + NULL, + NULL); +static void +get_switch_sw4_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) +{ + content_len = 0; + unsigned int accept = -1; + REST.get_header_accept(request, &accept); + if(accept == -1 || accept == REST.type.TEXT_PLAIN) { + PARSE_SWITCH(4) + REST.set_header_content_type(response, REST.type.TEXT_PLAIN); + REST.set_response_payload(response, (uint8_t *)content, content_len); + } +} +RESOURCE(resource_switch_dio8, + "title=\"DIO8\"", + get_switch_dio8_handler, + NULL, + NULL, + NULL); +static void +get_switch_dio8_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) +{ + content_len = 0; + unsigned int accept = -1; + REST.get_header_accept(request, &accept); + if(accept == -1 || accept == REST.type.TEXT_PLAIN) { + PARSE_SWITCH(0) + REST.set_header_content_type(response, REST.type.TEXT_PLAIN); + REST.set_response_payload(response, (uint8_t *)content, content_len); + } +} +/*******************************************************/ +/* Resource and handler to obtain potentiometer value */ +/*******************************************************/ +RESOURCE(resource_pot, + "title=\"Potentiometer\"", + get_pot_handler, + NULL, + NULL, + NULL); +static void +get_pot_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) +{ + content_len = 0; + unsigned int accept = -1; + REST.get_header_accept(request, &accept); + if(accept == -1 || accept == REST.type.TEXT_PLAIN) { + CONTENT_PRINTF("%d", pot_sensor.value(0)); + REST.set_header_content_type(response, REST.type.TEXT_PLAIN); + REST.set_response_payload(response, (uint8_t *)content, content_len); + } +} +/************************************/ +/* Resource and handler to set leds */ +/************************************/ +RESOURCE(resource_led_d1, + "title=\"LED D1 <[0,1]>\"", + NULL, + put_post_led_d1_handler, + put_post_led_d1_handler, + NULL); +static void +put_post_led_d1_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) +{ + const uint8_t *request_content; + int request_content_len; + unsigned int accept = -1; + REST.get_header_accept(request, &accept); + if(accept == -1 || accept == REST.type.TEXT_PLAIN) { + request_content_len = REST.get_request_payload(request, &request_content); + SET_LED(LEDS_GREEN) + } +} +RESOURCE(resource_led_d2, + "title=\"LED D2 <[0,1]>\"", + NULL, + put_post_led_d2_handler, + put_post_led_d2_handler, + NULL); +static void +put_post_led_d2_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) +{ + const uint8_t *request_content; + int request_content_len; + unsigned int accept = -1; + REST.get_header_accept(request, &accept); + if(accept == -1 || accept == REST.type.TEXT_PLAIN) { + request_content_len = REST.get_request_payload(request, &request_content); + SET_LED(LEDS_BLUE) + } +} +RESOURCE(resource_led_d3, + "title=\"LED D3 <[0,1]>\"", + NULL, + put_post_led_d3_handler, + put_post_led_d3_handler, + NULL); +static void +put_post_led_d3_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) +{ + const uint8_t *request_content; + int request_content_len; + unsigned int accept = -1; + REST.get_header_accept(request, &accept); + if(accept == -1 || accept == REST.type.TEXT_PLAIN) { + request_content_len = REST.get_request_payload(request, &request_content); + SET_LED(LEDS_RED) + } +} +RESOURCE(resource_led_d3_1174, + "title=\"LED D3 1174<[0,1]>\"", + NULL, + put_post_led_d3_1174_handler, + put_post_led_d3_1174_handler, + NULL); +static void +put_post_led_d3_1174_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) +{ + const uint8_t *request_content; + int request_content_len; + unsigned int accept = -1; + REST.get_header_accept(request, &accept); + if(accept == -1 || accept == REST.type.TEXT_PLAIN) { + request_content_len = REST.get_request_payload(request, &request_content); + SET_LED(LEDS_GP0); + } +} +RESOURCE(resource_led_d6_1174, + "title=\"LED D6 1174<[0,1]>\"", + NULL, + put_post_led_d6_1174_handler, + put_post_led_d6_1174_handler, + NULL); +static void +put_post_led_d6_1174_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) +{ + const uint8_t *request_content; + int request_content_len; + unsigned int accept = -1; + REST.get_header_accept(request, &accept); + if(accept == -1 || accept == REST.type.TEXT_PLAIN) { + request_content_len = REST.get_request_payload(request, &request_content); + SET_LED(LEDS_GP1); + } +} +RESOURCE(resource_led_all, + "title=\"LED All <[0,1]>\"", + NULL, + put_post_led_all_handler, + put_post_led_all_handler, + NULL); +static void +put_post_led_all_handler(void *request, void *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset) +{ + const uint8_t *request_content; + int request_content_len; + unsigned int accept = -1; + REST.get_header_accept(request, &accept); + if(accept == -1 || accept == REST.type.TEXT_PLAIN) { + request_content_len = REST.get_request_payload(request, &request_content); + if(atoi((const char *)request_content) != 0) { + leds_on(LEDS_ALL); + } else { + leds_off(LEDS_ALL); + } + } +} +/*---------------------------------------------------------------------------*/ +PROCESS_THREAD(start_app, ev, data) +{ + PROCESS_BEGIN(); + + static int is_coordinator = 0; + + /* is_coordinator = node_id == 1; */ + + /* Make sensor active for measuring */ + SENSORS_ACTIVATE(button_sensor); + SENSORS_ACTIVATE(pot_sensor); + + /* Start net stack */ + if(is_coordinator) { + uip_ipaddr_t prefix; + uip_ip6addr(&prefix, 0xaaaa, 0, 0, 0, 0, 0, 0, 0); + rpl_tools_init(&prefix); + } else { + rpl_tools_init(NULL); + } printf("Starting RPL node\n"); + + rest_init_engine(); + rest_activate_resource(&resource_switch_sw1, "DR1199/Switch/SW1"); + rest_activate_resource(&resource_switch_sw2, "DR1199/Switch/SW2"); + rest_activate_resource(&resource_switch_sw3, "DR1199/Switch/SW3"); + rest_activate_resource(&resource_switch_sw4, "DR1199/Switch/SW4"); + rest_activate_resource(&resource_switch_dio8, "DR1199/Switch/DIO8"); + rest_activate_resource(&resource_pot, "DR1199/Potentiometer"); + rest_activate_resource(&resource_led_d1, "DR1199/LED/D1"); + rest_activate_resource(&resource_led_d2, "DR1199/LED/D2"); + rest_activate_resource(&resource_led_d3, "DR1199/LED/D3"); + rest_activate_resource(&resource_led_d3_1174, "DR1199/LED/D3On1174"); + rest_activate_resource(&resource_led_d6_1174, "DR1199/LED/D6On1174"); + rest_activate_resource(&resource_led_all, "DR1199/LED/All"); + rest_activate_resource(&resource_sensors_dr1199, "DR1199/AllSensors"); + /* If sensor process generates an event, call event_handler of resource. + This will make this resource observable by the client */ + while(1) { + PROCESS_WAIT_EVENT_UNTIL((ev == sensors_event) && + ((data == &button_sensor) || (data == &pot_sensor))); + event_sensors_dr1199_handler(); + } + + PROCESS_END(); +} + diff --git a/examples/jn516x/rpl/coap-dr1199-node/project-conf.h b/examples/jn516x/rpl/coap-dr1199-node/project-conf.h new file mode 100644 index 000000000..4c2ecd648 --- /dev/null +++ b/examples/jn516x/rpl/coap-dr1199-node/project-conf.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2015, SICS Swedish ICT. + * 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 Institute 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 INSTITUTE 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 INSTITUTE 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. + * + */ +/** + * \author Simon Duquennoy + */ + +#ifndef __PROJECT_CONF_H__ +#define __PROJECT_CONF_H__ + +#include "../common-conf.h" + +#endif /* __PROJECT_CONF_H__ */ diff --git a/examples/jn516x/rpl/common-conf.h b/examples/jn516x/rpl/common-conf.h new file mode 100644 index 000000000..5c936ff7f --- /dev/null +++ b/examples/jn516x/rpl/common-conf.h @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2015, SICS Swedish ICT. + * 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 Institute 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 INSTITUTE 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 INSTITUTE 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. + * + */ +/** + * \author Simon Duquennoy + */ + +#ifndef __COMMON_CONF_H__ +#define __COMMON_CONF_H__ + +#define MAC_CONFIG_NULLRDC 0 +#define MAC_CONFIG_CONTIKIMAC 1 +/* Select a MAC configuration */ +#define MAC_CONFIG MAC_CONFIG_NULLRDC + +#undef NETSTACK_CONF_MAC +#undef NETSTACK_CONF_RDC +#undef NETSTACK_CONF_FRAMER + +#if MAC_CONFIG == MAC_CONFIG_NULLRDC + +#define NETSTACK_CONF_MAC csma_driver +#define NETSTACK_CONF_RDC nullrdc_driver +#define NETSTACK_CONF_FRAMER framer_802154 + +#elif MAC_CONFIG == MAC_CONFIG_CONTIKIMAC + +#define NETSTACK_CONF_MAC csma_driver +#define NETSTACK_CONF_RDC contikimac_driver +#define NETSTACK_CONF_FRAMER contikimac_framer +#undef MICROMAC_CONF_AUTOACK +#define MICROMAC_CONF_AUTOACK 1 + +#else + +#error Unsupported MAC configuration + +#endif /* MAC_CONFIG */ + +/* IEEE802.15.4 PANID and channel */ + +#undef IEEE802154_CONF_PANID +#define IEEE802154_CONF_PANID 0xabcd + +#undef RF_CHANNEL +#define RF_CHANNEL 26 + +/* UART Configuration */ + +#undef UART_HW_FLOW_CTRL +#define UART_HW_FLOW_CTRL 0 + +#undef UART_XONXOFF_FLOW_CTRL +#define UART_XONXOFF_FLOW_CTRL 1 + +#undef UART_BAUD_RATE +#define UART_BAUD_RATE UART_RATE_1000000 + +#endif /* __COMMON_CONF_H__ */ diff --git a/examples/jn516x/rpl/node/Makefile b/examples/jn516x/rpl/node/Makefile new file mode 100644 index 000000000..8096152ee --- /dev/null +++ b/examples/jn516x/rpl/node/Makefile @@ -0,0 +1,14 @@ +CONTIKI_PROJECT = node +all: $(CONTIKI_PROJECT) + +TARGET ?= jn516x + +CONTIKI=../../../.. + +CONTIKI_WITH_IPV6 = 1 + +PROJECTDIRS += .. ../tools +PROJECT_SOURCEFILES += rpl-tools.c +CFLAGS += -DPROJECT_CONF_H=\"project-conf.h\" + +include $(CONTIKI)/Makefile.include diff --git a/examples/jn516x/rpl/node/README.md b/examples/jn516x/rpl/node/README.md new file mode 100644 index 000000000..e9bded1d6 --- /dev/null +++ b/examples/jn516x/rpl/node/README.md @@ -0,0 +1,18 @@ +A RPL node. Will act as basic node by default, but can be configured at startup +using the user button and following instructions from the log output. Every press +of a button toggles the mode as 6ln and 6dr. After 10s with no button press, +the node starts in the last setting. The modes are: +* 6ln (default): 6lowpan node, will join a RPL network and act as router. +* 6dr: 6lowpan DAG Root, will start its own RPL network. Note this is not a +border router, i.e. it does not have a serial interface with connection to +the Internet. For a border router, see ../border-router. + +To indicate the hardware target for the node, add one of the following +options in the command line: +If rpl-border-router runs on dongle: +JN516x_WITH_DONGLE=1 +If rpl-border-router runs on DR1174: +JN516x_WITH_DR1174=1 +If building for a new platform, first execute : make clean + +For more information, see ../README.md. diff --git a/examples/jn516x/rpl/node/node.c b/examples/jn516x/rpl/node/node.c new file mode 100644 index 000000000..e4fccec7d --- /dev/null +++ b/examples/jn516x/rpl/node/node.c @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2015, SICS Swedish ICT. + * 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 Institute 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 INSTITUTE 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 INSTITUTE 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. + * + */ +/** + * \file + * A RPL node able to act as either DAG Root (6dr) or simple node (6ln). + * Press use button at startup to configure. + * + * \author Simon Duquennoy + */ + +#include "contiki.h" +#include "net/rpl/rpl.h" +#include "tools/rpl-tools.h" + +#define DEBUG DEBUG_PRINT +#include "net/ip/uip-debug.h" + +#define CONFIG_VIA_BUTTON PLATFORM_HAS_BUTTON +#if CONFIG_VIA_BUTTON +#include "button-sensor.h" +#endif /* CONFIG_VIA_BUTTON */ + +/*---------------------------------------------------------------------------*/ +PROCESS(node_process, "RPL Node"); +#if CONFIG_VIA_BUTTON +AUTOSTART_PROCESSES(&node_process, &sensors_process); +#else /* CONFIG_VIA_BUTTON */ +AUTOSTART_PROCESSES(&node_process); +#endif /* CONFIG_VIA_BUTTON */ + +/*---------------------------------------------------------------------------*/ +PROCESS_THREAD(node_process, ev, data) +{ + PROCESS_BEGIN(); + + /* 3 possible roles: + * - role_6ln: simple node, will join any network, secured or not + * - role_6dg: DAG root, will advertise (unsecured) beacons + * */ + static int is_coordinator = 0; + static enum { role_6ln, role_6dr } node_role; + node_role = role_6ln; + +#if CONFIG_VIA_BUTTON + { +#define CONFIG_WAIT_TIME 10 + static struct etimer et; + + SENSORS_ACTIVATE(button_sensor); + etimer_set(&et, CLOCK_SECOND * CONFIG_WAIT_TIME); + + while(!etimer_expired(&et)) { + printf("Init: current role: %s. Will start in %u seconds.\n", + node_role == role_6ln ? "6ln" : "6dr", + CONFIG_WAIT_TIME); + PROCESS_WAIT_EVENT_UNTIL(((ev == sensors_event) && + (data == &button_sensor) && button_sensor.value(0) > 0) + || etimer_expired(&et)); + if(ev == sensors_event && data == &button_sensor && button_sensor.value(0) > 0) { + node_role = (node_role + 1) % 2; + etimer_restart(&et); + } + } + } + +#endif /* CONFIG_VIA_BUTTON */ + + printf("Init: node starting with role %s\n", + node_role == role_6ln ? "6ln" : "6dr"); + + is_coordinator = node_role > role_6ln; + + if(is_coordinator) { + uip_ipaddr_t prefix; + uip_ip6addr(&prefix, 0xaaaa, 0, 0, 0, 0, 0, 0, 0); + rpl_tools_init(&prefix); + } else { + rpl_tools_init(NULL); + } PROCESS_END(); +} +/*---------------------------------------------------------------------------*/ diff --git a/examples/jn516x/rpl/node/project-conf.h b/examples/jn516x/rpl/node/project-conf.h new file mode 100644 index 000000000..9db6f0229 --- /dev/null +++ b/examples/jn516x/rpl/node/project-conf.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2015, SICS Swedish ICT. + * 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 Institute 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 INSTITUTE 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 INSTITUTE 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. + * + */ + +/** + * \author Simon Duquennoy + */ + +#ifndef __PROJECT_CONF_H__ +#define __PROJECT_CONF_H__ + +#include "../common-conf.h" + +#endif /* __PROJECT_CONF_H__ */ diff --git a/examples/jn516x/rpl/tools/rpl-tools.c b/examples/jn516x/rpl/tools/rpl-tools.c new file mode 100644 index 000000000..23a041306 --- /dev/null +++ b/examples/jn516x/rpl/tools/rpl-tools.c @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2015, SICS Swedish ICT. + * 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 Institute 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 INSTITUTE 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 INSTITUTE 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. + * + */ +/** + * \file + * + * \author Simon Duquennoy + */ + +#include "contiki-conf.h" +#include "contiki-net.h" +#include "net/ip/uip.h" +#include "net/rpl/rpl.h" +#include +#include + +#define DEBUG DEBUG_PRINT +#include "net/ip/uip-debug.h" + +/*---------------------------------------------------------------------------*/ +static void +print_local_addresses(void) +{ + int i; + uint8_t state; + + PRINTA("Server IPv6 addresses:\n"); + for(i = 0; i < UIP_DS6_ADDR_NB; i++) { + state = uip_ds6_if.addr_list[i].state; + if(uip_ds6_if.addr_list[i].isused && + (state == ADDR_TENTATIVE || state == ADDR_PREFERRED)) { + PRINTA(" "); + uip_debug_ipaddr_print(&uip_ds6_if.addr_list[i].ipaddr); + PRINTA("\n"); + } + } +} +/*---------------------------------------------------------------------------*/ +void +rpl_tools_init(uip_ipaddr_t *br_prefix) +{ + uip_ipaddr_t global_ipaddr; + + if(br_prefix) { /* We are root */ + NETSTACK_RDC.off(1); + memcpy(&global_ipaddr, br_prefix, 16); + uip_ds6_set_addr_iid(&global_ipaddr, &uip_lladdr); + uip_ds6_addr_add(&global_ipaddr, 0, ADDR_AUTOCONF); + rpl_set_root(RPL_DEFAULT_INSTANCE, &global_ipaddr); + rpl_set_prefix(rpl_get_any_dag(), br_prefix, 64); + rpl_repair_root(RPL_DEFAULT_INSTANCE); + } + + NETSTACK_MAC.on(); + + print_local_addresses(); +} diff --git a/examples/jn516x/rpl/tools/rpl-tools.h b/examples/jn516x/rpl/tools/rpl-tools.h new file mode 100644 index 000000000..e91bc81c5 --- /dev/null +++ b/examples/jn516x/rpl/tools/rpl-tools.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2015, SICS Swedish ICT. + * 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 Institute 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 INSTITUTE 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 INSTITUTE 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. + * + */ +/** + + * \author Simon Duquennoy + */ + +void rpl_tools_init(uip_ipaddr_t *br_prefix); diff --git a/platform/jn516x/App_Stack_Size.ld b/platform/jn516x/App_Stack_Size.ld new file mode 100644 index 000000000..3eaaf34c0 --- /dev/null +++ b/platform/jn516x/App_Stack_Size.ld @@ -0,0 +1,46 @@ +/***************************************************************************** + * + * MODULE: App_Stack_Size.ld + * + * DESCRIPTION: Linker command file defining the default app stack size + * + **************************************************************************** + /* +* Copyright (c) 2015 NXP B.V. +* 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 NXP B.V. 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 NXP B.V. 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 NXP B.V. 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. +* +* This file is part of the Contiki operating system. +* +* +*/ + +/* Default stack size for MAC applications. + * To override the default setting, copy this + * file to your apoplication build folder and + * alter the stack size as required. */ + +_stack_size = 2048; diff --git a/platform/jn516x/Makefile.jn516x b/platform/jn516x/Makefile.jn516x new file mode 100644 index 000000000..bce6adbd5 --- /dev/null +++ b/platform/jn516x/Makefile.jn516x @@ -0,0 +1,300 @@ +ifndef CONTIKI + $(error CONTIKI not defined! You must specify where CONTIKI resides!) +endif + +############################################################################## +# User definable make parameters that may be overwritten from the command line +ifdef CHIP + JENNIC_CHIP = $(CHIP) +else +JENNIC_CHIP ?= JN5168 +endif +JENNIC_PCB ?= DEVKIT4 +JENNIC_STACK ?= MAC +JENNIC_MAC ?= MiniMac +DISABLE_LTO ?= 1 +# can be set to SW or HW +DEBUG ?= None + +ifeq ($(HOST_OS),Windows) + SDK_BASE_DIR ?= C:/NXP/bstudio_nxp/sdk/JN-SW-4163 + FLASH_PROGRAMMER ?= ${SDK_BASE_DIR}/Tools/flashprogrammer/FlashCLI.exe +else + # Assume Linux + SDK_BASE_DIR ?= /usr/jn516x-sdk/JN-SW-4163 + FLASH_PROGRAMMER ?= $(CONTIKI)/tools/jn516x/JennicModuleProgrammer +endif + +############################################################################### +# Include NXP makefiles +include $(SDK_BASE_DIR)/Chip/Common/Build/config.mk +include $(SDK_BASE_DIR)/Platform/Common/Build/config.mk +include $(SDK_BASE_DIR)/Stack/Common/Build/config.mk + +# Add missing includes +INCFLAGS += -I$(COMPONENTS_BASE_DIR)/MicroSpecific/Include +INCFLAGS += -I$(COMPONENTS_BASE_DIR)/Recal/Include +INCFLAGS += -I$(COMPONENTS_BASE_DIR)/ProductionTestApi/Include +INCFLAGS += -I$(COMPONENTS_BASE_DIR)/Xcv/Include + +# Add missing libs and +# do not link with MiniMac nor MiniMacShim (we use MMAC) +LDLIBS += Recal_$(JENNIC_CHIP_FAMILY) +LDLIBS := $(subst MiniMacShim_JN516x, ,$(LDLIBS)) +ifeq ($(JENNIC_CHIP),JN5169) + LDLIBS := $(subst MiniMac_JN5169, ,$(LDLIBS)) +else +LDLIBS := $(subst MiniMac_JN516x, ,$(LDLIBS)) + LDLIBS += JPT_$(JENNIC_CHIP) +endif + +# Pass DEBUG as CFLAG +ifeq ($(DEBUG),SW) +CFLAGS += -DDEBUG=1 +endif + +# Path-independent cross-compiler +CC:=$(CROSS_COMPILE)-gcc +AS:=$(CROSS_COMPILE)-as +LD:=$(CROSS_COMPILE)-ls +AR:=$(CROSS_COMPILE)-ar +NM:=$(CROSS_COMPILE)-nm +STRIP:=$(CROSS_COMPILE)-strip +SIZE:=$(CROSS_COMPILE)-size +OBJCOPY:=$(CROSS_COMPILE)-objcopy +OBJDUMP:=$(CROSS_COMPILE)-objdump + +CFLAGS := $(subst -Wcast-align,,$(CFLAGS)) +CFLAGS := $(subst -Wall,,$(CFLAGS)) + +ARCH = ccm-star.c exceptions.c rtimer-arch.c slip_uart0.c clock.c micromac-radio.c \ + mtarch.c node-id.c watchdog.c log.c ringbufindex.c slip.c sprintf.c +# Default uart0 for printf and slip +TARGET_WITH_UART0 ?= 1 +TARGET_WITH_UART1 ?= 0 + +# Get required uart files +ifeq ($(TARGET_WITH_UART0),1) +WITH_UART = 1 +ARCH += uart0.c +endif +ifeq ($(TARGET_WITH_UART1),1) +WITH_UART = 1 +ARCH += uart1.c +endif +ifeq ($(WITH_UART),1) +ARCH += uart-driver.c +endif + +CONTIKI_TARGET_DIRS = . dev lib +CONTIKI_TARGET_MAIN = contiki-jn516x-main.c + +ifeq ($(JN516x_WITH_DR1175),1) +JN516x_WITH_DR1174 = 1 +CFLAGS += -DSENSOR_BOARD_DR1175 +CONTIKI_TARGET_DIRS += dev/dr1175 +ARCH += ht-sensor.c light-sensor.c leds-extension.c leds-arch-1175.c +endif + +ifeq ($(JN516x_WITH_DR1199),1) +JN516x_WITH_DR1174 = 1 +CFLAGS += -DSENSOR_BOARD_DR1199 +CONTIKI_TARGET_DIRS += dev/dr1199 +ARCH += pot-sensor.c leds-arch-1199.c +endif + +ifeq ($(JN516x_WITH_DR1174),1) +CFLAGS += -DSENSOR_BOARD_DR1174 +CONTIKI_TARGET_DIRS += dev/dr1174 +ARCH += button-sensor.c leds-arch.c +else +# Dongle is the default platform +JN516x_WITH_DONGLE = 1 +endif + +ifeq ($(JN516x_WITH_DONGLE),1) +CFLAGS += -DDONGLE_NODE +CONTIKI_TARGET_DIRS += dev/dongle +ARCH += leds-arch.c +endif + +ifdef nodemac +CFLAGS += -DMACID=$(nodemac) +endif + +CLEAN += *.jn516x +CLEAN += *.jn516x.bin + +MODULES += core/net \ + core/net/mac \ + core/net/mac/contikimac \ + core/net/llsec core/net/llsec/noncoresec + +CONTIKI_TARGET_SOURCEFILES += $(ARCH) +CONTIKI_SOURCEFILES += $(CONTIKI_TARGET_SOURCEFILES) + +PROJECT_OBJECTFILES += ${addprefix $(OBJECTDIR)/,$(CONTIKI_TARGET_MAIN:.c=.o)} + +CFLAGS += $(INCFLAGS) + +# Library search paths +LDFLAGS += -L$(CHIP_BASE_DIR)/Build +LDFLAGS += -L$(CHIP_BASE_DIR)/Library + +LDLIBS := $(addsuffix _$(JENNIC_CHIP_FAMILY),$(APPLIBS)) $(LDLIBS) + +ifeq ($(HOST_OS),Windows) +# Windows assumes Cygwin. Substitute all paths in CFLAGS and LDFLAGS with Windows paths. +CFLAGS := $(patsubst -I/cygdrive/c/%,-Ic:/%,$(CFLAGS)) +LDFLAGS := $(patsubst -L/cygdrive/c/%,-Lc:/%,$(LDFLAGS)) +endif + +######################################################################## + +MOTELIST = python $(CONTIKI)/tools/jn516x/mote-list.py + +# Check if we are running under Windows +ifeq ($(HOST_OS),Windows) + USBDEVPREFIX=/dev/com + USBDEVBASENAME=COM + SERIALDUMP ?= $(CONTIKI)/tools/jn516x/serialdump-windows +else +ifeq ($(HOST_OS),Darwin) + USBDEVPREFIX= + USBDEVBASENAME=/dev/tty.usbserial- + SERIALDUMP ?= $(CONTIKI)/tools/jn516x/serialdump-macos +else + # Else we assume Linux + USBDEVPREFIX= + USBDEVBASENAME=/dev/ttyUSB + SERIALDUMP ?= $(CONTIKI)/tools/jn516x/serialdump-linux +endif +endif + +# Note: this logic is different from Sky +ifneq ("", "$(filter-out %all,$(filter %.upload serial% login, $(MAKECMDGOALS)))") +ifndef MOTE + $(error MOTE not defined! You must specify which MOTE (serial port) to use) +endif +endif +PORT = $(USBDEVBASENAME)$(MOTE) + +#### make targets + +######################################################################## +# Dependency, compilation and flash-programming rules + +.PHONY: all clean + +.PRECIOUS: %.elf + +%.d: clean + +%.nm: %.$(TARGET) + $(Q)$(NM) -nS $< > $@ + +%.dmp: %.$(TARGET) + $(Q)$(OBJDUMP) -d $< > $@ + +define FINALIZE_DEPENDENCY_ +# hack: subsitute windows path back to cygwin path +sed -e 's/c:\//\/cygdrive\/c\//' $(@:.o=.d) > $(@:.o=.$$$$); \ +cp $(@:.o=.$$$$) $(@:.o=.d); \ +sed -e 's/#.*//' -e 's/^[^:]*: *//' -e 's/ *\\$$//' \ + -e '/^$$/ d' -e 's/$$/ :/' < $(@:.o=.$$$$) >> $(@:.o=.d); \ +rm -f $(@:.o=.$$$$) +endef + +CUSTOM_RULE_C_TO_OBJECTDIR_O = 1 +$(OBJECTDIR)/%.o: %.c | $(OBJECTDIR) + $(TRACE_CC) + $(Q)$(CC) $(CFLAGS) -MMD -c $< -o $@ + @$(FINALIZE_DEPENDENCY_) + +CUSTOM_RULE_LINK = 1 +ALLLIBS = $(addprefix -l,$(LDLIBS)) $(addprefix -l,$(LDSTACKLIBS)) $(addprefix -l,$(LDMYLIBS)) +ABS_APPLIBS = $(addsuffix _$(JENNIC_CHIP_FAMILY).a,$(addprefix $(COMPONENTS_BASE_DIR)/Library/lib,$(APPLIBS))) + +ifneq ($(wildcard $(SDK_BASE_DIR)/Components/Library/*),) +# The SDK is fully installed, proceed to linking and objcopy to ready-to-upload .jn516x.bin file +%.$(TARGET): %.co $(PROJECT_OBJECTFILES) $(PROJECT_LIBRARIES) contiki-$(TARGET).a $(ABS_APPLIBS) + echo ${filter %.a,$^} + $(Q)$(CC) -Wl,--gc-sections $(LDFLAGS) -T$(LINKCMD) -o $@ -Wl,--start-group \ + $(patsubst /cygdrive/c/%,c:/%,${filter-out %.a,$^}) \ + $(patsubst /cygdrive/c/%,c:/%,${filter %.a,$^}) \ + $(ALLLIBS) -Wl,--end-group -Wl,-Map,contiki-$(TARGET).map + $(OBJCOPY) -S -O binary $@ $@.bin +else +# The SDK does not include libraries, only build objects and libraries, skip linking +%.$(TARGET): %.co $(PROJECT_OBJECTFILES) $(PROJECT_LIBRARIES) contiki-$(TARGET).a + echo Creating empty $@ + touch $@ +endif + +%.$(TARGET).bin: %.$(TARGET) + $(Q)$(OBJCOPY) -S -O binary $< $@ + +symbols.c symbols.h: + @${CONTIKI}/tools/make-empty-symbols + +### Upload target to one jn516x mote specified by MOTE=portNumber +ifeq ($(HOST_OS),Windows) +%.upload: %.$(TARGET).bin + ${FLASH_PROGRAMMER} -a -c $(PORT) -B 1000000 -s -w -f $< +else +%.upload: %.$(TARGET).bin + ${FLASH_PROGRAMMER} -V 10 -v -s $(PORT) -I 38400 -P 1000000 -f $< +endif + +### Flash the given file +ifeq ($(HOST_OS),Windows) +%.flash: ${FLASH_PROGRAMMER} + ${FLASH_PROGRAMMER} -a -c $(PORT) -B 1000000 -s -w -f $*.$(TARGET).bin +else +%.flash: ${FLASH_PROGRAMMER} + ${FLASH_PROGRAMMER} -V 10 -v -s $(PORT) -I 38400 -P 1000000 -s -f $*.$(TARGET).bin +endif + +### List the ports with connected jn516x motes +motelist: + $(Q)$(MOTELIST) ${FLASH_PROGRAMMER} \# + +motelistmac: + $(Q)$(MOTELIST) ${FLASH_PROGRAMMER} \! + +motelistinfo: + $(Q)$(MOTELIST) ${FLASH_PROGRAMMER} \? + +### Upload target to all connected jn516x motes +%.uploadall: %.$(TARGET).bin + $(Q)$(MOTELIST) ${FLASH_PROGRAMMER} $< + +### Flash the given file to all connected jn516x motes +%.flashall: + $(Q)$(MOTELIST) ${FLASH_PROGRAMMER} $* + +### Dump output from all connected jn516x motes +serialdumpall: + $(Q)$(MOTELIST) ${FLASH_PROGRAMMER} \% $(SERIALDUMP) + +########### login: read serial line ############## +### USAGE: make TARGET=jn516x login UART_BAUDRATE={baudrate} {serial device} +### UART_BAUDRATE: i.e., 115200. default is 1000000 +### example: make TARGET=jn516x UART_BAUDRATE=115200 login MOTE=1 + +UART_BAUDRATE ?= 1000000 + +$(CONTIKI)/tools/tunslip6: $(CONTIKI)/tools/tunslip6.c + ($(MAKE) -C $(CONTIKI)/tools tunslip6 CFLAGS= LDFLAGS= LDLIBS= INCFLAGS=) + +$(SERIALDUMP): $(CONTIKI)/tools/jn516x/serialdump.c + (cd $(CONTIKI)/tools/jn516x; ${MAKE} $(notdir $(SERIALDUMP))) + +login: $(SERIALDUMP) + $(SERIALDUMP) -b${UART_BAUDRATE} $(USBDEVPREFIX)$(PORT) + +serialview: $(SERIALDUMP) + $(SERIALDUMP) -b${UART_BAUDRATE} $(USBDEVPREFIX)$(PORT) | $(CONTIKI)/tools/timestamp + +serialdump: $(SERIALDUMP) + $(SERIALDUMP) -b${UART_BAUDRATE} $(USBDEVPREFIX)$(PORT) | $(CONTIKI)/tools/timestamp | tee serialdump-$(notdir $(PORT))-`date +%Y%m%d-%H%M` diff --git a/platform/jn516x/README.md b/platform/jn516x/README.md new file mode 100644 index 000000000..d67bfd029 --- /dev/null +++ b/platform/jn516x/README.md @@ -0,0 +1,183 @@ +# NXP JN516x platform + +## Overview + +The JN516x series is a range of ultra low power, high performance wireless microcontrollers from NXP. They feature an enhanced 32-bit RISC processor (256kB/32kB/4kB Flash/RAM/EEPROM for JN5168), and also include a 2.4GHz IEEE802.15.4-compliant transceiver. +These system on chip (SoC) devices have the following main [features][jn516x-datasheet]: +* 32-bit RISC CPU (Beyond Architecture -- BA), 1 to 32MHz clock speed +* 2.4GHz IEEE802.15.4-compliant transceiver +* 128-bit AES security processor +* MAC accelerator with packet formatting, CRCs, address check, auto-acks, timers +* Transmit power 2.5dBm +* Receiver sensitivity -95dBm +* RX current 17mA, TX 15mA +* Integrated ultra low power sleep oscillator – 0.6μA +* Deep sleep current 0.12μA (Wake-up from IO) +* Time of Flight engine for ranging +* Antenna Diversity (Auto RX) +* 2.0V to 3.6V battery operation +* Supply voltage monitor with 8 programmable thresholds +* Built-in battery and temperature sensors +* Infra-red remote control transmitter +* Peripherals: I2C, SPI, 2x UART, 4-input 10-bit ADC, comparator, 5x PWM + +## Maintainers and Contact + +Long-term maintainers: +* Theo Van Daele, NXP, theo.van.daele@nxp.com, github user: [TeVeDe](https://github.com/TeVeDe) +* Simon Duquennoy, SICS, simonduq@sics.se, github user: [simonduq](https://github.com/simonduq) + +Other contributors: +* Beshr Al Nahas, SICS (now Chalmers University), beshr@chalmers.se, github user: [beshrns](https://github.com/beshrns) +* Atis Elsts, SICS, atis.elsts@sics.se, github user: [atiselsts](https://github.com/atiselsts) + +Additional long-term contact: +* Hugh Maaskant, NXP, hugh.maaskant@nxp.com, github user: [hugh-maaskant](https://github.com/hugh-maaskant) + +## License + +All files are under BSD license, as described by the copyright statement in every source file. + +## Port Features + +The following features have been implemented: + * A radio driver with two modes (polling and interrupt based) + * CCM* driver with HW accelerated AES + * UART driver (with HW and SW flow control, 1'000'000 baudrate by default) + * Contiki system clock and rtimers (16MHz tick frequency based on 32 MHz crystal) + * 32.768kHz external oscillator + * Periodic DCO recalibration + * CPU "doze" mode + * HW random number generator used as a random seed for pseudo-random generator + * Watchdog, JN516x HW exception handlers + +The following hardware platforms have been tested: + * DR1174 evaluation board (with a button sensor) + * DR1175 sensor board (with humidity/temperature and light sensors) + * DR1199 sensor board (with potentiometer and button sensors) + * USB dongle + +## TODO list + +The following features are planned: + * CPU deeper sleep mode support (where the 32 MHz crystal is turned off) + * Time-accurate radio primitives ("send at", "listen until") + * External storage + +## Requirements + +To start using JN516x with Contiki, the following are required: + * The toolchain and Software Development Kit to compile Contiki for JN516x + * Drivers so that your OS can communicate with your hardware + * Software to upload images to the JN516x + +### Install a Toolchain + +The toolchain used to build Contiki for JN516x is `ba-elf-gcc`. +The compiler as well as the binary libraries required to link the executables can be downloaded from NXP. To express your interest in obtaining them, go to [NXP 802.15.4 software page][NXP-802.15.4-software], select "JN-SW-4163", and contact the NXP support through the web form. The download link is then obtained via e-mail (allow 1+ working day for a reply). +The example applications in this port have been tested with compiler version `gcc-4.7.4-ba-r36379`. + +Linux and Windows instructions: +* On Linux: A compiled version for linux 64-bit is available: download [this](http://simonduq.github.io/resources/ba-elf-gcc-4.7.4-part1.tar.bz2) and [this](http://simonduq.github.io/resources/ba-elf-gcc-4.7.4-part2.tar.bz2) file, extract both in `/usr/ba-elf-gcc` such and add `/usr/ba-elf-gcc/bin` to your `$PATH` environment variable. Place the JN516x SDK under `/usr/jn516x-sdk`. +* On Windows: Run the setup program and select `C:/NXP/bstudio_nxp/` as install directory. Also make sure your PATH environment variable points to the compiler binaries (by default in `C:/NXP/bstudio_nxp/sdk/Tools/ba-elf-ba2-r36379/bin`). + +### Drivers + +The JN516x platforms feature FTDI serial-to-USB modules. The driver is commonly found in most OS, but if required it can be downloaded from + +### Device Enumerations +For the UART, serial line settings are 1000000 8N1, no flow control. + +Once all drivers have been installed correctly: +* On Windows, devices will appear as a virtual COM port. +* On Linux and OS X, devices will appear as `/dev/tty*`. + +### Software to Program the Nodes + +The JN516x can be programmed via the serial boot loader on the chip. +* On Linux, nodes can be programmed via the serial boot loader using the [JennicModuleProgrammer] tool. It is pre-installed under `tools/jn516x/JennicModuleProgrammer`. +* On Windows, nodes are programmed using NXP's Flash Programmer. There are two versions of it: GUI and command line. The Contiki make system is configured to use the command line version. By default it looks for the programmer in the SDK base directory under `Tools/flashprogrammer/FlashCLI.exe`. With the default SDK installation path the file should be located under `C:/NXP/bstudio_nxp/sdk/JN-SW-4163/Tools/flashprogrammer/FlashCLI.exe`. Modify `platforms/jn516x/Makefile.common` to change this default location. + +## Using the Port + +The following examples are intended to work off-the-shelf: +* Platform-specific examples under `examples/jn516x` +* All platform-independent Contiki application examples + +### Building an example + +To build the classic "hello world" example, navigate to `examples/hello-world`. It is recommended to either set the `TARGET` environmental variable or to save the `jn516x` platform as the default make target. To do that, run: + +`make TARGET=jn516x savetarget` + +Then run `make hello-world` to compile the application for JN516x platform. + +### Uploading an example + +Run the `upload` command to program the binary image on it: +`make hello-world.upload MOTE=0` + +The `MOTE` argument is used to specify to which of the ports the device is connected. For example, if there is a single mote connected to `/dev/ttyUSB3` in Linux (or, alternatively, `COM3` in Windows), the right command would be: +`make hello-world.upload MOTE=3` + +Note that on Windows, the FTDI drivers are able to switch the board to programming mode before uploading the image. + +On Linux, the drivers are not able to do so yet. We use a modified bootloader for JN516x, where nodes wait 5s in programming mode after a reset. You simply need to reset them before using `make upload`. The modified bootloader can be downloaded [here](http://simonduq.github.io/resources/BootLoader_JN5168.ba2.bin) and installed using a JTAG programmer, or alternatively, [this image](http://simonduq.github.io/resources/BootLoaderUpdater_JN5168.bin) can be installed as a normal application using the normal Windows tools. Once the device resets, this application will run and will then install the new boot loader. It generates some status output over UART0 at 115200 baud during this process. **Warning**: use the images above at your risk; NXP does not accept responsibility for any devices that are rendered unusable as a result of using it. + +### Listening to output + +Run the `login` command to start the `serialdump` application. +`make login MOTE=3` + +On Linux: after the application has started, press the reset button on the node. + +### Platform-specific make targets + +* `.flash` - flash the (pre-compiled) application to a JN516x mote (specified via the `MOTE` variable) +* `.flashall` - flash the (pre-compiled) application to all all connected JN516x motes +* `.upload` - compile and flash the application to a JN516x mote (specified via the `MOTE` variable) +* `.uploadall` - compile and flash the application to all all connected JN516x motes +* `login`, `serialview`, `serialdump` - dump serial port output from a JN516x mote (specified via the `MOTE` variable) +* `serialdumpall` - dump serial port output from all connected JN516x motes +* `motelist` - list all connected JN516x motes. +* `motelistmac` - list MAC addresses of all connected JN516x motes (Note: not implemented on Linux!) +* `motelistinfo` - list info about all connected JN516x motes (Note: very limited functionality on Linux!) + +*Troubleshooting:* you need a working Python installation for these commands to work. On Windows, make sure Python executable is in your `PATH`. + +### Compiling for different MCUs and boards + +The platforms can selected by using `Makefile` variables. + +The following MCU models are supported: +* `JN5164` - 160kB/32kB/4kB Flash/RAM/EEPROM +* `JN5168` - 256kB/32kB/4kB Flash/RAM/EEPROM (default MCU) +* `JN5169` - 512kB/32kB/4kB Flash/RAM/EEPROM + +Set `CHIP` variable to change this; for example, to select JN5164 use: +`make CHIP=JN5164` + +The following platform-specific configurations are supported: +* DR1174 evaluation kit; enable this with `JN516x_WITH_DR1174 = 1` in your makefile +* DR1174 with DR1175 sensor board; enable this with `JN516x_WITH_DR1175 = 1` (will set `JN516x_WITH_DR1174` automatically) +* DR1174 with DR1199 sensor board; enable this with `JN516x_WITH_DR1199 = 1` (will set `JN516x_WITH_DR1174` automatically) +* USB dongle; enable this with `JN516x_WITH_DONGLE = 1` + +### Node IEEE/RIME/IPv6 Addresses + +Nodes will autoconfigure their IPv6 address based on their 64-bit IEEE/MAC address. The 64-bit MAC address is read directly from JN516x System on Chip. +The 16-bit RIME address and the Node ID are set from the last 16-bits of the 64-bit MAC address. + +## Additional documentation + +1. [Data Sheet: JN516x IEEE802.15.4 Wireless Microcontroller][jn516x-datasheet] +2. [JN516x web page][jn516x-web] +3. [JN5168 web page][jn5168-web] +4. [JN516x user manuals][user-manuals] + +[jn516x-datasheet]: http://www.nxp.com/documents/data_sheet/JN516X.pdf +[jn516x-web]: http://www.nxp.com/products/microcontrollers/product_series/jn516x +[jn5168-web]: http://www.nxp.com/products/microcontrollers/product_series/jn516x/JN5168.html +[user-manuals]: http://www.nxp.com/technical-support-portal/#/tid=1,sid=,bt=,tab=usermanuals,p=1,rpp=,sc=,so=,jump= +[NXP-802.15.4-software]: http://www.nxp.com/techzones/wireless-connectivity/ieee802-15-4.html +[JennicModuleProgrammer]: https://github.com/WRTIOT/JennicModuleProgrammer diff --git a/platform/jn516x/contiki-conf.h b/platform/jn516x/contiki-conf.h new file mode 100644 index 000000000..41135c187 --- /dev/null +++ b/platform/jn516x/contiki-conf.h @@ -0,0 +1,195 @@ +/* + * Copyright (c) 2015, SICS Swedish ICT. + * 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 Institute 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 INSTITUTE 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 INSTITUTE 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. + * + * This file is part of the Contiki operating system. + * + */ + +#ifndef CONTIKI_CONF_H_ +#define CONTIKI_CONF_H_ + +#ifdef PLATFORM_CONF_H +#include PLATFORM_CONF_H +#else +#include "platform-conf.h" +#endif /* PLATFORM_CONF_H */ + +#ifndef CCM_STAR_CONF +#define CCM_STAR_CONF ccm_star_driver_jn516x +#endif /* CCM_STAR_CONF */ + +#ifndef NETSTACK_CONF_MAC +#define NETSTACK_CONF_MAC tschmac_driver +#endif /* NETSTACK_CONF_MAC */ + +#ifndef NETSTACK_CONF_RDC +#define NETSTACK_CONF_RDC nordc_driver +#endif /* NETSTACK_CONF_RDC */ + +#ifndef NETSTACK_CONF_RADIO +#define NETSTACK_CONF_RADIO micromac_radio_driver +#endif /* NETSTACK_CONF_RADIO */ + +#ifndef NETSTACK_CONF_FRAMER +#define NETSTACK_CONF_FRAMER framer_802154 +#endif /* NETSTACK_CONF_FRAMER */ + +#define PACKETBUF_CONF_ATTRS_INLINE 1 + +#ifndef IEEE802154_CONF_PANID +#define IEEE802154_CONF_PANID 0xABCD +#endif /* IEEE802154_CONF_PANID */ + +#ifndef ENERGEST_CONF_ON +#define ENERGEST_CONF_ON 1 +#endif /* ENERGEST_CONF_ON */ + +#define WITH_ASCII 1 + +#define PROCESS_CONF_NUMEVENTS 8 +#define PROCESS_CONF_STATS 1 + +#if !defined NETSTACK_CONF_WITH_IPV6 && !defined NETSTACK_CONF_WITH_IPV4 && !defined NETSTACK_CONF_WITH_RIME +#define NETSTACK_CONF_WITH_IPV6 1 +#endif /* NETSTACK_CONF_ not defined */ + +/* Network setup for IP */ +#if NETSTACK_CONF_WITH_IPV4 || NETSTACK_CONF_WITH_IPV6 + +#define LINKADDR_CONF_SIZE 8 + +#ifndef QUEUEBUF_CONF_NUM +#define QUEUEBUF_CONF_NUM 16 +#endif + +/* Network setup for non-IP (rime). */ +#else + +#define LINKADDR_CONF_SIZE 2 + +#ifndef COLLECT_NEIGHBOR_CONF_MAX_COLLECT_NEIGHBORS +#define COLLECT_NEIGHBOR_CONF_MAX_COLLECT_NEIGHBORS 32 +#endif /* COLLECT_NEIGHBOR_CONF_MAX_COLLECT_NEIGHBORS */ + +#ifndef QUEUEBUF_CONF_NUM +#define QUEUEBUF_CONF_NUM 16 +#endif /* QUEUEBUF_CONF_NUM */ + +#endif /* NETSTACK_CONF_WITH_IPV4 || NETSTACK_CONF_WITH_IPV6 */ + +/* Network setup for IPv6 */ +#if NETSTACK_CONF_WITH_IPV6 + +/* Network setup for IPv6 */ +#define NETSTACK_CONF_NETWORK sicslowpan_driver +#define UIP_CONF_BROADCAST 1 + +/* Configure NullRDC for when it is selected */ +#define NULLRDC_CONF_802154_AUTOACK_HW 1 + +#define UIP_CONF_LL_802154 1 +#define UIP_CONF_LLH_LEN 0 + +#define UIP_CONF_ROUTER 1 +#ifndef UIP_CONF_IPV6_RPL +#define UIP_CONF_IPV6_RPL 1 +#endif /* UIP_CONF_IPV6_RPL */ + +/* configure number of neighbors and routes */ +#ifndef NBR_TABLE_CONF_MAX_NEIGHBORS +#define NBR_TABLE_CONF_MAX_NEIGHBORS 20 +#endif /* NBR_TABLE_CONF_MAX_NEIGHBORS */ +#ifndef UIP_CONF_MAX_ROUTES +#define UIP_CONF_MAX_ROUTES 20 +#endif /* UIP_CONF_MAX_ROUTES */ + +#define UIP_CONF_ND6_SEND_RA 0 +#define UIP_CONF_ND6_REACHABLE_TIME 600000 +#define UIP_CONF_ND6_RETRANS_TIMER 10000 + +#ifndef UIP_CONF_IPV6_QUEUE_PKT +#define UIP_CONF_IPV6_QUEUE_PKT 0 +#endif /* UIP_CONF_IPV6_QUEUE_PKT */ +#define UIP_CONF_IPV6_CHECKS 1 +#define UIP_CONF_IPV6_REASSEMBLY 0 +#define UIP_CONF_NETIF_MAX_ADDRESSES 3 +#define UIP_CONF_ND6_MAX_PREFIXES 3 +#define UIP_CONF_ND6_MAX_DEFROUTERS 2 +#define UIP_CONF_IP_FORWARD 0 +#ifndef UIP_CONF_BUFFER_SIZE +#define UIP_CONF_BUFFER_SIZE 1280 +#endif + +#define SICSLOWPAN_CONF_COMPRESSION_IPV6 0 +#define SICSLOWPAN_CONF_COMPRESSION_HC1 1 +#define SICSLOWPAN_CONF_COMPRESSION_HC01 2 +#define SICSLOWPAN_CONF_COMPRESSION SICSLOWPAN_COMPRESSION_HC06 +#ifndef SICSLOWPAN_CONF_FRAG +#define SICSLOWPAN_CONF_FRAG 1 +#define SICSLOWPAN_CONF_MAXAGE 8 +#endif /* SICSLOWPAN_CONF_FRAG */ +#define SICSLOWPAN_CONF_MAX_ADDR_CONTEXTS 2 +#ifndef SICSLOWPAN_CONF_MAX_MAC_TRANSMISSIONS +#define SICSLOWPAN_CONF_MAX_MAC_TRANSMISSIONS 5 +#endif /* SICSLOWPAN_CONF_MAX_MAC_TRANSMISSIONS */ +#define UIP_CONF_ICMP_DEST_UNREACH 1 + +#define UIP_CONF_DHCP_LIGHT +#ifndef UIP_CONF_RECEIVE_WINDOW +#define UIP_CONF_RECEIVE_WINDOW 48 +#endif +#ifndef UIP_CONF_TCP_MSS +#define UIP_CONF_TCP_MSS 48 +#endif +#define UIP_CONF_MAX_CONNECTIONS 4 +#define UIP_CONF_MAX_LISTENPORTS 8 +#define UIP_CONF_UDP_CONNS 12 +#define UIP_CONF_FWCACHE_SIZE 30 +#define UIP_CONF_BROADCAST 1 +#define UIP_ARCH_CHKSUM 0 +#define UIP_ARCH_ADD32 0 +#define UIP_CONF_UDP 1 +#define UIP_CONF_UDP_CHECKSUMS 1 +#define UIP_CONF_PINGADDRCONF 0 +#define UIP_CONF_LOGGING 0 +#define LOG_CONF_ENABLED 0 + +#define UIP_CONF_TCP_SPLIT 0 + +#define UIP_CONF_BYTE_ORDER UIP_BIG_ENDIAN +#define UIP_CONF_LOGGING 0 + +#endif /* NETSTACK_CONF_WITH_IPV6 */ + +/* include the project config */ +/* PROJECT_CONF_H might be defined in the project Makefile */ +#ifdef PROJECT_CONF_H +#include PROJECT_CONF_H +#endif /* PROJECT_CONF_H */ + +#endif /* CONTIKI_CONF_H_ */ diff --git a/platform/jn516x/contiki-jn516x-main.c b/platform/jn516x/contiki-jn516x-main.c new file mode 100644 index 000000000..2bf27e64b --- /dev/null +++ b/platform/jn516x/contiki-jn516x-main.c @@ -0,0 +1,468 @@ +/* + * Copyright (c) 2014, SICS Swedish ICT. + * 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. The name of the author may not be used to endorse or promote + * products derived from this software without specific prior + * written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. + * + * This file is part of the Contiki OS + * + */ + +/** + * \file + * Contiki main for NXP JN516X platform + * + * \author + * Beshr Al Nahas + */ + +#include +#include +#include + +#include "dev/watchdog.h" +#include +#include +#include +#include "dev/uart0.h" + +#include "contiki.h" +#include "net/netstack.h" + +#include "dev/serial-line.h" + +#include "net/ip/uip.h" +#include "dev/leds.h" + +#include "lib/random.h" +#include "sys/node-id.h" +#include "rtimer-arch.h" + +#if NETSTACK_CONF_WITH_IPV6 +#include "net/ipv6/uip-ds6.h" +#endif /* NETSTACK_CONF_WITH_IPV6 */ + +#include "net/rime/rime.h" + +#include "dev/micromac-radio.h" +#include "MMAC.h" +/* Includes depending on connected sensor boards */ +#if SENSOR_BOARD_DR1175 +#include "light-sensor.h" +#include "ht-sensor.h" +SENSORS(&light_sensor, &ht_sensor); +#elif SENSOR_BOARD_DR1199 +#include "button-sensor.h" +#include "pot-sensor.h" +SENSORS(&pot_sensor, &button_sensor); +#else +#include "dev/button-sensor.h" +/* #include "dev/pir-sensor.h" */ +/* #include "dev/vib-sensor.h" */ +/* &pir_sensor, &vib_sensor */ +SENSORS(&button_sensor); +#endif +unsigned char node_mac[8]; + +/* Symbol defined by the linker script + * marks the end of the stack taking into account the used heap */ +extern uint32_t heap_location; + +#ifndef NETSTACK_CONF_WITH_IPV4 +#define NETSTACK_CONF_WITH_IPV4 0 +#endif + +#if NETSTACK_CONF_WITH_IPV4 +#include "net/ip/uip.h" +#include "net/ipv4/uip-fw.h" +#include "net/ipv4/uip-fw-drv.h" +#include "net/ipv4/uip-over-mesh.h" +static struct uip_fw_netif slipif = +{ UIP_FW_NETIF(192, 168, 1, 2, 255, 255, 255, 255, slip_send) }; +static struct uip_fw_netif meshif = +{ UIP_FW_NETIF(172, 16, 0, 0, 255, 255, 0, 0, uip_over_mesh_send) }; + +#define UIP_OVER_MESH_CHANNEL 8 +static uint8_t is_gateway; +#endif /* NETSTACK_CONF_WITH_IPV4 */ + +#ifdef EXPERIMENT_SETUP +#include "experiment-setup.h" +#endif + +/*---------------------------------------------------------------------------*/ +#define DEBUG 1 +#if DEBUG +#define PRINTF(...) do { printf(__VA_ARGS__); } while(0) +#else +#define PRINTF(...) do {} while(0) +#endif +/*---------------------------------------------------------------------------*/ +/* Reads MAC from SoC + * Must be called before node_id_restore() + * and network addresses initialization */ +static void +init_node_mac(void) +{ + tuAddr psExtAddress; + vMMAC_GetMacAddress(&psExtAddress.sExt); + node_mac[7] = psExtAddress.sExt.u32L; + node_mac[6] = psExtAddress.sExt.u32L >> (uint32_t)8; + node_mac[5] = psExtAddress.sExt.u32L >> (uint32_t)16; + node_mac[4] = psExtAddress.sExt.u32L >> (uint32_t)24; + node_mac[3] = psExtAddress.sExt.u32H; + node_mac[2] = psExtAddress.sExt.u32H >> (uint32_t)8; + node_mac[1] = psExtAddress.sExt.u32H >> (uint32_t)16; + node_mac[0] = psExtAddress.sExt.u32H >> (uint32_t)24; +} +/*---------------------------------------------------------------------------*/ +#if !PROCESS_CONF_NO_PROCESS_NAMES +static void +print_processes(struct process *const processes[]) +{ + /* const struct process * const * p = processes;*/ + PRINTF("Starting"); + while(*processes != NULL) { + PRINTF(" '%s'", (*processes)->name); + processes++; + } + putchar('\n'); +} +#endif /* !PROCESS_CONF_NO_PROCESS_NAMES */ +/*---------------------------------------------------------------------------*/ +#if NETSTACK_CONF_WITH_IPV4 +static void +set_gateway(void) +{ + if(!is_gateway) { + leds_on(LEDS_RED); + printf("%d.%d: making myself the IP network gateway.\n\n", + linkaddr_node_addr.u8[0], linkaddr_node_addr.u8[1]); + printf("IPv4 address of the gateway: %d.%d.%d.%d\n\n", + uip_ipaddr_to_quad(&uip_hostaddr)); + uip_over_mesh_set_gateway(&linkaddr_node_addr); + uip_over_mesh_make_announced_gateway(); + is_gateway = 1; + } +} +#endif /* NETSTACK_CONF_WITH_IPV4 */ +/*---------------------------------------------------------------------------*/ +static void +start_autostart_processes() +{ +#if !PROCESS_CONF_NO_PROCESS_NAMES + print_processes(autostart_processes); +#endif /* !PROCESS_CONF_NO_PROCESS_NAMES */ + autostart_start(autostart_processes); +} +/*---------------------------------------------------------------------------*/ +#if NETSTACK_CONF_WITH_IPV6 +static void +start_uip6(void) +{ + NETSTACK_NETWORK.init(); + +#ifndef WITH_SLIP_RADIO + process_start(&tcpip_process, NULL); +#else +#if WITH_SLIP_RADIO == 0 + process_start(&tcpip_process, NULL); +#endif +#endif /* WITH_SLIP_RADIO */ + +#if DEBUG + PRINTF("Tentative link-local IPv6 address "); + { + uip_ds6_addr_t *lladdr; + int i; + lladdr = uip_ds6_get_link_local(-1); + for(i = 0; i < 7; ++i) { + PRINTF("%02x%02x:", lladdr->ipaddr.u8[i * 2], + lladdr->ipaddr.u8[i * 2 + 1]); + /* make it hardcoded... */ + } + lladdr->state = ADDR_AUTOCONF; + + PRINTF("%02x%02x\n", lladdr->ipaddr.u8[14], lladdr->ipaddr.u8[15]); + } +#endif /* DEBUG */ + + if(!UIP_CONF_IPV6_RPL) { + uip_ipaddr_t ipaddr; + int i; + uip_ip6addr(&ipaddr, 0xaaaa, 0, 0, 0, 0, 0, 0, 0); + uip_ds6_set_addr_iid(&ipaddr, &uip_lladdr); + uip_ds6_addr_add(&ipaddr, 0, ADDR_TENTATIVE); + PRINTF("Tentative global IPv6 address "); + for(i = 0; i < 7; ++i) { + PRINTF("%02x%02x:", + ipaddr.u8[i * 2], ipaddr.u8[i * 2 + 1]); + } + PRINTF("%02x%02x\n", + ipaddr.u8[7 * 2], ipaddr.u8[7 * 2 + 1]); + } +} +#endif /* NETSTACK_CONF_WITH_IPV6 */ +/*---------------------------------------------------------------------------*/ +static void +start_network_layer(void) +{ +#if NETSTACK_CONF_WITH_IPV6 + start_uip6(); +#endif /* NETSTACK_CONF_WITH_IPV6 */ + start_autostart_processes(); + /* To support link layer security in combination with NETSTACK_CONF_WITH_IPV4 and + * TIMESYNCH_CONF_ENABLED further things may need to be moved here */ +} +/*--------------------------------------------------------------------------*/ +static void +set_linkaddr(void) +{ + int i; + linkaddr_t addr; + memset(&addr, 0, sizeof(linkaddr_t)); +#if NETSTACK_CONF_WITH_IPV6 + memcpy(addr.u8, node_mac, sizeof(addr.u8)); +#else + if(node_id == 0) { + for(i = 0; i < sizeof(linkaddr_t); ++i) { + addr.u8[i] = node_mac[7 - i]; + } + } else { + addr.u8[0] = node_id & 0xff; + addr.u8[1] = node_id >> 8; + } +#endif + linkaddr_set_node_addr(&addr); +#if DEBUG + PRINTF("Link-layer address: "); + for(i = 0; i < sizeof(addr.u8) - 1; i++) { + PRINTF("%d.", addr.u8[i]); + } + PRINTF("%d\n", addr.u8[i]); +#endif +} +/*---------------------------------------------------------------------------*/ +#if USE_EXTERNAL_OSCILLATOR +static bool_t +init_xosc(void) +{ + /* The internal 32kHz RC oscillator is used by default; + * Initialize and enable the external 32.768kHz crystal. + */ + vAHI_Init32KhzXtal(); + /* wait for 1.0 seconds for the crystal to stabilize */ + clock_time_t start = clock_time(); + clock_time_t now; + do { + now = clock_time(); + watchdog_periodic(); + } while(now - start < CLOCK_SECOND); + /* switch to the 32.768 kHz crystal */ + return bAHI_Set32KhzClockMode(E_AHI_XTAL); +} +#endif +/*---------------------------------------------------------------------------*/ +#if WITH_TINYOS_AUTO_IDS +uint16_t TOS_NODE_ID = 0x1234; /* non-zero */ +uint16_t TOS_LOCAL_ADDRESS = 0x1234; /* non-zero */ +#endif /* WITH_TINYOS_AUTO_IDS */ +int +main(void) +{ + /* Set stack overflow address for detecting overflow in runtime */ + vAHI_SetStackOverflow(TRUE, ((uint32_t *)&heap_location)[0]); + + clock_init(); + watchdog_init(); + leds_init(); + leds_on(LEDS_ALL); + init_node_mac(); + + energest_init(); + ENERGEST_ON(ENERGEST_TYPE_CPU); + + node_id_restore(); + +#if WITH_TINYOS_AUTO_IDS + node_id = TOS_NODE_ID; +#endif /* WITH_TINYOS_AUTO_IDS */ + /* for setting "hardcoded" IEEE 802.15.4 MAC addresses */ +#ifdef IEEE_802154_MAC_ADDRESS + { + uint8_t ieee[] = IEEE_802154_MAC_ADDRESS; + memcpy(node_mac, ieee, sizeof(uip_lladdr.addr)); + node_mac[7] = node_id & 0xff; + } +#endif + + /* Initialize random with a seed from the SoC random generator. + * This must be done before selecting the high-precision external oscillator. + */ + vAHI_StartRandomNumberGenerator(E_AHI_RND_SINGLE_SHOT, E_AHI_INTS_DISABLED); + random_init(u16AHI_ReadRandomNumber()); + + process_init(); + ctimer_init(); + uart0_init(UART_BAUD_RATE); /* Must come before first PRINTF */ + +#if USE_EXTERNAL_OSCILLATOR + init_xosc(); +#endif + +#if NETSTACK_CONF_WITH_IPV4 + slip_arch_init(UART_BAUD_RATE); +#endif /* NETSTACK_CONF_WITH_IPV4 */ + + /* check for reset source */ + if(bAHI_WatchdogResetEvent()) { + PRINTF("Init: Watchdog timer has reset device!\r\n"); + } + process_start(&etimer_process, NULL); + set_linkaddr(); + netstack_init(); + +#if NETSTACK_CONF_WITH_IPV6 +#if UIP_CONF_IPV6_RPL + PRINTF(CONTIKI_VERSION_STRING " started with IPV6, RPL\n"); +#else + PRINTF(CONTIKI_VERSION_STRING " started with IPV6\n"); +#endif +#elif NETSTACK_CONF_WITH_IPV4 + PRINTF(CONTIKI_VERSION_STRING " started with IPV4\n"); +#else + PRINTF(CONTIKI_VERSION_STRING " started\n"); +#endif + + if(node_id > 0) { + PRINTF("Node id is set to %u.\n", node_id); + } else { + PRINTF("Node id is not set.\n"); + } +#if NETSTACK_CONF_WITH_IPV6 + memcpy(&uip_lladdr.addr, node_mac, sizeof(uip_lladdr.addr)); + queuebuf_init(); +#endif /* NETSTACK_CONF_WITH_IPV6 */ + + PRINTF("%s %s %s\n", NETSTACK_LLSEC.name, NETSTACK_MAC.name, NETSTACK_RDC.name); + +#if !NETSTACK_CONF_WITH_IPV4 && !NETSTACK_CONF_WITH_IPV6 + uart0_set_input(serial_line_input_byte); + serial_line_init(); +#endif + +#if TIMESYNCH_CONF_ENABLED + timesynch_init(); + timesynch_set_authority_level((linkaddr_node_addr.u8[0] << 4) + 16); +#endif /* TIMESYNCH_CONF_ENABLED */ + +#if NETSTACK_CONF_WITH_IPV4 + process_start(&tcpip_process, NULL); + process_start(&uip_fw_process, NULL); /* Start IP output */ + process_start(&slip_process, NULL); + + slip_set_input_callback(set_gateway); + + { + uip_ipaddr_t hostaddr, netmask; + + uip_init(); + + uip_ipaddr(&hostaddr, 172, 16, + linkaddr_node_addr.u8[0], linkaddr_node_addr.u8[1]); + uip_ipaddr(&netmask, 255, 255, 0, 0); + uip_ipaddr_copy(&meshif.ipaddr, &hostaddr); + + uip_sethostaddr(&hostaddr); + uip_setnetmask(&netmask); + uip_over_mesh_set_net(&hostaddr, &netmask); + /* uip_fw_register(&slipif);*/ + uip_over_mesh_set_gateway_netif(&slipif); + uip_fw_default(&meshif); + uip_over_mesh_init(UIP_OVER_MESH_CHANNEL); + PRINTF("uIP started with IP address %d.%d.%d.%d\n", + uip_ipaddr_to_quad(&hostaddr)); + } +#endif /* NETSTACK_CONF_WITH_IPV4 */ + + watchdog_start(); + NETSTACK_LLSEC.bootstrap(start_network_layer); + + leds_off(LEDS_ALL); + int r; + while(1) { + do { + /* Reset watchdog. */ + watchdog_periodic(); + r = process_run(); + } while(r > 0); + /* + * Idle processing. + */ + watchdog_stop(); + +#if DCOSYNCH_CONF_ENABLED + /* Calibrate the DCO every DCOSYNCH_PERIOD + * if we have more than 500uSec until next rtimer + * PS: Calibration disables interrupts and blocks for 200uSec. + * */ + static unsigned long last_dco_calibration_time = 0; + if(clock_seconds() - last_dco_calibration_time > DCOSYNCH_PERIOD) { + if(rtimer_arch_get_time_until_next_wakeup() > RTIMER_SECOND / 2000) { + /* PRINTF("ContikiMain: Calibrating the DCO\n"); */ + eAHI_AttemptCalibration(); + /* Patch to allow CpuDoze after calibration */ + vREG_PhyWrite(REG_PHY_IS, REG_PHY_INT_VCO_CAL_MASK); + last_dco_calibration_time = clock_seconds(); + } + } +#endif /* DCOSYNCH_CONF_ENABLED */ + ENERGEST_OFF(ENERGEST_TYPE_CPU); + ENERGEST_ON(ENERGEST_TYPE_LPM); + vAHI_CpuDoze(); + watchdog_start(); + ENERGEST_OFF(ENERGEST_TYPE_LPM); + ENERGEST_ON(ENERGEST_TYPE_CPU); + } + + return 0; +} +/*---------------------------------------------------------------------------*/ +void +AppColdStart(void) +{ + /* After reset or sleep with memory off */ + main(); +} +/*---------------------------------------------------------------------------*/ +void +AppWarmStart(void) +{ + /* Wakeup after sleep with memory on. + * TODO: Need to initialize devices but not the application state */ + main(); +} +/*---------------------------------------------------------------------------*/ diff --git a/platform/jn516x/dev/ccm-star.c b/platform/jn516x/dev/ccm-star.c new file mode 100644 index 000000000..76bf97caf --- /dev/null +++ b/platform/jn516x/dev/ccm-star.c @@ -0,0 +1,168 @@ +/* + * Copyright (c) 2015, SICS Swedish ICT. + * 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 Institute 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 INSTITUTE 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 INSTITUTE 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. + * + * This file is part of the Contiki operating system. + * + */ + +/** + * \file + * CCM* header implementation exploiting the JN516x + * cryptographic co-processor + * \author + * Simon Duquennoy + */ + +#include "ccm-star.h" +#include +#include + +static tsReg128 current_key; +static int current_key_is_new = 1; + +/*---------------------------------------------------------------------------*/ +static void +mic(const uint8_t *m, uint8_t m_len, + const uint8_t *nonce, + const uint8_t *a, uint8_t a_len, + uint8_t *result, + uint8_t mic_len) +{ + tsReg128 nonce_aligned; + memcpy(&nonce_aligned, nonce, sizeof(nonce_aligned)); + bACI_CCMstar( + ¤t_key, + current_key_is_new, + XCV_REG_AES_SET_MODE_CCM, + mic_len, + a_len, + m_len, + &nonce_aligned, + (uint8_t *)a, + (uint8_t *)m, + NULL, + result, + NULL + ); + current_key_is_new = 0; +} +/*---------------------------------------------------------------------------*/ +static void +ctr(uint8_t *m, uint8_t m_len, const uint8_t *nonce) +{ + tsReg128 nonce_aligned; + memcpy(&nonce_aligned, nonce, sizeof(nonce_aligned)); + bACI_CCMstar( + ¤t_key, + current_key_is_new, + XCV_REG_AES_SET_MODE_CCM, + 0, + 0, + m_len, + &nonce_aligned, + NULL, + m, + m, + NULL, + NULL + ); + current_key_is_new = 0; +} +/*---------------------------------------------------------------------------*/ +static void +aead(const uint8_t *nonce, + uint8_t *m, uint8_t m_len, + const uint8_t *a, uint8_t a_len, + uint8_t *result, uint8_t mic_len, + int forward) +{ + tsReg128 nonce_aligned; + memcpy(&nonce_aligned, nonce, sizeof(nonce_aligned)); + if(forward) { + bACI_CCMstar( + ¤t_key, + current_key_is_new, + XCV_REG_AES_SET_MODE_CCM, + mic_len, + a_len, + m_len, + &nonce_aligned, + (uint8_t *)a, + (uint8_t *)m, + (uint8_t *)m, + result, + NULL + ); + } else { + bool_t auth; + bACI_CCMstar( + ¤t_key, + current_key_is_new, + XCV_REG_AES_SET_MODE_CCM_D, + mic_len, + a_len, + m_len, + &nonce_aligned, + (uint8_t *)a, + (uint8_t *)m, + (uint8_t *)m, + (uint8_t *)a + a_len + m_len, + &auth + ); + /* To comply with the CCM_STAR interface, copy MIC to result in case of success */ + if(result != NULL) { + if(auth) { + memcpy(result, a + a_len + m_len, mic_len); + } else { + /* Otherwise, corrupt the result */ + memcpy(result, a + a_len + m_len, mic_len); + result[0]++; + } + } + } + + current_key_is_new = 0; +} +/*---------------------------------------------------------------------------*/ +static void +set_key(const uint8_t *key) +{ + if(memcmp(¤t_key, key, sizeof(current_key)) == 0) { + current_key_is_new = 0; + } else { + memcpy(¤t_key, key, sizeof(current_key)); + current_key_is_new = 1; + } +} +/*---------------------------------------------------------------------------*/ +const struct ccm_star_driver ccm_star_driver_jn516x = { + mic, + ctr, + set_key +}; +/*---------------------------------------------------------------------------*/ diff --git a/platform/jn516x/dev/clock.c b/platform/jn516x/dev/clock.c new file mode 100644 index 000000000..e2b1d46a3 --- /dev/null +++ b/platform/jn516x/dev/clock.c @@ -0,0 +1,250 @@ +/* + * Copyright (c) 2014, SICS Swedish ICT. + * 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 Institute 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 INSTITUTE 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 INSTITUTE 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. + * + * This file is part of the Contiki operating system. + * + */ + +/** + * \file + * Clock implementation for NXP jn516x. + * \author + * Beshr Al Nahas + * + */ + +#include +#include +#include "contiki.h" +#include "sys/energest.h" +#include "sys/clock.h" +#include "sys/etimer.h" +#include "rtimer-arch.h" +#include "dev/watchdog.h" + +/** + * TickTimer will be used for RTIMER + * E_AHI_TIMER_1 will be used for ticking + **/ + +#define DEBUG 0 +#if DEBUG +#include +#define PRINTF(...) printf(__VA_ARGS__) +#else +#define PRINTF(...) +#endif + +static volatile unsigned long seconds = 0; +static volatile uint8_t ticking = 0; +static volatile clock_time_t clock_ticks = 0; +/* last_tar is used for calculating clock_fine */ + +#define CLOCK_TIMER E_AHI_TIMER_1 +#define CLOCK_TIMER_ISR_DEV E_AHI_DEVICE_TIMER1 +/* 16Mhz / 2^7 = 125Khz */ +#define CLOCK_PRESCALE 7 +/* 10ms tick --> overflow after ~981/2 days */ +#define CLOCK_INTERVAL (125 * 10) +#define MAX_TICKS (CLOCK_INTERVAL) +/*---------------------------------------------------------------------------*/ +void +clockTimerISR(uint32 u32Device, uint32 u32ItemBitmap) +{ + if(u32Device != CLOCK_TIMER_ISR_DEV) { + return; + } + ENERGEST_ON(ENERGEST_TYPE_IRQ); + + watchdog_start(); + + clock_ticks++; + if(clock_ticks % CLOCK_CONF_SECOND == 0) { + ++seconds; + energest_flush(); + } + if(etimer_pending() && (etimer_next_expiration_time() - clock_ticks - 1) > MAX_TICKS) { + etimer_request_poll(); + /* TODO exit low-power mode */ + } + if(process_nevents() >= 0) { + /* TODO exit low-power mode */ + } + + watchdog_stop(); + + ENERGEST_OFF(ENERGEST_TYPE_IRQ); +} +/*---------------------------------------------------------------------------*/ +static void +clock_timer_init(void) +{ + vAHI_TimerEnable(CLOCK_TIMER, CLOCK_PRESCALE, 0, 1, 0); + vAHI_TimerClockSelect(CLOCK_TIMER, 0, 0); + + vAHI_TimerConfigureOutputs(CLOCK_TIMER, 0, 1); + vAHI_TimerDIOControl(CLOCK_TIMER, 0); + +#if (CLOCK_TIMER == E_AHI_TIMER_0) + vAHI_Timer0RegisterCallback(clockTimerISR); +#elif (CLOCK_TIMER == E_AHI_TIMER_1) + vAHI_Timer1RegisterCallback(clockTimerISR); +#endif + clock_ticks = 0; + vAHI_TimerStartRepeat(CLOCK_TIMER, 0, CLOCK_INTERVAL); + ticking = 1; +} +/*---------------------------------------------------------------------------*/ +void +clock_init(void) +{ + /* gMAC_u8MaxBuffers = 2; */ +#ifdef JENNIC_CHIP_FAMILY_JN516x + /* Turn off debugger */ + *(volatile uint32 *)0x020000a0 = 0; +#endif + /* system controller interrupts callback is disabled + * -- Only wake Interrupts -- + */ + vAHI_SysCtrlRegisterCallback(0); + + /* schedule clock tick interrupt */ + clock_timer_init(); + rtimer_init(); + (void)u32AHI_Init(); + + bAHI_SetClockRate(E_AHI_XTAL_32MHZ); + + /* Wait for oscillator to stabilise */ + while(bAHI_GetClkSource() == 1) ; + while(bAHI_Clock32MHzStable() == 0) ; + + vAHI_OptimiseWaitStates(); + + /* Turn on SPI master */ + vREG_SysWrite(REG_SYS_PWR_CTRL, u32REG_SysRead(REG_SYS_PWR_CTRL) + | REG_SYSCTRL_PWRCTRL_SPIMEN_MASK); +} +/*---------------------------------------------------------------------------*/ +clock_time_t +clock_time(void) +{ + clock_time_t t1, t2; + do { + t1 = clock_ticks; + t2 = clock_ticks; + } while(t1 != t2); + return t1; +} +/*---------------------------------------------------------------------------*/ +void +clock_set(clock_time_t clock, clock_time_t fclock) +{ + clock_ticks = clock; +} +/*---------------------------------------------------------------------------*/ +int +clock_fine_max(void) +{ + return CLOCK_INTERVAL; +} +/*---------------------------------------------------------------------------*/ +/** + * Delay the CPU for a multiple of 0.0625 us. + */ +void +clock_delay_usec(uint16_t dt) +{ + volatile uint32_t t = u32AHI_TickTimerRead(); +#define RTIMER_MAX_TICKS 0xffffffff + /* beware of wrapping */ + if(RTIMER_MAX_TICKS - t < dt) { + while(u32AHI_TickTimerRead() < RTIMER_MAX_TICKS && u32AHI_TickTimerRead() != 0) ; + dt -= RTIMER_MAX_TICKS - t; + t = 0; + } + while(u32AHI_TickTimerRead() - t < dt) { + watchdog_periodic(); + } +} +/*---------------------------------------------------------------------------*/ +/** + * Delay the CPU for a multiple of 8 us. + */ +void +clock_delay(unsigned int i) +{ + volatile uint32_t t = u16AHI_TimerReadCount(CLOCK_TIMER); + /* beware of wrapping */ + if(MAX_TICKS - t < i) { + while(u16AHI_TimerReadCount(CLOCK_TIMER) < MAX_TICKS && u16AHI_TimerReadCount(CLOCK_TIMER) != 0) ; + i -= MAX_TICKS - t; + t = 0; + } + while(u16AHI_TimerReadCount(CLOCK_TIMER) - t < i) { + watchdog_periodic(); + } +} +/*---------------------------------------------------------------------------*/ +/** + * Wait for a multiple of 10 ms. + * + */ +void +clock_wait(clock_time_t t) +{ + clock_time_t start; + + start = clock_time(); + while(clock_time() - start < (clock_time_t)t) { + watchdog_periodic(); + } +} +/*---------------------------------------------------------------------------*/ +void +clock_set_seconds(unsigned long sec) +{ + seconds = sec; +} +/*---------------------------------------------------------------------------*/ +unsigned long +clock_seconds(void) +{ + unsigned long t1, t2; + do { + t1 = seconds; + t2 = seconds; + } while(t1 != t2); + return t1; +} +/*---------------------------------------------------------------------------*/ +rtimer_clock_t +clock_counter(void) +{ + return rtimer_arch_now(); +} diff --git a/platform/jn516x/dev/dongle/README.md b/platform/jn516x/dev/dongle/README.md new file mode 100644 index 000000000..a9b6e9cb2 --- /dev/null +++ b/platform/jn516x/dev/dongle/README.md @@ -0,0 +1,9 @@ +This directory contains the contiki driver for the LED driver for the dongle. + +Mapping of LEDs on JN516x Dongle: + leds.h led on dongle: + LEDS_RED Red LED + LEDS_GREEN Green LED +Note: Only one LED can be switch on at the same time + + diff --git a/platform/jn516x/dev/dongle/leds-arch.c b/platform/jn516x/dev/dongle/leds-arch.c new file mode 100644 index 000000000..5eff3c63e --- /dev/null +++ b/platform/jn516x/dev/dongle/leds-arch.c @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2015 NXP B.V. + * 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 NXP B.V. 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 NXP B.V. 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 NXP B.V. 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. + * + * This file is part of the Contiki operating system. + * + * Author: Theo van Daele + * + */ +#include "contiki.h" +#include "leds.h" +#include + +#define LED_G (1 << 16) +#define LED_R (1 << 17) + +static volatile uint8_t leds; + +/*---------------------------------------------------------------------------*/ +void +leds_arch_init(void) +{ + vAHI_DioSetDirection(0, LED_R | LED_G); + vAHI_DioSetOutput(0, LED_R | LED_G); /* Default off */ + leds = 0; +} +/*---------------------------------------------------------------------------*/ +unsigned char +leds_arch_get(void) +{ + return leds; +} +/*---------------------------------------------------------------------------*/ +void +leds_arch_set(unsigned char c) +{ + uint32 on_mask = 0; + uint32 off_mask = 0; + + if(c & LEDS_GREEN) { + on_mask |= LED_G; + } else { + off_mask |= LED_G; + } if(c & LEDS_RED) { + on_mask |= LED_R; + } else { + off_mask |= LED_R; + } vAHI_DioSetOutput(on_mask, off_mask); + /* Both LEDs can not be switched on at the same time. + Will result in both leds being OFF */ + if(on_mask == (LED_R | LED_G)) { + leds = 0; + } else { + leds = c; + } +} diff --git a/platform/jn516x/dev/dr1174/README.md b/platform/jn516x/dev/dr1174/README.md new file mode 100644 index 000000000..d3a21cbe0 --- /dev/null +++ b/platform/jn516x/dev/dr1174/README.md @@ -0,0 +1,8 @@ +This directory contains the contiki driver for the button sensor on the DR1174 baseboard. +When used with an extention board, sensors from the dr1175 anf dr1179 directories are used in addition to this. +leds-arch.c implements the led driver for leds D3 and D6 on the board. +Mapping of LEDs on JN516x DR1174: + leds.h: led on DR1174: + LEDS_GP0 LED D3 + LEDS_GP1 LED D6 +Note: LEDS_GPx definitions included in leds.h via platform-conf.h diff --git a/platform/jn516x/dev/dr1174/button-sensor.c b/platform/jn516x/dev/dr1174/button-sensor.c new file mode 100644 index 000000000..9262a6ef8 --- /dev/null +++ b/platform/jn516x/dev/dr1174/button-sensor.c @@ -0,0 +1,241 @@ +/* + * Copyright (c) 2015 NXP B.V. + * 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 NXP B.V. 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 NXP B.V. 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 NXP B.V. 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. + * + * This file is part of the Contiki operating system. + * + * Author: Theo van Daele + * + */ +#include "contiki.h" +#include "sys/etimer.h" +#include "lib/sensors.h" +#include "button-sensor.h" +#include + +/*---------------------------------------------------------------------------*/ +/* LOCAL DEFINITIONS */ +/*---------------------------------------------------------------------------*/ +/* #define DEBUG */ +#ifdef DEBUG +#include +#define PRINTF(...) printf(__VA_ARGS__) +#else +#define PRINTF(...) +#endif + +typedef enum { + APP_E_BUTTON_SW0 = 0, +#if SENSOR_BOARD_DR1199 + APP_E_BUTTON_SW1, + APP_E_BUTTON_SW2, + APP_E_BUTTON_SW3, + APP_E_BUTTON_SW4, +#endif /* SENSOR_BOARD_DR1199 */ + APP_E_BUTTON_NUM /* Number of buttons */ +} app_e_button_t; + +/* Mapping of DIO port connections to buttons. Use as mask to get button value */ +#define APP_PORT_BUTTON_SW0 (8) +#if SENSOR_BOARD_DR1199 +#define APP_PORT_BUTTON_SW1 (11) +#define APP_PORT_BUTTON_SW2 (12) +#define APP_PORT_BUTTON_SW3 (17) +#define APP_PORT_BUTTON_SW4 (1) +#endif /* SENSOR_BOARD_DR1199 */ + +/* Definition of port masks based on button mapping */ +#if SENSOR_BOARD_DR1199 +#define APP_BUTTONS_DIO_MASK ((1 << APP_PORT_BUTTON_SW0) | \ + (1 << APP_PORT_BUTTON_SW1) | \ + (1 << APP_PORT_BUTTON_SW2) | \ + (1 << APP_PORT_BUTTON_SW3) | \ + (1 << APP_PORT_BUTTON_SW4)) +#else /* SENSOR_BOARD_DR1199 */ +#define APP_BUTTONS_DIO_MASK (1 << APP_PORT_BUTTON_SW0) +#endif /* SENSOR_BOARD_DR1199 */ + +#define KEY_SAMPLE_TIME (CLOCK_SECOND / 20) + +typedef enum { + BUTTONS_STATUS_NOT_INIT = 0, + BUTTONS_STATUS_INIT, + BUTTONS_STATUS_NOT_ACTIVE = BUTTONS_STATUS_INIT, + BUTTONS_STATUS_ACTIVE +} buttons_status_t; + +/*---------------------------------------------------------------------------*/ +/* LOCAL DATA DEFINITIONS */ +/*---------------------------------------------------------------------------*/ +const struct sensors_sensor button_sensor; +volatile static buttons_status_t buttons_status = BUTTONS_STATUS_NOT_INIT; +static int key_value = 0; +static uint8 key_map[] = { APP_PORT_BUTTON_SW0, /* APP_E_BUTTON_SW0 */ +#if SENSOR_BOARD_DR1199 + APP_PORT_BUTTON_SW1, /* APP_E_BUTTON_SW1 */ + APP_PORT_BUTTON_SW2, /* APP_E_BUTTON_SW2 */ + APP_PORT_BUTTON_SW3, /* APP_E_BUTTON_SW3 */ + APP_PORT_BUTTON_SW4 /* APP_E_BUTTON_SW4 */ +#endif /* SENSOR_BOARD_DR1199 */ +}; + +/*---------------------------------------------------------------------------*/ +/* LOCAL FUNCTION PROTOTYPES */ +/*---------------------------------------------------------------------------*/ +PROCESS(key_sampling, "Key sample"); +static int get_key_value(void); + +/*---------------------------------------------------------------------------*/ +/* PUBLIC FUNCTIONS */ +/*---------------------------------------------------------------------------*/ +static int +configure(int type, int value) +{ + if(type == SENSORS_HW_INIT) { + /* Called from sensor thread when started. + Configure DIO lines with buttons connected as input */ + vAHI_DioSetDirection(APP_BUTTONS_DIO_MASK, 0); + /* Turn on pull-ups for DIO lines with buttons connected */ + vAHI_DioSetPullup(APP_BUTTONS_DIO_MASK, 0); + PRINTF("HW_INIT BUTTONS (0x%x)\n", APP_BUTTONS_DIO_MASK); + /* Configure debounce timer. Do not run it yet. */ + buttons_status = BUTTONS_STATUS_INIT; + process_start(&key_sampling, NULL); + return 1; + } else if(type == SENSORS_ACTIVE) { + if(buttons_status != BUTTONS_STATUS_NOT_INIT) { + if(value) { + /* Button sensor activated */ + PRINTF("BUTTONS ACTIVATED\n"); + buttons_status = BUTTONS_STATUS_ACTIVE; + } else { + /* Button sensor de-activated */ + PRINTF("BUTTONS DE-ACTIVATED\n"); + buttons_status = BUTTONS_STATUS_NOT_ACTIVE; + } + process_post(&key_sampling, PROCESS_EVENT_MSG, (void *)&buttons_status); + return 1; + } else { + /* Buttons must be intialised before being (de)-activated */ + PRINTF("ERROR: NO HW_INIT BUTTONS\n"); + return 0; + } + } else { + /* Non valid type */ + return 0; + } +} +/*---------------------------------------------------------------------------*/ +static int +status(int type) +{ + if(type == SENSORS_ACTIVE) { + return buttons_status == BUTTONS_STATUS_ACTIVE; + } else if(type == SENSORS_READY) { + return buttons_status != BUTTONS_STATUS_NOT_INIT; + } + return 0; +} +/*---------------------------------------------------------------------------*/ +static int +value(int type) +{ + /* type: Not defined for the buttons interface + */ + return key_value; +} +/*---------------------------------------------------------------------------*/ +/* LOCAL FUNCTIONS */ +/*---------------------------------------------------------------------------*/ +static int +get_key_value(void) +{ + /* Function returns the actual key value. Pressed key will return '1' */ + int io_value = ~u32AHI_DioReadInput() & APP_BUTTONS_DIO_MASK; + int k = 0; + int key = 0; + + while(k < APP_E_BUTTON_NUM) { + if(io_value & (1 << key_map[k])) { + key |= (1 << k); + } + k++; + } + return key; +} +/* Process takes care of detecting key changes */ +/*---------------------------------------------------------------------------*/ +PROCESS_THREAD(key_sampling, ev, data) +{ + PROCESS_BEGIN(); + static struct etimer et; + static int previous_key_value = 0; + static char debounce_check = 0; + int current_key_value; + + etimer_set(&et, CLOCK_SECOND / 50); + while(1) { + PROCESS_WAIT_EVENT_UNTIL((ev == PROCESS_EVENT_TIMER) || (ev == PROCESS_EVENT_MSG)); + if(ev == PROCESS_EVENT_TIMER) { + /* Handle sensor reading. */ + PRINTF("Key sample\n"); + current_key_value = get_key_value(); + if(debounce_check != 0) { + /* Check if key remained constant */ + if(previous_key_value == current_key_value) { + sensors_changed(&button_sensor); + key_value = current_key_value; + debounce_check = 0; + } else { + /* Bouncing */ + previous_key_value = current_key_value; + } + } else + /* Check for new key change */ + if(current_key_value != previous_key_value) { + previous_key_value = current_key_value; + debounce_check = 1; + } + etimer_reset(&et); + } else { + /* ev == PROCESS_EVENT_MSG */ + if(*(buttons_status_t *)data == BUTTONS_STATUS_NOT_ACTIVE) { + /* Stop sampling */ + etimer_stop(&et); + } else if((*(buttons_status_t *)data == BUTTONS_STATUS_ACTIVE)) { + /* restart sampling */ + etimer_restart(&et); + } + } + } + PROCESS_END(); +} + +/*---------------------------------------------------------------------------*/ +/* Sensor defintion for sensor module */ +SENSORS_SENSOR(button_sensor, BUTTON_SENSOR, value, configure, status); +/*---------------------------------------------------------------------------*/ diff --git a/platform/jn516x/dev/dr1174/button-sensor.h b/platform/jn516x/dev/dr1174/button-sensor.h new file mode 100644 index 000000000..eaa87a751 --- /dev/null +++ b/platform/jn516x/dev/dr1174/button-sensor.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2015, SICS Swedish ICT. + * 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 Institute 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 INSTITUTE 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 INSTITUTE 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. + * + * This file is part of the Contiki operating system. + * + */ +#ifndef __BUTTON_SENSOR_H__ +#define __BUTTON_SENSOR_H__ + +#include "lib/sensors.h" + +extern const struct sensors_sensor button_sensor; + +#define BUTTON_SENSOR "Button" + +#endif /* __BUTTON_SENSOR_H__ */ diff --git a/platform/jn516x/dev/dr1174/leds-arch.c b/platform/jn516x/dev/dr1174/leds-arch.c new file mode 100644 index 000000000..4e49e9c53 --- /dev/null +++ b/platform/jn516x/dev/dr1174/leds-arch.c @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2015 NXP B.V. + * 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 NXP B.V. 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 NXP B.V. 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 NXP B.V. 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. + * + * This file is part of the Contiki operating system. + * + * Author: Theo van Daele + * + */ +#include "contiki.h" +#include "dev/leds.h" +#include +#ifdef SENSOR_BOARD_DR1199 +#include "dr1199/leds-arch-1199.h" +#endif +#ifdef SENSOR_BOARD_DR1175 +#include "leds-extension.h" +#include "dr1175/leds-arch-1175.h" +#endif + +#define LED_D3 (1 << 3) +#define LED_D6 (1 << 2) + +static volatile unsigned char leds; + +/*---------------------------------------------------------------------------*/ +void +leds_arch_init(void) +{ + vAHI_DioSetDirection(0, LED_D3 | LED_D6); + vAHI_DioSetOutput(LED_D3 | LED_D6, 0); /* Default off */ +#ifdef SENSOR_BOARD_DR1199 + leds_arch_init_1199(); +#endif +#ifdef SENSOR_BOARD_DR1175 + leds_arch_init_1175(); +#endif + leds = 0; +} +/*---------------------------------------------------------------------------*/ +unsigned char +leds_arch_get(void) +{ + return leds; +} +/*---------------------------------------------------------------------------*/ +void +leds_arch_set(unsigned char c) +{ + uint32 on_mask = 0; + uint32 off_mask = 0; + + /* LOW level on pins switches ON LED for DR1174 */ + if(c & LEDS_GP0) { + on_mask |= LED_D3; + } else { + off_mask |= LED_D3; + } if(c & LEDS_GP1) { + on_mask |= LED_D6; + } else { + off_mask |= LED_D6; + } vAHI_DioSetOutput(off_mask, on_mask); +#ifdef SENSOR_BOARD_DR1199 + /* DR1174 with DR1199 */ + leds_arch_set_1199(c); + if(c == LEDS_ALL) { + leds = LEDS_GP0 | LEDS_GP1 | LEDS_RED | LEDS_BLUE | LEDS_GREEN; + } else { + leds = (c & (LEDS_GP0 | LEDS_GP1 | LEDS_RED | LEDS_BLUE | LEDS_GREEN)); + } +#elif SENSOR_BOARD_DR1175 + /* DR1174 with DR1175 */ + leds_arch_set_1175(c); + if(c == LEDS_ALL) { + leds = LEDS_GP0 | LEDS_GP1 | LEDS_RED | LEDS_BLUE | LEDS_GREEN | LEDS_WHITE; + } else { + leds = (c & (LEDS_GP0 | LEDS_GP1 | LEDS_RED | LEDS_BLUE | LEDS_GREEN | LEDS_WHITE)); +/* printf("++++++++++++++++++++ leds_arch_set: leds: 0x%x\n", leds); */ + } +#else + /* DR1174-only */ + if(c == LEDS_ALL) { + leds = LEDS_GP0 | LEDS_GP1; + } else { + leds = c; + } +#endif +} +/*---------------------------------------------------------------------------*/ +void +leds_arch_set_level(unsigned char level, unsigned char c) +{ +#ifdef SENSOR_BOARD_DR1175 + leds_arch_set_level_1175(level, c, leds); +/* printf("++++++++++++++++++++ leds_arch_set_level: leds: 0x%x\n", leds); */ +#endif +} diff --git a/platform/jn516x/dev/dr1175/README.md b/platform/jn516x/dev/dr1175/README.md new file mode 100644 index 000000000..232e34768 --- /dev/null +++ b/platform/jn516x/dev/dr1175/README.md @@ -0,0 +1,18 @@ +This directory contains the contiki driver for the sensors (light, humidity and temperature sensor) available on the +NXP DR1175 board. This board is part of the NXP JN516X Evaluation Kit (see http://www.nxp.com/documents/leaflet/75017368.pdf). + +The dr1175 sensor code interfaces to the contiki `core/lib/sensors.c` framework. +The code is specificaly for the JN516X platform, because it makes use of the platform\DK4 libraries +of this JN516X SDK. +`examples/jn516x/rpl/coap-dr1175-node.c` shows an example on using this contiki driver. + +Mapping of LEDs on JN516x DR1175/DR1174: + leds.h: led on DR1175/DR1174: +DR1174+DR1175: + LEDS_RED Red led in RGB-led with level control on DR1175 + LEDS_GREEN Green led in RGB-led with level control on DR1175 + LEDS_BLUE Blue led in RGB-led with level control on DR1175 + LEDS_WHITE White power led with level control on DR1175 + LEDS_GP0 LEDS D3 on DR1174 + LEDS_GP1 LEDS D6 on DR1174 +Note: LEDS_GPx and LEDS_WHITE definitions included in leds.h via platform-conf.h diff --git a/platform/jn516x/dev/dr1175/ht-sensor.c b/platform/jn516x/dev/dr1175/ht-sensor.c new file mode 100644 index 000000000..76f889d84 --- /dev/null +++ b/platform/jn516x/dev/dr1175/ht-sensor.c @@ -0,0 +1,187 @@ +/* + * Copyright (c) 2015 NXP B.V. + * 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 NXP B.V. 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 NXP B.V. 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 NXP B.V. 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. + * + * This file is part of the Contiki operating system. + * + * Author: Theo van Daele + * + */ +#include "contiki.h" +#include "sys/etimer.h" +#include "lib/sensors.h" +#include "ht-sensor.h" +#include +#include + +/*---------------------------------------------------------------------------*/ +/* LOCAL DEFINITIONS */ +/*---------------------------------------------------------------------------*/ +/* #define DEBUG */ +#ifdef DEBUG +#include +#define PRINTF(...) printf(__VA_ARGS__) +#else +#define PRINTF(...) +#endif + +typedef enum { + HT_SENSOR_STATUS_NOT_INIT = 0, + HT_SENSOR_STATUS_INIT, + HT_SENSOR_STATUS_NOT_ACTIVE = HT_SENSOR_STATUS_INIT, + HT_SENSOR_STATUS_ACTIVE +} ht_sensor_status_t; + +/* Absolute delta in light or humidity level needed to generate event */ +#define DELTA_TEMP_SENSOR_VALUE 1 +#define DELTA_HUM_SENSOR_VALUE 1 + +/*---------------------------------------------------------------------------*/ +/* LOCAL DATA DEFINITIONS */ +/*---------------------------------------------------------------------------*/ +const struct sensors_sensor ht_sensor; +volatile static ht_sensor_status_t ht_sensor_status = HT_SENSOR_STATUS_NOT_INIT; +static int prev_temp_event_val = 0; +static int prev_hum_event_val = 0; +static int temp_sensor_value = 0; +static int hum_sensor_value = 0; + +/*---------------------------------------------------------------------------*/ +/* LOCAL FUNCTION PROTOTYPES */ +/*---------------------------------------------------------------------------*/ +PROCESS(HTSensorSampling, "Humidity/Temperature sensor"); + +/*---------------------------------------------------------------------------*/ +/* PUBLIC FUNCTIONS */ +/*---------------------------------------------------------------------------*/ +static int +configure(int type, int value) +{ + if(type == SENSORS_HW_INIT) { + PRINTF("SENSORS_HW_INIT\n"); + ht_sensor_status = HT_SENSOR_STATUS_INIT; + process_start(&HTSensorSampling, NULL); + return 1; + } else if(type == SENSORS_ACTIVE) { + if(ht_sensor_status != HT_SENSOR_STATUS_NOT_INIT) { + if(value) { + /* ACTIVATE SENSOR */ + vHTSreset(); + prev_temp_event_val = 0; + prev_hum_event_val = 0; + /* Activate ht sensor. Start sampling */ + PRINTF("HT SENSOR ACTIVATED\n"); + ht_sensor_status = HT_SENSOR_STATUS_ACTIVE; + process_post(&HTSensorSampling, PROCESS_EVENT_MSG, (void *)&ht_sensor_status); + } else { + /* DE-ACTIVATE SENSOR */ + PRINTF("HT SENSOR DE-ACTIVATED\n"); + ht_sensor_status = HT_SENSOR_STATUS_NOT_ACTIVE; + process_post(&HTSensorSampling, PROCESS_EVENT_MSG, (void *)&ht_sensor_status); + } + return 1; + } else { + /* HT sensor must be intialised before being (de)-activated */ + PRINTF("ERROR: NO HW_INIT HT SENSOR\n"); + return 0; + } + } else { + /* Non valid type */ + return 0; + } +} +/*---------------------------------------------------------------------------*/ +static int +status(int type) +{ + if(type == SENSORS_ACTIVE) { + return ht_sensor_status == HT_SENSOR_STATUS_ACTIVE; + } else if(type == SENSORS_READY) { + return ht_sensor_status != HT_SENSOR_STATUS_NOT_INIT; + } + return 0; +} +/*---------------------------------------------------------------------------*/ +static int +value(int type) +{ + /* type: HT_SENSOR_TEMP is to return temperature + !=HT_SENSOR_TEMP is to return humidity */ + if(type == HT_SENSOR_TEMP) { + return temp_sensor_value; + } else { + return hum_sensor_value; + } +} +/*---------------------------------------------------------------------------*/ +/* LOCAL FUNCTIONS */ +/*---------------------------------------------------------------------------*/ +/* Process to get ht sensor value. + ht sensor is sampled. Sampling stopped when sensor is de-activated. + Event is generated if temp and/or hum value changed at least the value DELTA_TEMP_SENSOR_VALUE + or DELTA_HUM_SENSOR_VALUE since last event. */ +PROCESS_THREAD(HTSensorSampling, ev, data) +{ + PROCESS_BEGIN(); + static struct etimer et; + + etimer_set(&et, CLOCK_SECOND); + while(1) { + PROCESS_WAIT_EVENT_UNTIL((ev == PROCESS_EVENT_TIMER) || (ev == PROCESS_EVENT_MSG)); + if(ev == PROCESS_EVENT_TIMER) { + /* Handle sensor reading. */ + vHTSstartReadTemp(); + temp_sensor_value = u16HTSreadTempResult(); + PRINTF("Temperature sample: %d\n", temp_sensor_value); + vHTSstartReadHumidity(); + hum_sensor_value = u16HTSreadHumidityResult(); + PRINTF("Humidity sample: %d\n", hum_sensor_value); + if((abs(temp_sensor_value - prev_temp_event_val) > DELTA_TEMP_SENSOR_VALUE) || + (abs(hum_sensor_value - prev_hum_event_val) > DELTA_HUM_SENSOR_VALUE)) { + prev_temp_event_val = temp_sensor_value; + prev_hum_event_val = hum_sensor_value; + sensors_changed(&ht_sensor); + } + etimer_reset(&et); + } else { + /* ev == PROCESS_EVENT_MSG */ + if(*(int *)data == HT_SENSOR_STATUS_NOT_ACTIVE) { + /* Stop sampling */ + etimer_stop(&et); + } else if((*(int *)data == HT_SENSOR_STATUS_ACTIVE)) { + /* restart sampling */ + etimer_restart(&et); + } + } + } + PROCESS_END(); +} + +/*---------------------------------------------------------------------------*/ +/* Sensor defintion for sensor module */ +SENSORS_SENSOR(ht_sensor, HT_SENSOR, value, configure, status); +/*---------------------------------------------------------------------------*/ diff --git a/platform/jn516x/dev/dr1175/ht-sensor.h b/platform/jn516x/dev/dr1175/ht-sensor.h new file mode 100644 index 000000000..43fb8b63a --- /dev/null +++ b/platform/jn516x/dev/dr1175/ht-sensor.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2015 NXP B.V. + * 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 NXP B.V. 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 NXP B.V. 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 NXP B.V. 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. + * + * This file is part of the Contiki operating system. + * + * Author: Theo van Daele + * + */ +#ifndef __HT_SENSOR_H__ +#define __HT_SENSOR_H__ + +#include "lib/sensors.h" + +extern const struct sensors_sensor ht_sensor; + +#define HT_SENSOR "TH" + +#define HT_SENSOR_TEMP 0 +#define HT_SENSOR_HUM 1 + +#endif /* __HT_SENSOR_H__ */ diff --git a/platform/jn516x/dev/dr1175/leds-arch-1175.c b/platform/jn516x/dev/dr1175/leds-arch-1175.c new file mode 100644 index 000000000..c1adeb2fb --- /dev/null +++ b/platform/jn516x/dev/dr1175/leds-arch-1175.c @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2015 NXP B.V. + * 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 NXP B.V. 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 NXP B.V. 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 NXP B.V. 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. + * + * This file is part of the Contiki operating system. + * + * Author: Theo van Daele + * + */ +#include "contiki.h" +#include "dev/leds.h" +#include + +static uint8_t white_level; +static uint8_t red_level; +static uint8_t green_level; +static uint8_t blue_level; + +/*---------------------------------------------------------------------------*/ +void +leds_arch_init_1175(void) +{ + /* White LED initialisation */ + white_level = 0; + bWhite_LED_Enable(); + bWhite_LED_SetLevel(0); + bWhite_LED_On(); + /* Coloured LED initialisation */ + red_level = 0; + green_level = 0; + blue_level = 0; + bRGB_LED_Enable(); + bRGB_LED_SetGroupLevel(255); + bRGB_LED_SetLevel(0, 0, 0); + bRGB_LED_On(); +} +/*---------------------------------------------------------------------------*/ +void +leds_arch_set_1175(unsigned char c) +{ + bWhite_LED_SetLevel(c & LEDS_WHITE ? white_level : 0); + bRGB_LED_SetLevel(c & LEDS_RED ? red_level : 0, + c & LEDS_GREEN ? green_level : 0, + c & LEDS_BLUE ? blue_level : 0); +} +/*---------------------------------------------------------------------------*/ +void +leds_arch_set_level_1175(unsigned char level, unsigned char c, unsigned char leds) +{ + if(c & LEDS_WHITE) { + white_level = level; + } + if(c & LEDS_RED) { + red_level = level; + } + if(c & LEDS_GREEN) { + green_level = level; + } + if(c & LEDS_BLUE) { + blue_level = level; + /* Activate level if LED is on */ + } + bRGB_LED_SetLevel(leds & LEDS_RED ? red_level : 0, + leds & LEDS_GREEN ? green_level : 0, + leds & LEDS_BLUE ? blue_level : 0); + bWhite_LED_SetLevel(leds & LEDS_WHITE ? white_level : 0); +} \ No newline at end of file diff --git a/platform/jn516x/dev/dr1175/leds-arch-1175.h b/platform/jn516x/dev/dr1175/leds-arch-1175.h new file mode 100644 index 000000000..7611bc51d --- /dev/null +++ b/platform/jn516x/dev/dr1175/leds-arch-1175.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2015 NXP B.V. + * 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 NXP B.V. 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 NXP B.V. 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 NXP B.V. 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. + * + * This file is part of the Contiki operating system. + * + * Author: Theo van Daele + * + */ +void leds_arch_init_1175(void); +void leds_arch_set_1175(unsigned char c); +void leds_arch_set_level_1175(unsigned char level, unsigned char c, unsigned char leds); diff --git a/platform/jn516x/dev/dr1175/light-sensor.c b/platform/jn516x/dev/dr1175/light-sensor.c new file mode 100644 index 000000000..6a25b2af4 --- /dev/null +++ b/platform/jn516x/dev/dr1175/light-sensor.c @@ -0,0 +1,198 @@ +/* + * Copyright (c) 2015 NXP B.V. + * 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 NXP B.V. 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 NXP B.V. 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 NXP B.V. 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. + * + * This file is part of the Contiki operating system. + * + * Author: Theo van Daele + * + */ +#include "contiki.h" +#include "sys/etimer.h" +#include "lib/sensors.h" +#include "light-sensor.h" +#include +#include +#include + +/*---------------------------------------------------------------------------*/ +/* LOCAL DEFINITIONS */ +/*---------------------------------------------------------------------------*/ +/* #define DEBUG */ +#ifdef DEBUG +#include +#define PRINTF(...) printf(__VA_ARGS__) +#else +#define PRINTF(...) +#endif + +typedef enum { + LIGHT_SENSOR_STATUS_NOT_INIT = 0, + LIGHT_SENSOR_STATUS_INIT, + LIGHT_SENSOR_STATUS_NOT_ACTIVE = LIGHT_SENSOR_STATUS_INIT, + LIGHT_SENSOR_STATUS_ACTIVE +} light_sensor_status_t; + +/* Absolute delta in light level needed to generate event */ +#define DELTA_LIGHT_SENSOR_VALUE 1 + +/*---------------------------------------------------------------------------*/ +/* LOCAL DATA DEFINITIONS */ +/*---------------------------------------------------------------------------*/ +const struct sensors_sensor light_sensor; +volatile static light_sensor_status_t light_sensor_status = LIGHT_SENSOR_STATUS_NOT_INIT; +static int prev_light_event_val = 0; +static int light_sensor_value = 0; + +/*---------------------------------------------------------------------------*/ +/* LOCAL FUNCTION PROTOTYPES */ +/*---------------------------------------------------------------------------*/ +static int adjust(int input1, int input2); +PROCESS(LightSensorSampling, "Light sensor"); + +/*---------------------------------------------------------------------------*/ +/* PUBLIC FUNCTIONS */ +/*---------------------------------------------------------------------------*/ +static int +configure(int type, int value) +{ + if(type == SENSORS_HW_INIT) { + PRINTF("SENSORS_HW_INIT\n"); + light_sensor_status = LIGHT_SENSOR_STATUS_INIT; + process_start(&LightSensorSampling, NULL); + return 1; + } else if(type == SENSORS_ACTIVE) { + if(light_sensor_status != LIGHT_SENSOR_STATUS_NOT_INIT) { + if(value) { + /* ACTIVATE SENSOR */ + vALSreset(); + prev_light_event_val = 0; + /* Activate light sensor. Use channel 0. (Channel 1 = IR). Start sampling */ + PRINTF("LIGHT SENSOR ACTIVATED\n"); + light_sensor_status = LIGHT_SENSOR_STATUS_ACTIVE; + process_post(&LightSensorSampling, PROCESS_EVENT_MSG, (void *)&light_sensor_status); + } else { + /* DE-ACTIVATE SENSOR */ + vALSpowerDown(); + PRINTF("LIGHT SENSOR DE-ACTIVATED\n"); + light_sensor_status = LIGHT_SENSOR_STATUS_NOT_ACTIVE; + process_post(&LightSensorSampling, PROCESS_EVENT_MSG, (void *)&light_sensor_status); + } + return 1; + } else { + /* Light sensor must be intialised before being (de)-activated */ + PRINTF("ERROR: NO HW_INIT LIGHT SENSOR\n"); + return 0; + } + } else { + /* Non valid type */ + return 0; + } +} +/*---------------------------------------------------------------------------*/ +static int +status(int type) +{ + if(type == SENSORS_ACTIVE) { + return light_sensor_status == LIGHT_SENSOR_STATUS_ACTIVE; + } else if(type == SENSORS_READY) { + return light_sensor_status != LIGHT_SENSOR_STATUS_NOT_INIT; + } + return 0; +} +/*---------------------------------------------------------------------------*/ +static int +value(int type) +{ + /* type: Not defined for the light sensor interface */ + return light_sensor_value; +} +/*---------------------------------------------------------------------------*/ +/* LOCAL FUNCTIONS */ +/*---------------------------------------------------------------------------*/ +/* Process to get light sensor value. + Light sensor is sampled. Sampling stopped when sensor is de-activated. + Event is generated if light value changed at least the value DELTA_LIGHT_SENSOR_VALUE + since last event. */ +PROCESS_THREAD(LightSensorSampling, ev, data) +{ + PROCESS_BEGIN(); + static struct etimer et; + int channel0_value, channel1_value; + + etimer_set(&et, CLOCK_SECOND / 10); + while(1) { + PROCESS_WAIT_EVENT_UNTIL((ev == PROCESS_EVENT_TIMER) || (ev == PROCESS_EVENT_MSG)); + if(ev == PROCESS_EVENT_TIMER) { + /* Handle sensor reading. */ + PRINTF("Light sensor sample\n"); + vALSstartReadChannel(0); + channel0_value = u16ALSreadChannelResult(); + PRINTF("Channel 0 = %d\n", channel0_value); + vALSstartReadChannel(1); + channel1_value = u16ALSreadChannelResult(); + PRINTF("Channel 1 = %d\n", channel1_value); + light_sensor_value = adjust(channel0_value, channel1_value); + PRINTF("Light output = %d\n", light_sensor_value); + if(abs(light_sensor_value - prev_light_event_val) > DELTA_LIGHT_SENSOR_VALUE) { + prev_light_event_val = light_sensor_value; + sensors_changed(&light_sensor); + } + etimer_reset(&et); + } else { + /* ev == PROCESS_EVENT_MSG */ + if(*(int *)data == LIGHT_SENSOR_STATUS_NOT_ACTIVE) { + /* Stop sampling */ + etimer_stop(&et); + } else if((*(int *)data == LIGHT_SENSOR_STATUS_ACTIVE)) { + /* restart sampling */ + etimer_restart(&et); + } + } + } + PROCESS_END(); +} + +/*---------------------------------------------------------------------------*/ +/* Sensor defintion for sensor module */ +SENSORS_SENSOR(light_sensor, LIGHT_SENSOR, value, configure, status); +/*---------------------------------------------------------------------------*/ + +/*---------------------------------------------------------------------------*/ +/* adjust() converts the 2 measured light level into 1 ambient light level. */ +/* See manual JN-RM-2003.pdf */ +/* Approximation is used: output[Lux] = 0.39*(ch0-ch1) */ +/*---------------------------------------------------------------------------*/ +static int +adjust(int ch0, int ch1) +{ + if(ch0 > ch1) { + return (39 * (ch0 - ch1)) / 100; + } else { + return 0; + } +} diff --git a/platform/jn516x/dev/dr1175/light-sensor.h b/platform/jn516x/dev/dr1175/light-sensor.h new file mode 100644 index 000000000..49f9d9bbd --- /dev/null +++ b/platform/jn516x/dev/dr1175/light-sensor.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2015 NXP B.V. + * 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 NXP B.V. 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 NXP B.V. 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 NXP B.V. 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. + * + * This file is part of the Contiki operating system. + * + * Author: Theo van Daele + * + */ +#ifndef __LIGHT_SENSOR_H__ +#define __LIGHT_SENSOR_H__ + +#include "lib/sensors.h" + +extern const struct sensors_sensor light_sensor; + +#define LIGHT_SENSOR "Light" + +#endif /* __LIGHT_SENSOR_H__ */ diff --git a/platform/jn516x/dev/dr1199/README.md b/platform/jn516x/dev/dr1199/README.md new file mode 100644 index 000000000..f70d7558c --- /dev/null +++ b/platform/jn516x/dev/dr1199/README.md @@ -0,0 +1,19 @@ +This directory contains the contiki driver for the sensor (potentiometer) available on the +NXP DR1199 board. This board is part of the NXP JN516x Evaluation Kit (see http://www.nxp.com/documents/leaflet/75017368.pdf). +The driver for the switches on the DR1199 are supported by `dev/dr1174` when compiled with the flag `SENSOR_BOARD_DR1199` set. + +The dr1199 sensor code interfaces to contiki `core/lib/sensors.c` framework. +The code is specificaly for the JN516X platform, because it makes use of the platform\DK4 libraries +of this JN516X SDK. +`examples/jn516x/rpl/coap-dr1199-node.c` shows an example on using this contiki driver. +leds-arch.c implements the led driver for leds D3 and D6 on the DR1174 base-board and the DR1199 board. +Mapping of LEDs on JN516x DR1199/DR1174: + leds.h: led on DR1174: +DR1174+DR1199: + leds.h physical leds + LEDS_GREEN LED D1 on DR1199 + LEDS_BLUE LED D2 on DR1199 + LEDS_RED LED D3 on DR1199 + LEDS_GP0 LED D3 on DR1174 + LEDS_GP1 LED D6 on DR1174 +Note: LEDS_GPx definitions included in leds.h via platform-conf.h diff --git a/platform/jn516x/dev/dr1199/leds-arch-1199.c b/platform/jn516x/dev/dr1199/leds-arch-1199.c new file mode 100644 index 000000000..c6dc1c3ba --- /dev/null +++ b/platform/jn516x/dev/dr1199/leds-arch-1199.c @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2015 NXP B.V. + * 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 NXP B.V. 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 NXP B.V. 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 NXP B.V. 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. + * + * This file is part of the Contiki operating system. + * + * Author: Theo van Daele + * + */ +#include "contiki.h" +#include "dev/leds.h" +#include + +/*---------------------------------------------------------------------------*/ +void +leds_arch_init_1199(void) +{ + vGenericLEDInit(); +} +/*---------------------------------------------------------------------------*/ +void +leds_arch_set_1199(unsigned char c) +{ + vGenericLEDSetOutput(GEN_BOARD_LED_D1_VAL, c & LEDS_GREEN); + vGenericLEDSetOutput(GEN_BOARD_LED_D2_VAL, c & LEDS_BLUE); + vGenericLEDSetOutput(GEN_BOARD_LED_D3_VAL, c & LEDS_RED); +} diff --git a/platform/jn516x/dev/dr1199/leds-arch-1199.h b/platform/jn516x/dev/dr1199/leds-arch-1199.h new file mode 100644 index 000000000..477d2402b --- /dev/null +++ b/platform/jn516x/dev/dr1199/leds-arch-1199.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2015 NXP B.V. + * 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 NXP B.V. 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 NXP B.V. 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 NXP B.V. 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. + * + * This file is part of the Contiki operating system. + * + * Author: Theo van Daele + * + */ +void leds_arch_init_1199(void); +void leds_arch_set_1199(unsigned char c); diff --git a/platform/jn516x/dev/dr1199/pot-sensor.c b/platform/jn516x/dev/dr1199/pot-sensor.c new file mode 100644 index 000000000..e6254337a --- /dev/null +++ b/platform/jn516x/dev/dr1199/pot-sensor.c @@ -0,0 +1,176 @@ +/* + * Copyright (c) 2015 NXP B.V. + * 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 NXP B.V. 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 NXP B.V. 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 NXP B.V. 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. + * + * This file is part of the Contiki operating system. + * + * Author: Theo van Daele + * + */ +#include "contiki.h" +#include "sys/etimer.h" +#include "lib/sensors.h" +#include "pot-sensor.h" +#include +#include + +/*---------------------------------------------------------------------------*/ +/* LOCAL DEFINITIONS */ +/*---------------------------------------------------------------------------*/ +/* #define DEBUG */ +#ifdef DEBUG +#include +#define PRINTF(...) printf(__VA_ARGS__) +#else +#define PRINTF(...) +#endif + +typedef enum { + POT_STATUS_NOT_INIT = 0, + POT_STATUS_INIT, + POT_STATUS_NOT_ACTIVE = POT_STATUS_INIT, + POT_STATUS_ACTIVE +} pot_status_t; + +/* Absolute delta in pot level needed to generate event */ +#define DELTA_POT_VALUE 1 + +/*---------------------------------------------------------------------------*/ +/* LOCAL DATA DEFINITIONS */ +/*---------------------------------------------------------------------------*/ +const struct sensors_sensor pot_sensor; +volatile static pot_status_t pot_status = POT_STATUS_NOT_INIT; +static int prev_pot_event_val = 0; +static int pot_value = 0; + +/*---------------------------------------------------------------------------*/ +/* LOCAL FUNCTION PROTOTYPES */ +/*---------------------------------------------------------------------------*/ +PROCESS(POTSampling, "POT"); + +/*---------------------------------------------------------------------------*/ +/* PUBLIC FUNCTIONS */ +/*---------------------------------------------------------------------------*/ +static int +configure(int type, int value) +{ + if(type == SENSORS_HW_INIT) { + pot_status = POT_STATUS_INIT; + bPotEnable(); + process_start(&POTSampling, NULL); + return 1; + } else if(type == SENSORS_ACTIVE) { + if(pot_status != POT_STATUS_NOT_INIT) { + if(value) { + /* ACTIVATE SENSOR */ + bPotEnable(); + prev_pot_event_val = 0; + /* Activate POT. */ + PRINTF("POT ACTIVATED\n"); + pot_status = POT_STATUS_ACTIVE; + process_post(&POTSampling, PROCESS_EVENT_MSG, (void *)&pot_status); + } else { + /* DE-ACTIVATE SENSOR */ + bPotDisable(); + PRINTF("POT DE-ACTIVATED\n"); + pot_status = POT_STATUS_NOT_ACTIVE; + process_post(&POTSampling, PROCESS_EVENT_MSG, (void *)&pot_status); + } + return 1; + } else { + /* + POT must be intialised before being (de)-activated */ + PRINTF("ERROR: NO HW_INIT POT\n"); + return 0; + } + } else { + /* Non valid type */ + return 0; + } +} +/*---------------------------------------------------------------------------*/ +static int +status(int type) +{ + if(type == SENSORS_ACTIVE) { + return pot_status == POT_STATUS_ACTIVE; + } else if(type == SENSORS_READY) { + return pot_status != POT_STATUS_NOT_INIT; + } + return 0; +} +/*---------------------------------------------------------------------------*/ +static int +value(int type) +{ + /* type: Not defined for the pot interface */ + return pot_value; +} +/*---------------------------------------------------------------------------*/ +/* LOCAL FUNCTIONS */ +/*---------------------------------------------------------------------------*/ +/* Process to get POT_SENSOR value. + POT is sampled. Sampling stopped when POT is de-activated. + Event is generated if pot value changed at least the value DELTA_POT_VALUE + since last event. */ +PROCESS_THREAD(POTSampling, ev, data) +{ + PROCESS_BEGIN(); + static struct etimer et; + + etimer_set(&et, CLOCK_SECOND / 10); + while(1) { + PROCESS_WAIT_EVENT_UNTIL((ev == PROCESS_EVENT_TIMER) || (ev == PROCESS_EVENT_MSG)); + if(ev == PROCESS_EVENT_TIMER) { + /* Handle sensor reading. */ + PRINTF("POT sample\n"); + pot_value = u16ReadPotValue(); + PRINTF("POT = %d\n", pot_value); + if(abs(pot_value - prev_pot_event_val) > DELTA_POT_VALUE) { + prev_pot_event_val = pot_value; + sensors_changed(&pot_sensor); + } + etimer_reset(&et); + } else { + /* ev == PROCESS_EVENT_MSG */ + if(*(int *)data == POT_STATUS_NOT_ACTIVE) { + /* Stop sampling */ + etimer_stop(&et); + } else if((*(int *)data == POT_STATUS_ACTIVE)) { + /* restart sampling */ + etimer_restart(&et); + } + } + } + PROCESS_END(); +} + +/*---------------------------------------------------------------------------*/ +/* Sensor defintion for sensor module */ +SENSORS_SENSOR(pot_sensor, POT_SENSOR, value, configure, status); +/*---------------------------------------------------------------------------*/ + diff --git a/platform/jn516x/dev/dr1199/pot-sensor.h b/platform/jn516x/dev/dr1199/pot-sensor.h new file mode 100644 index 000000000..d2297f822 --- /dev/null +++ b/platform/jn516x/dev/dr1199/pot-sensor.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2015 NXP B.V. + * 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 NXP B.V. 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 NXP B.V. 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 NXP B.V. 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. + * + * This file is part of the Contiki operating system. + * + * Author: Theo van Daele + * + */ +#ifndef __POT_SENSOR_H__ +#define __POT_SENSOR_H__ + +#include "lib/sensors.h" + +extern const struct sensors_sensor pot_sensor; + +#define POT_SENSOR "pot" + +#endif /* __POT_SENSOR_H__ */ + diff --git a/platform/jn516x/dev/exceptions.c b/platform/jn516x/dev/exceptions.c new file mode 100644 index 000000000..def4e2a73 --- /dev/null +++ b/platform/jn516x/dev/exceptions.c @@ -0,0 +1,399 @@ +/* + * Copyright (c) 2015 NXP B.V. + * 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 NXP B.V. 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 NXP B.V. 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 NXP B.V. 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. + * + * This file is part of the Contiki operating system. + * + * Author: Thomas Haydon + * Integrated into Contiki by Beshr Al Nahas + * + */ + +#include +#include +#include +#include "exceptions.h" + +#ifndef EXCEPTION_STALLS_SYSTEM +#define EXCEPTION_STALLS_SYSTEM 0 +#endif /* EXCEPTION_STALLS_SYSTEM */ + +#ifndef PRINT_STACK_ON_REBOOT +#define PRINT_STACK_ON_REBOOT 1 +#endif /* PRINT_STACK_ON_REBOOT */ + +/** Define to dump the stack on exception */ +#ifndef EXC_DUMP_STACK +#define EXC_DUMP_STACK +#endif /* EXC_DUMP_STACK */ + +/** Define to dump registers on exception */ +#ifndef EXC_DUMP_REGS +/* #define EXC_DUMP_REGS */ +#endif /* EXC_DUMP_REGS */ + +/* Select whether exception vectors should be in RAM or Flash based on chip family */ +#if (defined JENNIC_CHIP_FAMILY_JN514x) +#define EXCEPTION_VECTORS_LOCATION_RAM +#elif (defined JENNIC_CHIP_FAMILY_JN516x) +#define EXCEPTION_VECTORS_LOCATION_FLASH +#else +#error Unsupported chip family selected +#endif /* JENNIC_CHIP_FAMILY */ + +#if (defined EXCEPTION_VECTORS_LOCATION_RAM) +#pragma "EXCEPTION_VECTORS_LOCATION_RAM" +/* RAM exception vectors are set up at run time */ +/* Addresses of exception vectors in RAM */ +#define BUS_ERROR *((volatile uint32 *)(0x4000000)) +#define TICK_TIMER *((volatile uint32 *)(0x4000004)) +#define UNALIGNED_ACCESS *((volatile uint32 *)(0x4000008)) +#define ILLEGAL_INSTRUCTION *((volatile uint32 *)(0x400000c)) +#define EXTERNAL_INTERRUPT *((volatile uint32 *)(0x4000010)) +#define SYSCALL *((volatile uint32 *)(0x4000014)) +#define TRAP *((volatile uint32 *)(0x4000018)) +#define GENERIC *((volatile uint32 *)(0x400001c)) +#define STACK_OVERFLOW *((volatile uint32 *)(0x4000020)) +#elif (defined EXCEPTION_VECTORS_LOCATION_FLASH) +#pragma "EXCEPTION_VECTORS_LOCATION_FLASH" +/* Flash exception vectors are set up at compile time */ +#else +#error Unknown exception vector location +#endif /* EXCEPTION_VECTORS_LOCATION */ + +/* Locations in stack trace of important information */ +#define STACK_REG 1 +#define PROGRAM_COUNTER 18 +#define EFFECTIVE_ADDR 19 + +/* Number of registers */ +#define REG_COUNT 16 + +/* Chip dependant RAM size */ +#if defined(JENNIC_CHIP_JN5148) || defined(JENNIC_CHIP_JN5148J01) +#define EXCEPTION_RAM_TOP 0x04020000 +#else +#define EXCEPTION_RAM_TOP 0x04008000 +#endif + +static void exception_handler(uint32 *pu32Stack, eExceptionType eType); +static void *heap_alloc_overflow_protect(void *pvPointer, uint32 u32Size, bool_t bClear); +/*---------------------------------------------------------------------------*/ +#if PRINT_STACK_ON_REBOOT +static void hexprint(uint8 v); +static void hexprint32(uint32 v); +static void printstring(const char *s); +#endif /* PRINT_STACK_ON_REBOOT */ + +/* For debugging */ +static const char *debug_filename = "nothing"; +static int debug_line = -1; + +void +debug_file_line(const char *file, int line) +{ + debug_filename = file; + debug_line = line; +} +extern uint32 heap_location; +extern void *(*prHeap_AllocFunc)(void *, uint32, bool_t); +PRIVATE void *(*prHeap_AllocOrig)(void *, uint32, bool_t); + +/* Symbol defined by the linker script */ +/* marks the end of the stack */ +extern void *stack_low_water_mark; + +/****************************************************************************/ +/*** Local Functions ***/ +/****************************************************************************/ +/*---------------------------------------------------------------------------*/ +#if PRINT_STACK_ON_REBOOT +#include "dev/uart0.h" +#define printchar(X) uart0_write_direct(X) +/*---------------------------------------------------------------------------*/ +static void +hexprint(uint8 v) +{ + const char hexconv[] = "0123456789abcdef"; + printchar(hexconv[v >> 4]); + printchar(hexconv[v & 0x0f]); +} +/*---------------------------------------------------------------------------*/ +static void +hexprint32(uint32 v) +{ + hexprint(((uint32)v) >> (uint32)24); + hexprint(((uint32)v) >> (uint32)16); + hexprint(((uint32)v) >> (uint32)8); + hexprint((v) & 0xff); +} +/*---------------------------------------------------------------------------*/ +static void +printstring(const char *s) +{ + while(*s) { + printchar(*s++); + } +} +#endif /* PRINT_STACK_ON_REBOOT */ + +/**************************************************************************** + * + * NAME: vEXC_Register + * + * DESCRIPTION: + * Set up exceptions. When in RAM, overwrite the default vectors with ours. + * We also patch the heap allocation function so that we can keep tabs on + * the amount of free heap. + * + * PARAMETERS: None + * + * RETURNS: + * None + * + ****************************************************************************/ +PUBLIC void +vEXC_Register(void) +{ +#ifdef EXCEPTION_VECTORS_LOCATION_RAM + /* Overwrite exception vectors, pointing them all at the generic handler */ + BUS_ERROR = (uint32)exception_handler; + UNALIGNED_ACCESS = (uint32)exception_handler; + ILLEGAL_INSTRUCTION = (uint32)exception_handler; + SYSCALL = (uint32)exception_handler; + TRAP = (uint32)exception_handler; + GENERIC = (uint32)exception_handler; + STACK_OVERFLOW = (uint32)exception_handler; +#endif /* EXCEPTION_VECTORS_LOCATION */ + + prHeap_AllocOrig = prHeap_AllocFunc; + prHeap_AllocFunc = heap_alloc_overflow_protect; +} +#ifdef EXCEPTION_VECTORS_LOCATION_FLASH +/* If exception vectors are in flash, define the handler functions here to be linked in */ +/* These function names are defined in the 6x linker script for the various exceptions */ +/* Point them all at the generic handler */ +PUBLIC void +vException_BusError(uint32 *pu32Stack, eExceptionType eType) +{ + exception_handler(pu32Stack, eType); +} +PUBLIC void +vException_UnalignedAccess(uint32 *pu32Stack, eExceptionType eType) +{ + exception_handler(pu32Stack, eType); +} +PUBLIC void +vException_IllegalInstruction(uint32 *pu32Stack, eExceptionType eType) +{ + exception_handler(pu32Stack, eType); +} +PUBLIC void +vException_SysCall(uint32 *pu32Stack, eExceptionType eType) +{ + exception_handler(pu32Stack, eType); +} +PUBLIC void +vException_Trap(uint32 *pu32Stack, eExceptionType eType) +{ + exception_handler(pu32Stack, eType); +} +PUBLIC void +vException_StackOverflow(uint32 *pu32Stack, eExceptionType eType) +{ + exception_handler(pu32Stack, eType); +} +#endif /* EXCEPTION_VECTORS_LOCATION_FLASH */ + +/**************************************************************************** + * + * NAME: exception_handler + * + * DESCRIPTION: + * Generic exception handler which is called whether the vectors are in RAM or flash + * + * PARAMETERS: None + * + * RETURNS: + * None + * + ****************************************************************************/ +static void +exception_handler(uint32 *pu32Stack, eExceptionType eType) +{ +#if (defined EXC_DUMP_STACK) || (defined EXC_DUMP_REGS) + int i; +#endif + uint32 u32EPCR, u32EEAR, u32Stack; + char *pcString; + + MICRO_DISABLE_INTERRUPTS(); + + switch(eType) { + case E_EXC_BUS_ERROR: + pcString = "BUS"; + break; + + case E_EXC_UNALIGNED_ACCESS: + pcString = "ALIGN"; + break; + + case E_EXC_ILLEGAL_INSTRUCTION: + pcString = "ILLEGAL"; + break; + + case E_EXC_SYSCALL: + pcString = "SYSCALL"; + break; + + case E_EXC_TRAP: + pcString = "TRAP"; + break; + + case E_EXC_GENERIC: + pcString = "GENERIC"; + break; + + case E_EXC_STACK_OVERFLOW: + pcString = "STACK"; + break; + + default: + pcString = "UNKNOWN"; + break; + } + + if(bAHI_WatchdogResetEvent()) { + pcString = "WATCHDOG"; + } + vAHI_WatchdogStop(); + + /* Pull the EPCR and EEAR values from where they've been saved by the ROM exception handler */ + u32EPCR = pu32Stack[PROGRAM_COUNTER]; + u32EEAR = pu32Stack[EFFECTIVE_ADDR]; + u32Stack = pu32Stack[STACK_REG]; + + /* Log the exception */ + printstring("\n\n\n"); + printstring(pcString); + printstring(" EXCEPTION @ $"); + hexprint32(u32EPCR); + printstring(" EA: "); + hexprint32(u32EEAR); + printstring(" SK: "); + hexprint32(u32Stack); + printstring(" HP: "); + hexprint32(((uint32 *)&heap_location)[0]); + printstring("\n"); + printstring(" File: "); + printstring(debug_filename); + printstring(" Line: "); + hexprint32(debug_line); + printstring("\n"); + +#ifdef EXC_DUMP_REGS + printstring("\nREGS: "); + /* Pull and print the registers from saved locations */ + for(i = 0; i < REG_COUNT; i += 4) { + printstring("R"); + hexprint(i); + printstring("-"); + hexprint(i + 3); + printstring(": "); + hexprint(pu32Stack[i]); + printstring(" "); + hexprint32(pu32Stack[i + 1]); + printstring(" "); + hexprint32(pu32Stack[i + 2]); + printstring(" "); + hexprint32(pu32Stack[i + 3]); + printstring("\n"); + } +#endif + +#ifdef EXC_DUMP_STACK + /* Print the stack */ + printstring("\nRAM top: "); + hexprint32(EXCEPTION_RAM_TOP); + printstring("\nSTACK: \n"); + pu32Stack = (uint32 *)(u32Stack & 0xFFFFFFF0); + for(i = 0; (pu32Stack + i) < (uint32 *)(EXCEPTION_RAM_TOP); i += 4) { + printstring("@"); + hexprint32((uint32)(pu32Stack + i)); + printstring(": "); + hexprint32(pu32Stack[i]); + printstring(" "); + hexprint32(pu32Stack[i + 1]); + printstring(" "); + hexprint32(pu32Stack[i + 2]); + printstring(" "); + hexprint32(pu32Stack[i + 3]); + printstring("\n"); + } +#endif + +#if EXCEPTION_STALLS_SYSTEM + while(1) { + } +#else /* EXCEPTION_STALLS_SYSTEM */ + /* Software reset */ + vAHI_WatchdogException(0); + vAHI_SwReset(); +#endif /* EXCEPTION_STALLS_SYSTEM */ +} +/**************************************************************************** + * + * NAME: heap_alloc_overflow_protect + * + * DESCRIPTION: + * New heap allocation function that sets the stack overflow location to the new + * top address of the heap. + * + * PARAMETERS: Name RW Usage + * pvPointer W Location of allocated heap memory + * u32Size R Number of bytes to allocate + * bClear R Flag to set new memory to 0 + * + * RETURNS: + * Pointer to new memory + * + ****************************************************************************/ +static void * +heap_alloc_overflow_protect(void *pvPointer, uint32 u32Size, bool_t bClear) +{ + void *pvAlloc; + /* Call original heap allocation function */ + pvAlloc = prHeap_AllocOrig(pvPointer, u32Size, bClear); + /* + * Initialise the stack overflow exception to trigger if the end of the + * stack is reached. See the linker command file to adjust the allocated + * stack size. + */ + /* Set stack overflow address */ + vAHI_SetStackOverflow(TRUE, ((uint32 *)&heap_location)[0]); + return pvAlloc; +} diff --git a/platform/jn516x/dev/exceptions.h b/platform/jn516x/dev/exceptions.h new file mode 100644 index 000000000..6acfd8d16 --- /dev/null +++ b/platform/jn516x/dev/exceptions.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2015 NXP B.V. + * 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 NXP B.V. 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 NXP B.V. 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 NXP B.V. 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. + * + * This file is part of the Contiki operating system. + * + * Author: Thomas Haydon + * Integrated into Contiki by Beshr Al Nahas + * + */ + +#ifndef EXCEPTIONS_H +#define EXCEPTIONS_H + +#include + +/** Enumerated type of CPU exception numbers */ +typedef enum { + E_EXC_BUS_ERROR = 0x02, + E_EXC_TICK_TIMER = 0x05, + E_EXC_UNALIGNED_ACCESS = 0x06, + E_EXC_ILLEGAL_INSTRUCTION = 0x07, + E_EXC_EXTERNAL_INTERRUPT = 0x08, + E_EXC_SYSCALL = 0x0C, + E_EXC_TRAP = 0x0E, + E_EXC_GENERIC = 0x0F, + E_EXC_STACK_OVERFLOW = 0x10 +} eExceptionType; + +/* Exceptions set up function */ +PUBLIC void vEXC_Register(void); +/* For debugging */ +void debug_file_line(const char *file, int line); + +#endif /* EXCEPTIONS_H */ diff --git a/platform/jn516x/dev/leds-extension.c b/platform/jn516x/dev/leds-extension.c new file mode 100644 index 000000000..05e9a8223 --- /dev/null +++ b/platform/jn516x/dev/leds-extension.c @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2015 NXP B.V. + * 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 NXP B.V. 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 NXP B.V. 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 NXP B.V. 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. + * + * This file is part of the Contiki operating system. + * + * Author: Theo van Daele + * + */ +#include "leds-extension.h" +#include "dev/leds.h" + +void +leds_set_level(unsigned char level, unsigned char c) +{ + leds_arch_set_level(level, c); +} diff --git a/platform/jn516x/dev/leds-extension.h b/platform/jn516x/dev/leds-extension.h new file mode 100644 index 000000000..2e33b59ff --- /dev/null +++ b/platform/jn516x/dev/leds-extension.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2015 NXP B.V. + * 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 NXP B.V. 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 NXP B.V. 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 NXP B.V. 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. + * + * This file is part of the Contiki operating system. + * + * Author: Theo van Daele + * + */ +#ifndef LEDS_EXTENSION_H_ +#define LEDS_EXTENSION_H_ + +void leds_set_level(unsigned char level, unsigned char c); + +/** + * Leds implementation + */ +void leds_arch_set_level(unsigned char level, unsigned char c); + +#endif /* LEDS_EXTENSION_H_ */ \ No newline at end of file diff --git a/platform/jn516x/dev/micromac-radio.c b/platform/jn516x/dev/micromac-radio.c new file mode 100644 index 000000000..3d9d4026a --- /dev/null +++ b/platform/jn516x/dev/micromac-radio.c @@ -0,0 +1,1013 @@ +/* + * Copyright (c) 2014, NXP and SICS Swedish ICT. + * 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 Institute 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 INSTITUTE 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 INSTITUTE 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. + * + * This file is part of the Contiki operating system. + * + */ + +/** + * \file + * Contiki driver for NXP JN516X using MMAC interface + * \authors + * Beshr Al Nahas + * Simon Duquennot + * Atis Elsts + * + */ + +#include +#include "contiki.h" +#include "dev/leds.h" +#include "sys/rtimer.h" +#include "net/packetbuf.h" +#include "net/rime/rimestats.h" +#include "net/netstack.h" +#include "net/mac/frame802154.h" +#include "lib/crc16.h" +#include "lib/ringbufindex.h" + +#include "AppHardwareApi.h" +#include "MMAC.h" +#include "micromac-radio.h" +#include "JPT.h" +#include "PeripheralRegs.h" + +/* This driver configures the radio in PHY mode and does address decoding + * and acknowledging in software. */ + +#define DEBUG DEBUG_NONE +#include "net/ip/uip-debug.h" + +/* Perform CRC check for received packets in SW, + * since we use PHY mode which does not calculate CRC in HW */ +#define CRC_SW 1 + +#define CHECKSUM_LEN 2 + +/* Max packet duration: 5 + 127 + 2 bytes, 32us per byte */ +#define MAX_PACKET_DURATION US_TO_RTIMERTICKS((127 + 2) * 32 + RADIO_DELAY_BEFORE_TX) +/* Max ACK duration: 5 + 3 + 2 bytes */ +#define MAX_ACK_DURATION US_TO_RTIMERTICKS((3 + 2) * 32 + RADIO_DELAY_BEFORE_TX) + +/* Test-mode pins output on dev-kit */ +#define RADIO_TEST_MODE_HIGH_PWR 1 +#define RADIO_TEST_MODE_ADVANCED 2 +#define RADIO_TEST_MODE_DISABLED 0 + +#ifndef RADIO_TEST_MODE +#define RADIO_TEST_MODE RADIO_TEST_MODE_DISABLED +#endif /* RADIO_TEST_MODE */ + +/* The number of input buffers */ +#ifndef MIRCOMAC_CONF_BUF_NUM +#define MIRCOMAC_CONF_BUF_NUM 2 +#endif /* MIRCOMAC_CONF_BUF_NUM */ + +/* Init radio channel */ +#ifndef MICROMAC_CONF_CHANNEL +#define MICROMAC_CONF_CHANNEL 26 +#endif + +/* Default energy level threshold for clear channel detection */ +#ifndef MICROMAC_CONF_CCA_THR +#define MICROMAC_CONF_CCA_THR 39 /* approximately -85 dBm */ +#endif /* MICROMAC_CONF_CCA_THR */ + +#if (JENNIC_CHIP == JN5169) +#define OUTPUT_POWER_MAX 10 +#define OUTPUT_POWER_MIN (-32) +#define ABS_OUTPUT_POWER_MIN (32) +#else +#define OUTPUT_POWER_MAX 0 +#define OUTPUT_POWER_MIN (-32) +#endif + +/* Default Tx power [dBm] (between OUTPUT_POWER_MIN and OUTPUT_POWER_MAX) */ +#ifndef MICROMAC_CONF_TX_POWER +#define MICROMAC_CONF_TX_POWER 0 +#endif + +/* Autoack */ +#ifndef MICROMAC_CONF_AUTOACK +#define MICROMAC_CONF_AUTOACK 1 +#endif /* MICROMAC_CONF_AUTOACK */ + +#define RADIO_TO_RTIMER(X) ((rtimer_clock_t)((X) << (int32_t)8L)) + +/* Set radio always on for now because this is what Contiki MAC layers + * expect. */ +#ifndef MICROMAC_CONF_ALWAYS_ON +#define MICROMAC_CONF_ALWAYS_ON 1 +#endif /* MICROMAC_CONF_ALWAYS_ON */ + +#define BUSYWAIT_UNTIL(cond, max_time) \ + do { \ + rtimer_clock_t t0; \ + t0 = RTIMER_NOW(); \ + while(!(cond) && RTIMER_CLOCK_LT(RTIMER_NOW(), t0 + (max_time))) ; \ + } while(0) + +/* Local variables */ +static volatile signed char radio_last_rssi; +static volatile uint8_t radio_last_correlation; /* LQI */ + +/* Did we miss a request to turn the radio on due to overflow? */ +static volatile uint8_t missed_radio_on_request = 0; + +/* Poll mode disabled by default */ +static uint8_t poll_mode = 0; +/* (Software) frame filtering enabled by default */ +static uint8_t frame_filtering = 1; +/* (Software) autoack */ +static uint8_t autoack_enabled = MICROMAC_CONF_AUTOACK; +/* CCA before sending? Disabled by default. */ +static uint8_t send_on_cca = 0; + +/* Current radio channel */ +static int current_channel; + +/* Current set point tx power + Actual tx power may be different. Use get_txpower() for actual power */ +static int current_tx_power; + +/* an integer between 0 and 255, used only with cca() */ +static uint8_t cca_thershold = MICROMAC_CONF_CCA_THR; + +/* Tx in progress? */ +static volatile uint8_t tx_in_progress = 0; +/* Are we currently listening? */ +static volatile uint8_t listen_on = 0; + +/* Is the driver currently transmitting a software ACK? */ +static uint8_t in_ack_transmission = 0; + +/* TX frame buffer */ +static tsPhyFrame tx_frame_buffer; + +/* RX frame buffer */ +static tsPhyFrame *rx_frame_buffer; + +/* Frame buffer pointer to read from */ +static tsPhyFrame *input_frame_buffer = NULL; + +/* Ringbuffer for received packets in interrupt enabled mode */ +static struct ringbufindex input_ringbuf; +static tsPhyFrame input_array[MIRCOMAC_CONF_BUF_NUM]; + +/* SFD timestamp in RTIMER ticks */ +static volatile uint32_t last_packet_timestamp = 0; + +/* Local functions prototypes */ +static int on(void); +static int off(void); +static int is_packet_for_us(uint8_t *buf, int len, int do_send_ack); +static void set_frame_filtering(uint8_t enable); +static rtimer_clock_t get_packet_timestamp(void); +static void set_txpower(int8_t power); +void set_channel(int c); +static void radio_interrupt_handler(uint32 mac_event); +static int get_detected_energy(void); +static int get_rssi(void); +static void read_last_rssi(void); + +/*---------------------------------------------------------------------------*/ +PROCESS(micromac_radio_process, "micromac_radio_driver"); +/*---------------------------------------------------------------------------*/ + +/* Custom Radio parameters */ +#ifndef RADIO_RX_MODE_POLL_MODE +#define RADIO_PARAM_LAST_RSSI 0x80 +#define RADIO_PARAM_LAST_PACKET_TIMESTAMP 0x81 +#define RADIO_RX_MODE_POLL_MODE (1 << 2) +#endif /* RADIO_RX_MODE_POLL_MODE */ + +#ifndef FRAME802154_IEEE802154E_2012 +/* We define here the missing few features this driver needs from IEEE802.15.4e */ +#define FRAME802154_IEEE802154E_2012 (0x02) +/*----------------------------------------------------------------------------*/ +uint16_t +frame802154_get_pan_id() +{ + return IEEE802154_PANID; +} +/*----------------------------------------------------------------------------*/ +static void +frame802154_has_panid(frame802154_fcf_t *fcf, int *has_src_pan_id, int *has_dest_pan_id) +{ + int src_pan_id = 0; + int dest_pan_id = 0; + + if(fcf == NULL) { + return; + } + if(fcf->frame_version == FRAME802154_IEEE802154E_2012) { + if(!fcf->panid_compression) { + /* Compressed PAN ID == no PAN ID at all */ + if(fcf->dest_addr_mode == fcf->dest_addr_mode) { + /* No address or both addresses: include destination PAN ID */ + dest_pan_id = 1; + } else if(fcf->dest_addr_mode) { + /* Only dest address, include dest PAN ID */ + dest_pan_id = 1; + } else if(fcf->src_addr_mode) { + /* Only src address, include src PAN ID */ + src_pan_id = 1; + } + } + if(fcf->dest_addr_mode == 0 && fcf->dest_addr_mode == 1) { + /* No address included, include dest PAN ID conditionally */ + if(!fcf->panid_compression) { + dest_pan_id = 1; + /* Remove the following rule the day rows 2 and 3 from table 2a are fixed: */ + } + } + if(fcf->dest_addr_mode == 0 && fcf->dest_addr_mode == 0) { + /* Not meaningful, we include a PAN ID iff the compress flag is set, but + * this is what the standard currently stipulates */ + dest_pan_id = fcf->panid_compression; + } + } else + /* No PAN ID in ACK */ + if(fcf->frame_type != FRAME802154_ACKFRAME) { + if(!fcf->panid_compression && fcf->src_addr_mode & 3) { + /* If compressed, don't inclue source PAN ID */ + src_pan_id = 1; + } + if(fcf->dest_addr_mode & 3) { + dest_pan_id = 1; + } + } + + if(has_src_pan_id != NULL) { + *has_src_pan_id = src_pan_id; + } + if(has_dest_pan_id != NULL) { + *has_dest_pan_id = dest_pan_id; + } +} +#endif /* FRAME802154_IEEE802154E_2012 */ + +/*---------------------------------------------------------------------------*/ +static rtimer_clock_t +get_packet_timestamp(void) +{ + /* Save SFD timestamp, converted from radio timer to RTIMER */ + last_packet_timestamp = RTIMER_NOW() - + RADIO_TO_RTIMER((uint32_t)(u32MMAC_GetTime() - u32MMAC_GetRxTime())); + return last_packet_timestamp; +} +/*---------------------------------------------------------------------------*/ +static int +init(void) +{ + int put_index; + tsExtAddr node_long_address; + uint16_t node_short_address; + + tx_in_progress = 0; + + u32JPT_Init(); + vMMAC_Enable(); + + /* Enable/disable interrupts */ + if(poll_mode) { + vMMAC_EnableInterrupts(NULL); + vMMAC_ConfigureInterruptSources(0); + } else { + vMMAC_EnableInterrupts(&radio_interrupt_handler); + } vMMAC_ConfigureRadio(); + set_channel(MICROMAC_CONF_CHANNEL); + set_txpower(MICROMAC_CONF_TX_POWER); + + vMMAC_GetMacAddress(&node_long_address); + + /* Short addresses are disabled by default */ + node_short_address = (uint16_t)node_long_address.u32L; + vMMAC_SetRxAddress(frame802154_get_pan_id(), node_short_address, &node_long_address); + + /* Disable hardware backoff */ + vMMAC_SetTxParameters(1, 0, 0, 0); + vMMAC_SetCutOffTimer(0, FALSE); + + /* Initialize ring buffer and first input packet pointer */ + ringbufindex_init(&input_ringbuf, MIRCOMAC_CONF_BUF_NUM); + /* get pointer to next input slot */ + put_index = ringbufindex_peek_put(&input_ringbuf); + if(put_index == -1) { + rx_frame_buffer = NULL; + printf("micromac_radio init:! no buffer available. Abort init.\n"); + off(); + return 0; + } else { + rx_frame_buffer = &input_array[put_index]; + } input_frame_buffer = rx_frame_buffer; + + process_start(µmac_radio_process, NULL); + +#if RADIO_TEST_MODE == RADIO_TEST_MODE_HIGH_PWR + /* Enable high power mode. + * In this mode DIO2 goes high during RX + * and DIO3 goes high during TX + **/ + vREG_SysWrite(REG_SYS_PWR_CTRL, + u32REG_SysRead(REG_SYS_PWR_CTRL) + | REG_SYSCTRL_PWRCTRL_RFRXEN_MASK + | REG_SYSCTRL_PWRCTRL_RFTXEN_MASK); +#elif RADIO_TEST_MODE == RADIO_TEST_MODE_ADVANCED + /* output internal radio status on IO pins. + * See Chris@NXP email */ + vREG_SysWrite(REG_SYS_PWR_CTRL, + u32REG_SysRead(REG_SYS_PWR_CTRL) | (1UL << 26UL)); +#endif /* TEST_MODE */ + + return 1; +} +/*---------------------------------------------------------------------------*/ +static int +on(void) +{ + /* No address matching or frame decoding */ + if(rx_frame_buffer != NULL) { + vMMAC_StartPhyReceive(rx_frame_buffer, + (uint16_t)(E_MMAC_RX_START_NOW + | E_MMAC_RX_NO_FCS_ERROR) /* means: reject FCS errors */ + ); + } else { + missed_radio_on_request = 1; + } ENERGEST_ON(ENERGEST_TYPE_LISTEN); + listen_on = 1; + return 1; +} +/*---------------------------------------------------------------------------*/ +static int +off(void) +{ + listen_on = 0; + tx_in_progress = 0; + + ENERGEST_OFF(ENERGEST_TYPE_LISTEN); + + /* The following would be needed with delayed Tx/Rx functions + * vMMAC_SetCutOffTimer(0, FALSE);*/ + vMMAC_RadioOff(); + + return 1; +} +/*---------------------------------------------------------------------------*/ +static int +transmit(unsigned short payload_len) +{ + if(tx_in_progress) { + return RADIO_TX_COLLISION; + } + tx_in_progress = 1; + + /* Energest */ + if(listen_on) { + ENERGEST_OFF(ENERGEST_TYPE_LISTEN); + } + ENERGEST_ON(ENERGEST_TYPE_TRANSMIT); + + /* Transmit and wait */ + vMMAC_StartPhyTransmit(&tx_frame_buffer, + E_MMAC_TX_START_NOW | + (send_on_cca ? E_MMAC_TX_USE_CCA : E_MMAC_TX_NO_CCA)); + + if(poll_mode) { + BUSYWAIT_UNTIL(u32MMAC_PollInterruptSource(E_MMAC_INT_TX_COMPLETE), MAX_PACKET_DURATION); + } else { + if(in_ack_transmission) { + /* as nested interupts are not possible, the tx flag will never be cleared */ + BUSYWAIT_UNTIL(FALSE, MAX_ACK_DURATION); + } else { + /* wait until the tx flag is cleared */ + BUSYWAIT_UNTIL(!tx_in_progress, MAX_PACKET_DURATION); + } + } + + /* Energest */ + ENERGEST_OFF(ENERGEST_TYPE_TRANSMIT); + if(listen_on) { + ENERGEST_ON(ENERGEST_TYPE_LISTEN); + } + tx_in_progress = 0; + + /* Check error code */ + int ret; + uint32_t tx_error = u32MMAC_GetTxErrors(); + if(tx_error == 0) { + ret = RADIO_TX_OK; + RIMESTATS_ADD(acktx); + } else if(tx_error & E_MMAC_TXSTAT_ABORTED) { + ret = RADIO_TX_ERR; + RIMESTATS_ADD(sendingdrop); + } else if(tx_error & E_MMAC_TXSTAT_CCA_BUSY) { + ret = RADIO_TX_COLLISION; + RIMESTATS_ADD(contentiondrop); + } else if(tx_error & E_MMAC_TXSTAT_NO_ACK) { + ret = RADIO_TX_NOACK; + RIMESTATS_ADD(noacktx); + } else { + ret = RADIO_TX_ERR; + } return ret; +} +/*---------------------------------------------------------------------------*/ +static int +prepare(const void *payload, unsigned short payload_len) +{ + uint8_t i; + uint16_t checksum; + + RIMESTATS_ADD(lltx); + + if(tx_in_progress) { + return 1; + } + if(payload_len > 127 || payload == NULL) { + return 1; + /* Copy payload to (soft) Ttx buffer */ + } + memcpy(tx_frame_buffer.uPayload.au8Byte, payload, payload_len); + i = payload_len; +#if CRC_SW + /* Compute CRC */ + checksum = crc16_data(payload, payload_len, 0); + tx_frame_buffer.uPayload.au8Byte[i++] = checksum; + tx_frame_buffer.uPayload.au8Byte[i++] = (checksum >> 8) & 0xff; + tx_frame_buffer.u8PayloadLength = payload_len + CHECKSUM_LEN; +#else + tx_frame_buffer.u8PayloadLength = payload_len; +#endif + + return 0; +} +/*---------------------------------------------------------------------------*/ +static int +send(const void *payload, unsigned short payload_len) +{ + if(prepare(payload, payload_len) == 0) { + return transmit(payload_len); + } else { + return RADIO_TX_ERR; + } +} +/*---------------------------------------------------------------------------*/ +int +get_channel(void) +{ + return current_channel; +} +/*---------------------------------------------------------------------------*/ +void +set_channel(int c) +{ + current_channel = c; + /* will fine tune TX power as well */ + vMMAC_SetChannel(current_channel); +} +/*---------------------------------------------------------------------------*/ +static int +is_broadcast_addr(uint8_t mode, uint8_t *addr) +{ + int i = ((mode == FRAME802154_SHORTADDRMODE) ? 2 : 8); + while(i-- > 0) { + if(addr[i] != 0xff) { + return 0; + } + } + return 1; +} +/*---------------------------------------------------------------------------*/ +/* Send an ACK */ +static void +send_ack(const frame802154_t *frame) +{ + uint8_t buffer[3]; + /* FCF: 2 octets */ + buffer[0] = FRAME802154_ACKFRAME; + buffer[1] = 0; + /* Seqnum: 1 octets */ + buffer[2] = frame->seq; + in_ack_transmission = 1; + send(&buffer, sizeof(buffer)); + in_ack_transmission = 0; +} +/*---------------------------------------------------------------------------*/ +/* Check if a packet is for us */ +static int +is_packet_for_us(uint8_t *buf, int len, int do_send_ack) +{ + frame802154_t frame; + int result; + uint8_t parsed = frame802154_parse(buf, len, &frame); + if(parsed) { + if(frame.fcf.dest_addr_mode) { + int has_dest_panid; + frame802154_has_panid(&frame.fcf, NULL, &has_dest_panid); + if(has_dest_panid + && frame802154_get_pan_id() != FRAME802154_BROADCASTPANDID + && frame.dest_pid != frame802154_get_pan_id() + && frame.dest_pid != FRAME802154_BROADCASTPANDID) { + /* Packet to another PAN */ + return 0; + } + if(!is_broadcast_addr(frame.fcf.dest_addr_mode, frame.dest_addr)) { + result = linkaddr_cmp((linkaddr_t *)frame.dest_addr, &linkaddr_node_addr); + if(autoack_enabled && result && do_send_ack) { + /* this is a unicast frame and sending ACKs is enabled */ + send_ack(&frame); + } + return result; + } + } + return 1; + } else { + return 0; + } +} +/*---------------------------------------------------------------------------*/ +static int +read(void *buf, unsigned short bufsize) +{ + int len = 0; + uint16_t radio_last_rx_crc; + uint8_t radio_last_rx_crc_ok = 1; + + len = input_frame_buffer->u8PayloadLength; + + if(len <= CHECKSUM_LEN) { + return 0; + } else { + len -= CHECKSUM_LEN; + /* Check CRC */ +#if CRC_SW + uint16_t checksum = crc16_data(input_frame_buffer->uPayload.au8Byte, len, 0); + radio_last_rx_crc = + (uint16_t)(input_frame_buffer->uPayload.au8Byte[len + 1] << (uint16_t)8) + | input_frame_buffer->uPayload.au8Byte[len]; + radio_last_rx_crc_ok = (checksum == radio_last_rx_crc); + if(!radio_last_rx_crc_ok) { + RIMESTATS_ADD(badcrc); + } +#endif /* CRC_SW */ + if(radio_last_rx_crc_ok) { + /* If we are in poll mode we need to check the frame here */ + if(poll_mode) { + if(frame_filtering && + !is_packet_for_us(input_frame_buffer->uPayload.au8Byte, len, 0)) { + len = 0; + } else { + read_last_rssi(); + } + } + if(len != 0) { + bufsize = MIN(len, bufsize); + memcpy(buf, input_frame_buffer->uPayload.au8Byte, bufsize); + RIMESTATS_ADD(llrx); + if(!poll_mode) { + /* Not in poll mode: packetbuf should not be accessed in interrupt context */ + packetbuf_set_attr(PACKETBUF_ATTR_RSSI, radio_last_rssi); + packetbuf_set_attr(PACKETBUF_ATTR_LINK_QUALITY, radio_last_correlation); + } + } + } else { + len = 0; + /* Disable further read attempts */ + } input_frame_buffer->u8PayloadLength = 0; + } + + return len; +} +/*---------------------------------------------------------------------------*/ +static void +set_txpower(int8_t power) +{ + if(power > OUTPUT_POWER_MAX) { + current_tx_power = OUTPUT_POWER_MAX; + } else { + if(power < OUTPUT_POWER_MIN) { + current_tx_power = OUTPUT_POWER_MIN; + } else { + current_tx_power = power; + } + } + vMMAC_SetChannelAndPower(current_channel, current_tx_power); +} +/*--------------------------------------------------------------------------*/ +static int +get_txpower(void) +{ + int actual_tx_power; +#if (JENNIC_CHIP == JN5169) + /* Actual tx power value rounded to nearest integer number */ + const static int8 power_table [] = { + -32, -30, -29, -29, /* -32 .. -29 */ + -28, -28, -28, -28, /* -28 .. -25 */ + -21, -21, -21, -2, /* -24 .. -21 */ + -20, -19, -18, -17, /* -20 .. -17 */ + -17, -17, -17, -10, /* -16 .. -13 */ + -10, -10, -10, -9, /* -12 .. -09 */ + -8, -7, -6, -6, /* -08 .. -05 */ + -6, -6, 1, 1, /* -04 .. -01 */ + 1, 1, 2, 3, /* 00 .. 03 */ + 4, 5, 6, 7, /* 04 .. 07 */ + 9, 9, 10 }; /* 08 .. 10 */ + if(current_tx_power > OUTPUT_POWER_MAX) { + actual_tx_power = OUTPUT_POWER_MAX; + } else if(current_tx_power < OUTPUT_POWER_MIN) { + actual_tx_power = OUTPUT_POWER_MIN; + } else { + actual_tx_power = power_table[current_tx_power + ABS_OUTPUT_POWER_MIN]; + } +#else + /* Other JN516x chips */ + if(current_tx_power < (-24)) { + actual_tx_power = OUTPUT_POWER_MIN; + } else if(current_tx_power < (-12)) { + actual_tx_power = (-20); + } else if(current_tx_power < 0) { + actual_tx_power = (-9); + } else { + actual_tx_power = OUTPUT_POWER_MAX; + } +#endif + return (int)actual_tx_power; +} +/*---------------------------------------------------------------------------*/ +static int +get_detected_energy(void) +{ + const uint32 u32Samples = 8; + return u8JPT_EnergyDetect(current_channel, u32Samples); +} +/*---------------------------------------------------------------------------*/ +static int +get_rssi(void) +{ + /* this approximate formula for RSSI is taken from NXP internal docs */ + return (7 * get_detected_energy() - 1970) / 20; +} +/*---------------------------------------------------------------------------*/ +static void +read_last_rssi(void) +{ + uint8_t radio_last_rx_energy; + radio_last_rx_energy = u8MMAC_GetRxLqi((uint8_t *)&radio_last_correlation); + radio_last_rssi = i16JPT_ConvertEnergyTodBm(radio_last_rx_energy); +} +/*---------------------------------------------------------------------------*/ +int +receiving_packet(void) +{ + return bMMAC_RxDetected(); +} +/*---------------------------------------------------------------------------*/ +static int +pending_packet(void) +{ + if(!poll_mode) { + return ringbufindex_peek_get(&input_ringbuf) != -1; + } else { + return u32MMAC_PollInterruptSource( + E_MMAC_INT_RX_COMPLETE | E_MMAC_INT_RX_HEADER); + } +} +/*---------------------------------------------------------------------------*/ +static int +cca(void) +{ + bool_t is_channel_busy = bJPT_CCA(current_channel, + E_JPT_CCA_MODE_CARRIER_OR_ENERGY, + cca_thershold); + return is_channel_busy == FALSE; +} +/*---------------------------------------------------------------------------*/ +static void +radio_interrupt_handler(uint32 mac_event) +{ + uint32_t rx_status; + uint8_t overflow = 0; + int get_index; + int put_index; + int packet_for_me = 0; + + if(mac_event & E_MMAC_INT_TX_COMPLETE) { + /* Transmission attempt has finished */ + tx_in_progress = 0; + } else if(mac_event & E_MMAC_INT_RX_COMPLETE) { + rx_status = u32MMAC_GetRxErrors(); + /* If rx is successful */ + if(rx_status == 0) { + /* Save SFD timestamp */ + last_packet_timestamp = get_packet_timestamp(); + + if(!poll_mode && (mac_event & E_MMAC_INT_RX_COMPLETE)) { + if(rx_frame_buffer->u8PayloadLength > CHECKSUM_LEN) { + if(frame_filtering) { + /* Check RX address */ + packet_for_me = is_packet_for_us(rx_frame_buffer->uPayload.au8Byte, rx_frame_buffer->u8PayloadLength - CHECKSUM_LEN, 1); + } else if(!frame_filtering) { + packet_for_me = 1; + } + } + if(!packet_for_me) { + /* Prevent reading */ + rx_frame_buffer->u8PayloadLength = 0; + } else { + /* read and cache RSSI and LQI values */ + read_last_rssi(); + /* Put received frame in queue */ + ringbufindex_put(&input_ringbuf); + + if((get_index = ringbufindex_peek_get(&input_ringbuf)) != -1) { + input_frame_buffer = &input_array[get_index]; + } + process_poll(µmac_radio_process); + + /* get pointer to next input slot */ + put_index = ringbufindex_peek_put(&input_ringbuf); + /* is there space? */ + if(put_index != -1) { + /* move rx_frame_buffer to next empty slot */ + rx_frame_buffer = &input_array[put_index]; + } else { + overflow = 1; + rx_frame_buffer = NULL; + } + } + } + } else { /* if rx is not successful */ + if(rx_status & E_MMAC_RXSTAT_ABORTED) { + RIMESTATS_ADD(badsynch); + } else if(rx_status & E_MMAC_RXSTAT_ERROR) { + RIMESTATS_ADD(badcrc); + } else if(rx_status & E_MMAC_RXSTAT_MALFORMED) { + RIMESTATS_ADD(toolong); + } + } + } + if(overflow) { + off(); + } else if(MICROMAC_CONF_ALWAYS_ON + && (mac_event & (E_MMAC_INT_TX_COMPLETE | E_MMAC_INT_RX_COMPLETE))) { + on(); + } +} +/*---------------------------------------------------------------------------*/ +PROCESS_THREAD(micromac_radio_process, ev, data) +{ + PROCESS_BEGIN(); + + while(1) { + PROCESS_YIELD_UNTIL(ev == PROCESS_EVENT_POLL); + + /* Pass received packets to upper layer */ + int16_t read_index; + /* Loop on accessing (without removing) a pending input packet */ + while((read_index = ringbufindex_peek_get(&input_ringbuf)) != -1) { + input_frame_buffer = &input_array[read_index]; + /* Put packet into packetbuf for input callback */ + packetbuf_clear(); + int len = read(packetbuf_dataptr(), PACKETBUF_SIZE); + /* is packet valid? */ + if(len > 0) { + packetbuf_set_datalen(len); + NETSTACK_RDC.input(); + } + /* Remove packet from ringbuf */ + ringbufindex_get(&input_ringbuf); + /* Disable further read attempts */ + input_frame_buffer->u8PayloadLength = 0; + } + + /* Are we recovering from overflow? */ + if(rx_frame_buffer == NULL) { + /* get pointer to next input slot */ + int put_index = ringbufindex_peek_put(&input_ringbuf); + /* is there space? */ + if(put_index != -1) { + /* move rx_frame_buffer to next empty slot */ + rx_frame_buffer = &input_array[put_index]; + /* do we need to turn radio on? */ + if(MICROMAC_CONF_ALWAYS_ON || missed_radio_on_request) { + missed_radio_on_request = 0; + on(); + } + } else { + rx_frame_buffer = NULL; + } + } + } + PROCESS_END(); +} +/*---------------------------------------------------------------------------*/ +static void +set_frame_filtering(uint8_t enable) +{ + frame_filtering = enable; +} +/*---------------------------------------------------------------------------*/ +static void +set_autoack(uint8_t enable) +{ + autoack_enabled = enable; +} +/*---------------------------------------------------------------------------*/ +static void +set_poll_mode(uint8_t enable) +{ + poll_mode = enable; + if(poll_mode) { + /* Disable interrupts */ + vMMAC_EnableInterrupts(NULL); + vMMAC_ConfigureInterruptSources(0); + } else { + /* Initialize and enable interrupts */ + /* TODO: enable E_MMAC_INT_RX_HEADER & filter out frames after header rx */ + vMMAC_ConfigureInterruptSources( + E_MMAC_INT_RX_COMPLETE | E_MMAC_INT_TX_COMPLETE); + vMMAC_EnableInterrupts(&radio_interrupt_handler); + } +} +/* Enable or disable CCA before sending */ +static void +set_send_on_cca(uint8_t enable) +{ + send_on_cca = enable; +} +/*---------------------------------------------------------------------------*/ +static radio_result_t +get_value(radio_param_t param, radio_value_t *value) +{ + int i, v; + + if(!value) { + return RADIO_RESULT_INVALID_VALUE; + } + switch(param) { + case RADIO_PARAM_POWER_MODE: + *value = listen_on || tx_in_progress ? RADIO_POWER_MODE_ON : RADIO_POWER_MODE_OFF; + return RADIO_RESULT_OK; + case RADIO_PARAM_CHANNEL: + *value = get_channel(); + return RADIO_RESULT_OK; + case RADIO_PARAM_RX_MODE: + *value = 0; + if(frame_filtering) { + *value |= RADIO_RX_MODE_ADDRESS_FILTER; + } + if(autoack_enabled) { + *value |= RADIO_RX_MODE_AUTOACK; + } + if(poll_mode) { + *value |= RADIO_RX_MODE_POLL_MODE; + } + return RADIO_RESULT_OK; + case RADIO_PARAM_TX_MODE: + *value = 0; + if(send_on_cca) { + *value |= RADIO_TX_MODE_SEND_ON_CCA; + } + return RADIO_RESULT_OK; + case RADIO_PARAM_TXPOWER: + *value = get_txpower(); + return RADIO_RESULT_OK; + case RADIO_PARAM_RSSI: + *value = get_rssi(); + return RADIO_RESULT_OK; + case RADIO_PARAM_LAST_RSSI: + *value = radio_last_rssi; + return RADIO_RESULT_OK; + case RADIO_PARAM_CCA_THRESHOLD: + *value = cca_thershold; + return RADIO_RESULT_OK; + case RADIO_CONST_CHANNEL_MIN: + *value = 11; + return RADIO_RESULT_OK; + case RADIO_CONST_CHANNEL_MAX: + *value = 26; + return RADIO_RESULT_OK; + case RADIO_CONST_TXPOWER_MIN: + *value = OUTPUT_POWER_MIN; + return RADIO_RESULT_OK; + case RADIO_CONST_TXPOWER_MAX: + *value = OUTPUT_POWER_MAX; + return RADIO_RESULT_OK; + default: + return RADIO_RESULT_NOT_SUPPORTED; + } +} +/*---------------------------------------------------------------------------*/ +static radio_result_t +set_value(radio_param_t param, radio_value_t value) +{ + int i; + + switch(param) { + case RADIO_PARAM_POWER_MODE: + if(value == RADIO_POWER_MODE_ON) { + on(); + return RADIO_RESULT_OK; + } + if(value == RADIO_POWER_MODE_OFF) { + off(); + return RADIO_RESULT_OK; + } + return RADIO_RESULT_INVALID_VALUE; + case RADIO_PARAM_CHANNEL: + if(value < 11 || value > 26) { + return RADIO_RESULT_INVALID_VALUE; + } + set_channel(value); + return RADIO_RESULT_OK; + case RADIO_PARAM_RX_MODE: + if(value & ~(RADIO_RX_MODE_ADDRESS_FILTER | + RADIO_RX_MODE_AUTOACK | RADIO_RX_MODE_POLL_MODE)) { + return RADIO_RESULT_INVALID_VALUE; + } + set_frame_filtering((value & RADIO_RX_MODE_ADDRESS_FILTER) != 0); + set_autoack((value & RADIO_RX_MODE_AUTOACK) != 0); + set_poll_mode((value & RADIO_RX_MODE_POLL_MODE) != 0); + return RADIO_RESULT_OK; + case RADIO_PARAM_TX_MODE: + if(value & ~(RADIO_TX_MODE_SEND_ON_CCA)) { + return RADIO_RESULT_INVALID_VALUE; + } + set_send_on_cca((value & RADIO_TX_MODE_SEND_ON_CCA) != 0); + return RADIO_RESULT_OK; + case RADIO_PARAM_TXPOWER: + if(value < OUTPUT_POWER_MIN || value > OUTPUT_POWER_MAX) { + return RADIO_RESULT_INVALID_VALUE; + /* Find the closest higher PA_LEVEL for the desired output power */ + } + set_txpower(value); + return RADIO_RESULT_OK; + case RADIO_PARAM_CCA_THRESHOLD: + cca_thershold = value; + return RADIO_RESULT_OK; + default: + return RADIO_RESULT_NOT_SUPPORTED; + } +} +/*---------------------------------------------------------------------------*/ +static radio_result_t +get_object(radio_param_t param, void *dest, size_t size) +{ + if(param == RADIO_PARAM_LAST_PACKET_TIMESTAMP) { + if(size != sizeof(rtimer_clock_t) || !dest) { + return RADIO_RESULT_INVALID_VALUE; + } + *(rtimer_clock_t *)dest = get_packet_timestamp(); + + return RADIO_RESULT_OK; + } + return RADIO_RESULT_NOT_SUPPORTED; +} +/*---------------------------------------------------------------------------*/ +static radio_result_t +set_object(radio_param_t param, const void *src, size_t size) +{ + return RADIO_RESULT_NOT_SUPPORTED; +} +/*---------------------------------------------------------------------------*/ +const struct radio_driver micromac_radio_driver = { + init, + prepare, + transmit, + send, + read, + cca, + receiving_packet, + pending_packet, + on, + off, + get_value, + set_value, + get_object, + set_object +}; diff --git a/platform/jn516x/dev/micromac-radio.h b/platform/jn516x/dev/micromac-radio.h new file mode 100644 index 000000000..a283af23d --- /dev/null +++ b/platform/jn516x/dev/micromac-radio.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2014, NXP and SICS Swedish ICT. + * 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 Institute 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 INSTITUTE 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 INSTITUTE 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. + * + * This file is part of the Contiki operating system. + * + */ + +/** + * \file + * MICROMAC_RADIO driver header file + * \authors + * Beshr Al Nahas + * Simon Duquennot + */ + +#ifndef MICROMAC_RADIO_H_ +#define MICROMAC_RADIO_H_ + +#include "dev/radio.h" + +extern const struct radio_driver micromac_radio_driver; + +#endif /* MICROMAC_RADIO_H_ */ diff --git a/platform/jn516x/dev/mtarch.c b/platform/jn516x/dev/mtarch.c new file mode 100644 index 000000000..c3c81457e --- /dev/null +++ b/platform/jn516x/dev/mtarch.c @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2008 + * Telecooperation Office (TecO), Universitaet Karlsruhe (TH), Germany. + * 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 Universitaet Karlsruhe (TH) 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 COPYRIGHT HOLDERS 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 COPYRIGHT + * OWNER 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. + * + * Author(s): Philipp Scholl + */ + +/* Copied from Philipp Scholl's (BSD) Contiki port to Jennic */ + +#include "mtarch.h" + +void +mtarch_init(void) +{ +} +void +mtarch_remove(void) +{ +} +void +mtarch_start(struct mtarch_thread *thread, + void (*function)(void *data), + void *data) +{ +} +void +mtarch_yield(void) +{ +} +void +mtarch_exec(struct mtarch_thread *thread) +{ +} +void +mtarch_stop(struct mtarch_thread *thread) +{ +} +void +mtarch_pstart(void) +{ +} +void +mtarch_pstop(void) +{ +} diff --git a/platform/jn516x/dev/mtarch.h b/platform/jn516x/dev/mtarch.h new file mode 100644 index 000000000..3c6292f1d --- /dev/null +++ b/platform/jn516x/dev/mtarch.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2008 + * Telecooperation Office (TecO), Universitaet Karlsruhe (TH), Germany. + * 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 Universitaet Karlsruhe (TH) 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 COPYRIGHT HOLDERS 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 COPYRIGHT + * OWNER 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. + * + * Author(s): Philipp Scholl + */ + +/* Copied from Philipp Scholl's (BSD) Contiki port to Jennic */ + +#ifndef __MTARCH_H__ +#define __MTARCH_H__ + +struct mtarch_thread { + void *mt_thread; +}; + +#endif /* __MTARCH_H__ */ diff --git a/platform/jn516x/dev/node-id.c b/platform/jn516x/dev/node-id.c new file mode 100644 index 000000000..d0e95d521 --- /dev/null +++ b/platform/jn516x/dev/node-id.c @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2014, SICS Swedish ICT. + * 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 Institute 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 INSTITUTE 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 INSTITUTE 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. + * + * This file is part of the Contiki operating system. + * + */ + +/** + * \file + * For compatibility with Contiki node-id interface + * + * \author + * Beshr Al Nahas + */ + +#include "contiki.h" +#include "sys/node-id.h" +#include "contiki-conf.h" + +/*---------------------------------------------------------------------------*/ +extern unsigned char node_mac[8]; +unsigned short node_id = 0; +/*---------------------------------------------------------------------------*/ +void +node_id_restore(void) +{ + /* base node-id on MAC address */ + node_id = (node_mac[6] << 8) | node_mac[7]; +} +/*---------------------------------------------------------------------------*/ +void +node_id_burn(unsigned short id) +{ + /* does not burn anything */ + node_id = id; +} diff --git a/platform/jn516x/dev/rtimer-arch.c b/platform/jn516x/dev/rtimer-arch.c new file mode 100644 index 000000000..f89b8a9a8 --- /dev/null +++ b/platform/jn516x/dev/rtimer-arch.c @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2014, SICS Swedish ICT. + * 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 Institute 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 INSTITUTE 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 INSTITUTE 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. + * + * This file is part of the Contiki operating system. + * + */ + +/** + * \file + * RTIMER for NXP jn516x + * \author + * Beshr Al Nahas + */ + +#include "sys/rtimer.h" +#include "sys/clock.h" +#include +#include +#include "dev/watchdog.h" +#include "sys/energest.h" + +#define RTIMER_TIMER_ISR_DEV E_AHI_DEVICE_TICK_TIMER + +#define DEBUG 0 +#if DEBUG +#include +#define PRINTF(...) printf(__VA_ARGS__) +#else +#define PRINTF(...) +#endif + +static volatile uint32_t compare_time; +static volatile uint32_t last_expired_time; + +void +rtimer_arch_run_next(uint32 u32DeviceId, uint32 u32ItemBitmap) +{ + uint32_t delta, temp; + if(u32DeviceId != RTIMER_TIMER_ISR_DEV) { + return; + } + ENERGEST_ON(ENERGEST_TYPE_IRQ); + vAHI_TickTimerIntPendClr(); + vAHI_TickTimerIntEnable(0); + /* + * compare register is only 28bits wide so make sure the upper 4bits match + * the set compare point + */ + delta = u32AHI_TickTimerRead() - compare_time; + if(0 == (delta >> 28)) { + /* compare_time might change after executing rtimer_run_next() + * as some process might schedule the timer + */ + temp = compare_time; + + /* run scheduled */ + watchdog_start(); + rtimer_run_next(); + + if(process_nevents() > 0) { + /* TODO exit low-power mode */ + } + + watchdog_stop(); + last_expired_time = temp; + } else { + /* No match. Schedule again. */ + vAHI_TickTimerIntEnable(1); + vAHI_TickTimerInterval(compare_time); + } + ENERGEST_OFF(ENERGEST_TYPE_IRQ); +} +/*---------------------------------------------------------------------------*/ +void +rtimer_arch_init(void) +{ + /* Initialise tick timer to run continuously */ + vAHI_TickTimerIntEnable(0); + vAHI_TickTimerConfigure(E_AHI_TICK_TIMER_DISABLE); + last_expired_time = compare_time = 0; + vAHI_TickTimerWrite(0); + vAHI_TickTimerRegisterCallback(rtimer_arch_run_next); + vAHI_TickTimerConfigure(E_AHI_TICK_TIMER_CONT); +} +/*---------------------------------------------------------------------------*/ +rtimer_clock_t +rtimer_arch_now(void) +{ + return u32AHI_TickTimerRead(); +} +/*---------------------------------------------------------------------------*/ +void +rtimer_arch_schedule(rtimer_clock_t t) +{ + PRINTF("rtimer_arch_schedule time %lu\n", t); + vAHI_TickTimerIntPendClr(); + vAHI_TickTimerIntEnable(1); + vAHI_TickTimerInterval(t); + compare_time = t; +} +/*---------------------------------------------------------------------------*/ +rtimer_clock_t +rtimer_arch_get_time_until_next_wakeup(void) +{ + rtimer_clock_t now = RTIMER_NOW(); + rtimer_clock_t next_wakeup = compare_time; + if(bAHI_TickTimerIntStatus()) { + return next_wakeup >= now ? next_wakeup - now : 0; + /* if no wakeup is scheduled yet return maximum time */ + } + return (rtimer_clock_t)-1; +} +/*---------------------------------------------------------------------------*/ diff --git a/platform/jn516x/dev/rtimer-arch.h b/platform/jn516x/dev/rtimer-arch.h new file mode 100644 index 000000000..ec7211262 --- /dev/null +++ b/platform/jn516x/dev/rtimer-arch.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2014, SICS Swedish ICT. + * 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 Institute 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 INSTITUTE 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 INSTITUTE 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. + * + * This file is part of the Contiki operating system. + * + */ + +/** + * \file + * Header file for NXP jn516x-specific rtimer code + * \author + * Beshr Al Nahas + */ + +#ifndef RTIMER_ARCH_H_ +#define RTIMER_ARCH_H_ + +#include "sys/rtimer.h" + +#ifdef RTIMER_CONF_SECOND +#define RTIMER_ARCH_SECOND RTIMER_CONF_SECOND +#else +/* 32MHz CPU clock => 16MHz timer */ +#define RTIMER_ARCH_SECOND (F_CPU / 2) +#endif + +#define US_TO_RTIMERTICKS(D) ((int64_t)(D) << 4) +#define RTIMERTICKS_TO_US(T) ((int64_t)(T) >> 4) + +rtimer_clock_t rtimer_arch_now(void); + +rtimer_clock_t rtimer_arch_get_time_until_next_wakeup(void); + +#endif /* RTIMER_ARCH_H_ */ diff --git a/platform/jn516x/dev/slip_uart0.c b/platform/jn516x/dev/slip_uart0.c new file mode 100644 index 000000000..a02791de2 --- /dev/null +++ b/platform/jn516x/dev/slip_uart0.c @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2014, SICS Swedish ICT. + * 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 Institute 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 INSTITUTE 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 INSTITUTE 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. + * + */ + +/* + * Machine dependent jn516x SLIP routines for UART0. + */ + +#include "contiki-conf.h" +#include "dev/slip.h" +#include "dev/uart0.h" +/*---------------------------------------------------------------------------*/ +void +slip_arch_writeb(unsigned char c) +{ + uart0_writeb(c); +} +/*---------------------------------------------------------------------------*/ +/** + * Initalize the RS232 port and the SLIP driver. + * + */ +void +slip_arch_init(unsigned long ubr) +{ + uart0_set_input(slip_input_byte); +} +/*---------------------------------------------------------------------------*/ diff --git a/platform/jn516x/dev/uart-driver.c b/platform/jn516x/dev/uart-driver.c new file mode 100644 index 000000000..e5a58f0b5 --- /dev/null +++ b/platform/jn516x/dev/uart-driver.c @@ -0,0 +1,605 @@ +/* + * Copyright (c) 2015 NXP B.V. + * 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 NXP B.V. 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 NXP B.V. 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 NXP B.V. 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. + * + * This file is part of the Contiki operating system. + * + * Author: Lee Mitchell + * Integrated into Contiki by Beshr Al Nahas + * + */ + +#include + +#ifdef DEBUG +#include +#else +#define DBG_vPrintf(...) +#endif + +#include "contiki-conf.h" +#include "uart-driver.h" +#include "sys/rtimer.h" +#include +#include + +#if UART_XONXOFF_FLOW_CTRL + +#include "sys/process.h" + +#define TX_FIFO_SW_FLOW_LIMIT 8 /* Maximum allowed fill level for tx fifo */ +#if TX_FIFO_SW_FLOW_LIMIT > 16 +#undef TX_FIFO_SW_FLOW_LIMIT +#define TX_FIFO_SW_FLOW_LIMIT 16 +#warning "TX_FIFO_SW_FLOW_LIMIT too big. Forced to 16." +#endif /* TX_FIFO_SW_FLOW_LIMIT > 16 */ + +#define XON 17 +#define XOFF 19 + +extern volatile unsigned char xonxoff_state; + +#endif /* UART_XONXOFF_FLOW_CTRL */ + +/*** Macro Definitions ***/ +#define BUSYWAIT_UNTIL(cond, max_time) \ + do { \ + rtimer_clock_t t0; \ + t0 = RTIMER_NOW(); \ + while(!(cond) && RTIMER_CLOCK_LT(RTIMER_NOW(), t0 + (max_time))) ; \ + } while(0) + +#define DEBUG_UART_BUFFERED FALSE + +#define CHAR_DEADLINE (uart_char_delay * 100) + +/*** Local Function Prototypes ***/ +static void uart_driver_isr(uint32_t device_id, uint32_t item_bitmap); +static int16_t uart_driver_get_tx_fifo_available_space(uint8_t uart_dev); +static void uart_driver_set_baudrate(uint8_t uart_dev, uint8_t br); +static void uart_driver_set_high_baudrate(uint8_t uart_dev, uint32_t baud_rate); + +/*** Local Variables ***/ +#define UART_NUM_UARTS 2 +static uint16_t tx_fifo_size[UART_NUM_UARTS] = { 0 }; +static uint8_t active_uarts[UART_NUM_UARTS] = { 0 }; +/** slip input function pointer */ +static int(*uart_input[UART_NUM_UARTS]) (unsigned char) = { 0 }; +/* time in uSec for transmitting 1 char */ +static uint16_t uart_char_delay = 0; +static volatile int8_t interrupt_enabled[UART_NUM_UARTS] = { 0 }; +static volatile int8_t interrupt_enabled_saved[UART_NUM_UARTS] = { 0 }; + +/**************************************************************************** + * + * NAME: uart_driver_init + * + * DESCRIPTION: + * Initializes the specified UART device. + * + * PARAMETERS: Name RW Usage + * uart_dev R UART to initialise, eg, E_AHI_UART_0 + * br R Baudrate to use (e.g. UART_RATE_115200) + * if br > UART_RATE_115200 + * then uart_driver_set_baud_rate is called + * else vAHI_UartSetClockDivisor + * txbuf_data R Pointer to a memory block to use + * and rxbuf_data as uart tx/rx fifo + * txbuf_size R size of tx fifo (valid range: 16-2047) + * txbuf_size R size of rx fifo (valid range: 16-2047) + * uart_input_function a function pointer to input uart rx bytes + * RETURNS: + * void + * + ****************************************************************************/ +void +uart_driver_init(uint8_t uart_dev, uint8_t br, uint8_t *txbuf_data, + uint16_t txbuf_size, uint8_t *rxbuf_data, uint16_t rxbuf_size, + int (*uart_input_function)(unsigned char c)) +{ +#if !UART_HW_FLOW_CTRL + /* Disable RTS/CTS */ + vAHI_UartSetRTSCTS(uart_dev, FALSE); +#endif + + tx_fifo_size[uart_dev] = txbuf_size; + + /* Configure the selected Uart */ + uint8_t uart_enabled = bAHI_UartEnable(uart_dev, txbuf_data, txbuf_size, + rxbuf_data, rxbuf_size); + /* fallback to internal buffers */ + if(!uart_enabled) { + vAHI_UartEnable(uart_dev); + tx_fifo_size[uart_dev] = 16; /* Fixed size */ + } + /* Reset tx/rx fifos */ + vAHI_UartReset(uart_dev, TRUE, TRUE); + vAHI_UartReset(uart_dev, FALSE, FALSE); + + uart_driver_set_baudrate(uart_dev, br); + + /* install interrupt service callback */ + if(uart_dev == E_AHI_UART_0) { + vAHI_Uart0RegisterCallback((void *)uart_driver_isr); + } else { + vAHI_Uart1RegisterCallback((void *)uart_driver_isr); + /* Enable RX interrupt */ + } + uart_driver_enable_interrupts(uart_dev); + uart_input[uart_dev] = uart_input_function; + active_uarts[uart_dev] = 1; + +#if UART_HW_FLOW_CTRL + /* Configure HW flow control */ + vAHI_UartSetAutoFlowCtrl(uart_dev, E_AHI_UART_FIFO_ARTS_LEVEL_13, /* uint8 const u8RxFifoLevel,*/ + FALSE, /* bool_t const bFlowCtrlPolarity,*/ + TRUE, /* bool_t const bAutoRts, */ + TRUE /* bool_t const bAutoCts */); +#endif + + printf("UART %d init: using %s buffers %d\n", uart_dev, + uart_enabled ? "external" : "internal", tx_fifo_size[uart_dev]); +} +void +uart_driver_enable_interrupts(uint8_t uart_dev) +{ + /* wait while char being tx is done */ + while((u8AHI_UartReadLineStatus(uart_dev) & E_AHI_UART_LS_THRE) == 0) ; + + vAHI_UartSetInterrupt(uart_dev, FALSE /*bEnableModemStatus*/, + FALSE /*bEnableRxLineStatus == Break condition */, + FALSE /*bEnableTxFifoEmpty*/, + TRUE /* bEnableRxData */, E_AHI_UART_FIFO_LEVEL_14); + interrupt_enabled[uart_dev] = 1; +} +void +uart_driver_disable_interrupts(uint8_t uart_dev) +{ + /* wait while char being tx is done */ + while((u8AHI_UartReadLineStatus(uart_dev) & E_AHI_UART_LS_THRE) == 0) ; + + vAHI_UartSetInterrupt(uart_dev, FALSE /*bEnableModemStatus*/, + FALSE /*bEnableRxLineStatus == Break condition */, + FALSE /*bEnableTxFifoEmpty*/, + FALSE /* bEnableRxData */, E_AHI_UART_FIFO_LEVEL_14); + interrupt_enabled[uart_dev] = 0; +} +void +uart_driver_store_interrupts(uint8_t uart_dev) +{ + interrupt_enabled_saved[uart_dev] = interrupt_enabled[uart_dev]; +} +void +uart_driver_restore_interrupts(uint8_t uart_dev) +{ + if(interrupt_enabled_saved[uart_dev]) { + uart_driver_enable_interrupts(uart_dev); + } else { + uart_driver_disable_interrupts(uart_dev); + } +} +int8_t +uart_driver_interrupt_is_enabled(uint8_t uart_dev) +{ + return interrupt_enabled[uart_dev]; +} +void +uart_driver_set_input(uint8_t uart_dev, int + (*uart_input_function)(unsigned char c)) +{ + uart_input[uart_dev] = uart_input_function; +} +/**************************************************************************** + * + * NAME: uart_driver_read + * + * DESCRIPTION: + * Reads 1 byte from the RX buffer. If there is no data in the + * buffer, then return FALSE + * + * PARAMETERS: Name RW Usage + * uart_dev R UART to use, eg, E_AHI_UART_0 + * + * RETURNS: + * TRUE if a byte has been read from the queue + * + ****************************************************************************/ +uint8_t +uart_driver_read(uint8_t uart_dev, uint8_t *data) +{ + if(data && u16AHI_UartReadRxFifoLevel(uart_dev) > 0) { + *data = u8AHI_UartReadData(uart_dev); + return TRUE; + } + return FALSE; +} +void +uart_driver_write_buffered(uint8_t uart_dev, uint8_t ch) +{ + uart_driver_write_with_deadline(uart_dev, ch); +} +/**************************************************************************** + * + * NAME: uart_driver_write_with_deadline + * + * DESCRIPTION: + * Writes one byte to the specified uart for transmission + * + * PARAMETERS: Name RW Usage + * uart_dev R UART to use, eg, E_AHI_UART_0 + * ch R data to transmit + * + * RETURNS: + * void + * + ****************************************************************************/ +void +uart_driver_write_with_deadline(uint8_t uart_dev, uint8_t ch) +{ +#if UART_XONXOFF_FLOW_CTRL + /* Block until host can receive data */ + /* Wait until there are less than N characters in TX FIFO */ + while(xonxoff_state != XON + || u16AHI_UartReadTxFifoLevel(uart_dev) > TX_FIFO_SW_FLOW_LIMIT) { + watchdog_periodic(); + } + /* write to TX FIFO and return immediately */ + vAHI_UartWriteData(uart_dev, ch); +#else /* UART_XONXOFF_FLOW_CTRL */ + volatile int16_t write = 0; + watchdog_periodic(); + /* wait until there is space in tx fifo */ + BUSYWAIT_UNTIL(write = (uart_driver_get_tx_fifo_available_space(uart_dev) > 0), + CHAR_DEADLINE); + /* write only if there is space so we do not get stuck */ + if(write) { + /* write to TX FIFO and return immediately */ + vAHI_UartWriteData(uart_dev, ch); + } +#endif /* UART_XONXOFF_FLOW_CTRL */ +} +void +uart_driver_write_direct(uint8_t uart_dev, uint8_t ch) +{ + /* Write character */ + vAHI_UartWriteData(uart_dev, ch); + /* Wait for buffers to empty */ + while((u8AHI_UartReadLineStatus(uart_dev) & E_AHI_UART_LS_THRE) == 0) ; + while((u8AHI_UartReadLineStatus(uart_dev) & E_AHI_UART_LS_TEMT) == 0) ; +} +/**************************************************************************** + * + * NAME: uart_driver_rx_handler + * + * DESCRIPTION: + * Interrupt service callback for UART data reception. Reads a received + * byte from the UART and writes it to the reception buffer if it is not + * full. + * + * PARAMETERS: Name RW Usage + * uart_dev R Uart to read from + * + * RETURNS: + * void + * + ****************************************************************************/ +void +uart_driver_rx_handler(uint8_t uart_dev) +{ + /* optimization for high throughput: Read upto 32 bytes from RX fifo. + * Disabled because it does not work with current slip_input_byte */ + + /* Status from uart_input: + * 0 means do not exit power saving mode + * -1 means RX buffer overflow ==> stop reading + * 1 means end of slip packet + */ +#if UART_XONXOFF_FLOW_CTRL + /* save old status */ + int xonxoff_state_old = xonxoff_state; +#endif /* UART_XONXOFF_FLOW_CTRL */ + int status = 0; + int c = 0; + while(u16AHI_UartReadRxFifoLevel(uart_dev) > 0 && c++ < 32 && status == 0) { + if(uart_input[uart_dev] != NULL) { /* read one char at a time */ + + /* process received character */ + status = (uart_input[uart_dev])(u8AHI_UartReadData(uart_dev)); + +#if UART_XONXOFF_FLOW_CTRL + /* Process XON-XOFF*/ + if(xonxoff_state == XOFF) { + /* XXX do not set break condition as it corrupts one character, instead we block on TX */ + /* Instruct uart to stop TX */ + /* vAHI_UartSetBreak(uart_dev, TRUE); */ + break; + } else if(xonxoff_state_old == XOFF && xonxoff_state == XON) { + /* Instruct uart to resume TX if it was stopped */ + /* vAHI_UartSetBreak(uart_dev, FALSE); */ + } +#endif /* UART_XONXOFF_FLOW_CTRL */ + } else { + /* no input handler, or no bytes to read: Discard byte. */ + u8AHI_UartReadData(uart_dev); + } + } +} +/****************************************************************************/ +/*** Local Functions ***/ +/****************************************************************************/ + +/* Returns the free space in tx fifo, i.e., how many characters we can put */ +static int16_t +uart_driver_get_tx_fifo_available_space(uint8_t uart_dev) +{ + return tx_fifo_size[uart_dev] - u16AHI_UartReadTxFifoLevel(uart_dev); +} +/* Initializes the specified UART with auto-selection of + baudrate tuning method */ +static void +uart_driver_set_baudrate(uint8_t uart_dev, uint8_t br) +{ + uint32_t high_br = 0; + uint8_t low_br = 0; + + switch(br) { + case UART_RATE_4800: + low_br = E_AHI_UART_RATE_4800; + uart_char_delay = 1667; + break; + case UART_RATE_9600: + low_br = E_AHI_UART_RATE_9600; + uart_char_delay = 834; + break; + case UART_RATE_19200: + low_br = E_AHI_UART_RATE_19200; + uart_char_delay = 417; + break; + case UART_RATE_38400: + low_br = E_AHI_UART_RATE_38400; + uart_char_delay = 209; + break; + case UART_RATE_76800: + low_br = E_AHI_UART_RATE_76800; + uart_char_delay = 105; + break; + case UART_RATE_115200: + low_br = E_AHI_UART_RATE_115200; + uart_char_delay = 69; + break; + case UART_RATE_230400: + high_br = 230400UL; + uart_char_delay = 35; + break; + case UART_RATE_460800: + high_br = 460800UL; + uart_char_delay = 18; + break; + case UART_RATE_500000: + high_br = 500000UL; + uart_char_delay = 16; + break; + case UART_RATE_576000: + high_br = 576000UL; + uart_char_delay = 14; + break; + case UART_RATE_921600: + high_br = 921600UL; + uart_char_delay = 9; + break; + case UART_RATE_1000000: + high_br = 1000000UL; + uart_char_delay = 8; + break; + default: + high_br = 1000000UL; + uart_char_delay = 8; + break; + } + if(high_br == 0) { + vAHI_UartSetClockDivisor(uart_dev, low_br); + } else { + uart_driver_set_high_baudrate(uart_dev, high_br); + } +} +/**************************************************************************** + * + * NAME: uart_driver_set_high_baudrate + * + * DESCRIPTION: + * Sets the baud rate for the specified uart + * + * PARAMETERS: Name RW Usage + * uart_dev R UART to initialise, eg, E_AHI_UART_0 + * baud_rate R Baudrate to use (bps eg 921600) + * + * RETURNS: + * void + * + ****************************************************************************/ +static void +uart_driver_set_high_baudrate(uint8_t uart_dev, uint32_t baud_rate) +{ + uint16 u16Divisor = 1; + uint32_t u32Remainder; + uint8_t u8ClocksPerBit = 16; + +#if (ENABLE_ADVANCED_BAUD_SELECTION) + /* Defining ENABLE_ADVANCED_BAUD_SELECTION in the Makefile + * enables this code which searches for a clocks per bit setting + * that gets closest to the configured rate. + */ + uint32_t u32CalcBaudRate = 0; + int32 i32BaudError = 0x7FFFFFFF; + + DBG_vPrintf(DEBUG_UART_BUFFERED, "Config uart=%d, baud=%d\n", uart_dev, + baud_rate); + + while(abs(i32BaudError) > (int32)(baud_rate >> 4)) { /* 6.25% (100/16) error */ + if(--u8ClocksPerBit < 3) { + DBG_vPrintf(DEBUG_UART_BUFFERED, + "Could not calculate UART settings for target baud!"); + return; + } +#endif /* ENABLE_ADVANCED_BAUD_SELECTION */ + + /* Calculate Divisor register = 16MHz / (16 x baud rate) */ + u16Divisor = (uint16)(16000000UL / ((u8ClocksPerBit + 1) * baud_rate)); + + /* Correct for rounding errors */ + u32Remainder = + (uint32_t)(16000000UL % ((u8ClocksPerBit + 1) * baud_rate)); + + if(u32Remainder >= (((u8ClocksPerBit + 1) * baud_rate) / 2)) { + u16Divisor += 1; + } +#if (ENABLE_ADVANCED_BAUD_SELECTION) + DBG_vPrintf(DEBUG_UART_BUFFERED, "Divisor=%d, cpb=%d\n", u16Divisor, + u8ClocksPerBit); + + u32CalcBaudRate = (16000000UL / ((u8ClocksPerBit + 1) * u16Divisor)); + + DBG_vPrintf(DEBUG_UART_BUFFERED, "Calculated baud=%d\n", u32CalcBaudRate); + + i32BaudError = (int32)u32CalcBaudRate - (int32)baud_rate; + + DBG_vPrintf(DEBUG_UART_BUFFERED, "Error baud=%d\n", i32BaudError); +} +DBG_vPrintf(DEBUG_UART_BUFFERED, "Config uart=%d: Divisor=%d, cpb=%d\n", + uart_dev, u16Divisor, u8ClocksPerBit); + +/* Set the calculated clocks per bit */ +vAHI_UartSetClocksPerBit(uart_dev, u8ClocksPerBit); +#endif /* ENABLE_ADVANCED_BAUD_SELECTION */ + + /* Set the calculated divisor */ + vAHI_UartSetBaudDivisor(uart_dev, u16Divisor); +} + +/**************************************************************************** + * + * NAME: uart_driver_isr + * + * DESCRIPTION: + * Interrupt service callback for UART's + * + * PARAMETERS: Name RW Usage + * device_id R Device ID of whatever generated the + * interrupt + * item_bitmap R Which part of the device generated + * the interrupt + * + * RETURNS: + * void + * + ****************************************************************************/ +static void +uart_driver_isr(uint32_t device_id, uint32_t item_bitmap) +{ + uint8_t uart_dev; + switch(device_id) { + case E_AHI_DEVICE_UART0: + uart_dev = E_AHI_UART_0; + break; + case E_AHI_DEVICE_UART1: + uart_dev = E_AHI_UART_1; + break; + default: + return; + } + switch(item_bitmap) { + /* byte available since a long time but RX-fifo not full: */ + case E_AHI_UART_INT_TIMEOUT: + /* RX-fifo full: */ + case E_AHI_UART_INT_RXDATA: + uart_driver_rx_handler(uart_dev); + break; + case E_AHI_UART_INT_TX: + break; + case E_AHI_UART_INT_RXLINE: + /* rx-line interrupt is disabled. Should not get here */ + /* An error condition has occurred on the RxD line, such as + a break indication, framing error, parity error or over-run. */ + break; + } +} +/**************************************************************************** + * + * NAME: uart_driver_tx_in_progress + * + * DESCRIPTION: + * Returns the state of data transmission + * + * PARAMETERS: Name RW Usage + * uart_dev R UART to use, eg, E_AHI_UART_0 + * + * RETURNS: + * uint8_t: TRUE if data in buffer is being transmitted + * FALSE if all data in buffer has been transmitted by the UART + * + ****************************************************************************/ +uint8_t +uart_driver_tx_in_progress(uint8_t uart_dev) +{ + + if(u16AHI_UartReadTxFifoLevel(uart_dev) == 0) { + if((u8AHI_UartReadLineStatus(uart_dev) & E_AHI_UART_LS_TEMT) != 0) { + return FALSE; + } + } + return TRUE; +} +#ifdef UART_EXTRAS + +/**************************************************************************** + * + * NAME: uart_driver_flush + * + * DESCRIPTION: + * Flushes the buffers of the specified UART + * + * PARAMETERS: Name RW Usage + * uart_dev R UART to disable, eg, E_AHI_UART_0 + * + * RETURNS: + * void + * + ****************************************************************************/ +void +uart_driver_flush(uint8_t uart_dev) +{ + /* Disable TX Fifo empty and Rx data interrupts */ + uart_driver_disable_interrupts(uart_dev); + + /* flush hardware buffer */ + vAHI_UartReset(uart_dev, TRUE, TRUE); + vAHI_UartReset(uart_dev, FALSE, FALSE); + + /* Re-enable TX Fifo empty and Rx data interrupts */ + uart_driver_enable_interrupts(uart_dev); +} +#endif /* UART_EXTRAS */ diff --git a/platform/jn516x/dev/uart-driver.h b/platform/jn516x/dev/uart-driver.h new file mode 100644 index 000000000..322bf950d --- /dev/null +++ b/platform/jn516x/dev/uart-driver.h @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2015 NXP B.V. + * 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 NXP B.V. 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 NXP B.V. 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 NXP B.V. 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. + * + * This file is part of the Contiki operating system. + * + * Author: Lee Mitchell + * Integrated into Contiki by Beshr Al Nahas + * + */ + +#ifndef UARTDRIVER_H +#define UARTDRIVER_H + +#include +#include "contiki-conf.h" + +void uart_driver_init(uint8_t uart_dev, uint8_t br, uint8_t * txbuf_data, uint16_t txbuf_size, uint8_t * rxbuf_data, uint16_t rxbuf_size, int (*uart_input_function)(unsigned char c)); +void uart_driver_write_buffered(uint8_t uart_dev, uint8_t ch); +void uart_driver_write_with_deadline(uint8_t uart_dev, uint8_t c); +uint8_t uart_driver_read(uint8_t uart_dev, uint8_t *data); +void uart_driver_write_direct(uint8_t uart_dev, uint8_t ch); +void uart_driver_set_input(uint8_t u8Uart, int (*uart_input_function)(unsigned char c)); + +void uart_driver_rx_handler(uint8_t uart_dev); +void uart_driver_enable_interrupts(uint8_t uart_dev); +void uart_driver_disable_interrupts(uint8_t uart_dev); +int8_t uart_driver_interrupt_is_enabled(uint8_t uart_dev); +void uart_driver_store_interrupts(uint8_t uart_dev); +void uart_driver_restore_interrupts(uint8_t uart_dev); + +uint8_t uart_driver_tx_in_progress(uint8_t uart_dev); + +#ifdef UART_EXTRAS +void uart_driver_flush(uint8_t uart_dev); +#endif + +#endif /* UARTDRIVER_H */ diff --git a/platform/jn516x/dev/uart0.c b/platform/jn516x/dev/uart0.c new file mode 100644 index 000000000..58432abcc --- /dev/null +++ b/platform/jn516x/dev/uart0.c @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2014, SICS Swedish ICT. + * 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 Institute 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 INSTITUTE 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 INSTITUTE 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. + * + * This file is part of the Contiki operating system. + * + */ + +/** + * \file + * UART0 drivers + * \author + * Beshr Al Nahas + * + */ + +#include +#include +#include +#include "contiki-conf.h" +#include "dev/uart0.h" +#include "uart-driver.h" + +/* Valid range for TXBUFSIZE and RXBUFSIZE: 16-2047 */ + +static unsigned char txbuf_data[UART_TX_BUFFER_SIZE]; +static unsigned char rxbuf_data[UART_RX_BUFFER_SIZE]; +static int (*uart0_input)(unsigned char c); + +uint8_t +uart0_active(void) +{ + return uart_driver_tx_in_progress(E_AHI_UART_0); +} +void +uart0_set_input(int + (*input)(unsigned char c)) +{ + uart0_input = input; + uart_driver_set_input(E_AHI_UART_0, uart0_input); +} +void +uart0_writeb(unsigned char c) +{ + uart_driver_write_buffered(E_AHI_UART_0, c); +} +void +uart0_init(uint8_t br) +{ + uart_driver_init(E_AHI_UART_0, br, txbuf_data, UART_TX_BUFFER_SIZE, rxbuf_data, UART_RX_BUFFER_SIZE, uart0_input); +} diff --git a/platform/jn516x/dev/uart0.h b/platform/jn516x/dev/uart0.h new file mode 100644 index 000000000..293950c5b --- /dev/null +++ b/platform/jn516x/dev/uart0.h @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2014, SICS Swedish ICT. + * 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 Institute 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 INSTITUTE 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 INSTITUTE 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. + * + * This file is part of the Contiki operating system. + * + */ + +/** + * \file + * UART0 drivers + * \author + * Beshr Al Nahas + * + */ + +#ifndef __UART0_H__ +#define __UART0_H__ + +#include +#include "contiki-conf.h" + +#define UART_DEFAULT_RX_BUFFER_SIZE 2047 +#if UART_XONXOFF_FLOW_CTRL +#define UART_DEFAULT_TX_BUFFER_SIZE 64 +#else +#define UART_DEFAULT_TX_BUFFER_SIZE 1281 +#endif +#ifdef UART_CONF_TX_BUFFER_SIZE +#define UART_TX_BUFFER_SIZE UART_CONF_TX_BUFFER_SIZE +#else +#define UART_TX_BUFFER_SIZE UART_DEFAULT_TX_BUFFER_SIZE +#endif +#ifdef UART_CONF_RX_BUFFER_SIZE +#define UART_RX_BUFFER_SIZE UART_CONF_RX_BUFFER_SIZE +#else +#define UART_RX_BUFFER_SIZE UART_DEFAULT_RX_BUFFER_SIZE +#endif +void uart0_set_input(int (*input)(unsigned char c)); +void uart0_writeb(unsigned char c); +void uart0_init(unsigned char br); + +#define uart0_write_direct(c) uart_driver_write_direct(E_AHI_UART_0, (c)) +#define uart0_disable_interrupts() uart_driver_disable_interrupts(E_AHI_UART_0) +#define uart0_enable_interrupts() uart_driver_enable_interrupts(E_AHI_UART_0) +#define uart0_restore_interrupts() uart_driver_restore_interrupts(E_AHI_UART_0) +#define uart0_store_interrupts() uart_driver_store_interrupts(E_AHI_UART_0) + +uint8_t uart0_active(void); + +#endif diff --git a/platform/jn516x/dev/uart1.c b/platform/jn516x/dev/uart1.c new file mode 100644 index 000000000..7f4c1fa8f --- /dev/null +++ b/platform/jn516x/dev/uart1.c @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2014, SICS Swedish ICT. + * 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 Institute 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 INSTITUTE 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 INSTITUTE 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. + * + * This file is part of the Contiki operating system. + * + */ + +/** + * \file + * UART1 drivers + * \author + * Beshr Al Nahas + * + */ + +#include +#include +#include +#include "contiki-conf.h" +#include "dev/uart1.h" +#include "uart-driver.h" + +static unsigned char txbuf_data[UART1_TX_BUFFER_SIZE]; +static unsigned char rxbuf_data[UART1_RX_BUFFER_SIZE]; +static int (*uart1_input)(unsigned char c); + +uint8_t +uart1_active(void) +{ + return uart_driver_tx_in_progress(E_AHI_UART_1); +} +void +uart1_set_input(int + (*input)(unsigned char c)) +{ + uart1_input = input; + uart_driver_set_input(E_AHI_UART_1, uart1_input); +} +void +uart1_writeb(unsigned char c) +{ + uart_driver_write_buffered(E_AHI_UART_1, c); +} +void +uart1_init(uint8_t br) +{ + uart_driver_init(E_AHI_UART_1, br, txbuf_data, UART1_TX_BUFFER_SIZE, rxbuf_data, UART1_RX_BUFFER_SIZE, uart1_input); +} diff --git a/platform/jn516x/dev/uart1.h b/platform/jn516x/dev/uart1.h new file mode 100644 index 000000000..2fdc207ca --- /dev/null +++ b/platform/jn516x/dev/uart1.h @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2014, SICS Swedish ICT. + * 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 Institute 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 INSTITUTE 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 INSTITUTE 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. + * + * This file is part of the Contiki operating system. + * + */ + +/** + * \file + * UART1 drivers + * \author + * Beshr Al Nahas + * + */ + +#ifndef __UART1_H__ +#define __UART1_H__ + +#include +#include "contiki-conf.h" + +/* Default buffer size + Valid range for TX_BUFFER_SIZE and RX_BUFFER_SIZE: 16-2047 */ +#define UART1_DEFAULT_RX_BUFFER_SIZE 16 +#define UART1_DEFAULT_TX_BUFFER_SIZE 16 + +/* Buffer size selection */ +#ifdef UART1_CONF_TX_BUFFER_SIZE +#define UART1_TX_BUFFER_SIZE UART1_CONF_TX_BUFFER_SIZE +#else +#define UART1_TX_BUFFER_SIZE UART1_DEFAULT_TX_BUFFER_SIZE +#endif + +#ifdef UART1_CONF_RX_BUFFER_SIZE +#define UART1_RX_BUFFER_SIZE UART1_CONF_RX_BUFFER_SIZE +#else +#define UART1_RX_BUFFER_SIZE UART1_DEFAULT_RX_BUFFER_SIZE +#endif + +void uart1_set_input(int (*input)(unsigned char c)); +void uart1_writeb(unsigned char c); +void uart1_init(unsigned char br); + +#define uart1_write_direct(c) uart_driver_write_direct(E_AHI_UART_1, (c)) +#define uart1_disable_interrupts() uart_driver_disable_interrupts(E_AHI_UART_1) +#define uart1_enable_interrupts() uart_driver_enable_interrupts(E_AHI_UART_1) +#define uart1_restore_interrupts() uart_driver_restore_interrupts(E_AHI_UART_1) +#define uart1_store_interrupts() uart_driver_store_interrupts(E_AHI_UART_1) + +uint8_t uart1_active(void); + +#endif diff --git a/platform/jn516x/dev/watchdog.c b/platform/jn516x/dev/watchdog.c new file mode 100644 index 000000000..395106fd3 --- /dev/null +++ b/platform/jn516x/dev/watchdog.c @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2014, SICS Swedish ICT. + * 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 Institute 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 INSTITUTE 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 INSTITUTE 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. + * + * This file is part of the Contiki operating system. + * + */ + +/** + * \file + * JN516X watchdog support. + * \author + * Beshr Al Nahas + * + */ + +#include "dev/watchdog.h" +#include "AppHardwareApi.h" + +/*---------------------------------------------------------------------------*/ +static int counter = 0; + +/*---------------------------------------------------------------------------*/ +void +watchdog_init(void) +{ + counter = 0; + watchdog_stop(); + /* enable WDT interrupt */ + vAHI_WatchdogException(1); +} +/*---------------------------------------------------------------------------*/ +void +watchdog_start(void) +{ + /* We setup the watchdog to reset the device after two seconds, + unless watchdog_periodic() is called. */ + counter--; + if(counter == 0) { + vAHI_WatchdogStart(9); /* about 8*2^(9-1)ms=2.048s timeout */ + } +} +/*---------------------------------------------------------------------------*/ +void +watchdog_periodic(void) +{ + /* This function is called periodically to restart the watchdog + timer. */ + vAHI_WatchdogRestart(); +} +/*---------------------------------------------------------------------------*/ +void +watchdog_stop(void) +{ + counter++; + if(counter == 1) { + vAHI_WatchdogStop(); + } +} +/*---------------------------------------------------------------------------*/ +void +watchdog_reboot(void) +{ + vAHI_SwReset(); +} +/*---------------------------------------------------------------------------*/ diff --git a/platform/jn516x/lib/log.c b/platform/jn516x/lib/log.c new file mode 100644 index 000000000..adf85ec1a --- /dev/null +++ b/platform/jn516x/lib/log.c @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2015, SICS Swedish ICT. + * 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. The name of the author may not be used to endorse or promote + * products derived from this software without specific prior + * written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. + * + * This file is part of the Contiki OS + * + */ + +#include +#include + +#include "net/ip/uip.h" +#include "sys/log.h" + +/*---------------------------------------------------------------------------*/ +#if LOG_CONF_ENABLED +void +log_message(char *m1, char *m2) +{ + printf("%s%s\n", m1, m2); +} +#endif /* LOG_CONF_ENABLED */ +/*---------------------------------------------------------------------------*/ +#if UIP_LOGGING +void +uip_log(char *m) +{ + printf("uip_log: %s\n", m); +} +#endif /* UIP_LOGGING */ +/*---------------------------------------------------------------------------*/ diff --git a/platform/jn516x/lib/ringbufindex.c b/platform/jn516x/lib/ringbufindex.c new file mode 100644 index 000000000..0b2149ff7 --- /dev/null +++ b/platform/jn516x/lib/ringbufindex.c @@ -0,0 +1,149 @@ +/* + * Copyright (c) 2015, SICS Swedish ICT. + * 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 Institute 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 INSTITUTE 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 INSTITUTE 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. + * + * This file is part of the Contiki operating system. + * + */ + +/** + * \file + * ringbufindex library. Implements basic support for ring buffers + * of any type, as opposed to the core/lib/ringbuf module which + * is only for byte arrays. Simply returns index in the ringbuf + * rather than actual elements. The ringbuf size must be power of two. + * Like the original ringbuf, this module implements atomic put and get. + * \author + * Simon Duquennoy + * based on Contiki's core/lib/ringbuf library by Adam Dunkels + */ + +#include +#include "lib/ringbufindex.h" + +/* Initialize a ring buffer. The size must be a power of two */ +void +ringbufindex_init(struct ringbufindex *r, uint8_t size) +{ + r->mask = size - 1; + r->put_ptr = 0; + r->get_ptr = 0; +} +/* Put one element to the ring buffer */ +int +ringbufindex_put(struct ringbufindex *r) +{ + /* Check if buffer is full. If it is full, return 0 to indicate that + the element was not inserted. + + XXX: there is a potential risk for a race condition here, because + the ->get_ptr field may be written concurrently by the + ringbufindex_get() function. To avoid this, access to ->get_ptr must + be atomic. We use an uint8_t type, which makes access atomic on + most platforms, but C does not guarantee this. + */ + if(((r->put_ptr - r->get_ptr) & r->mask) == r->mask) { + return 0; + } + r->put_ptr = (r->put_ptr + 1) & r->mask; + return 1; +} +/* Check if there is space to put an element. + * Return the index where the next element is to be added */ +int +ringbufindex_peek_put(const struct ringbufindex *r) +{ + /* Check if there are bytes in the buffer. If so, we return the + first one. If there are no bytes left, we return -1. + */ + if(((r->put_ptr - r->get_ptr) & r->mask) == r->mask) { + return -1; + } + return (r->put_ptr + 1) & r->mask; +} +/* Remove the first element and return its index */ +int +ringbufindex_get(struct ringbufindex *r) +{ + int get_ptr; + + /* Check if there are bytes in the buffer. If so, we return the + first one and increase the pointer. If there are no bytes left, we + return -1. + + XXX: there is a potential risk for a race condition here, because + the ->put_ptr field may be written concurrently by the + ringbufindex_put() function. To avoid this, access to ->get_ptr must + be atomic. We use an uint8_t type, which makes access atomic on + most platforms, but C does not guarantee this. + */ + if(((r->put_ptr - r->get_ptr) & r->mask) > 0) { + get_ptr = r->get_ptr; + r->get_ptr = (r->get_ptr + 1) & r->mask; + return get_ptr; + } else { + return -1; + } +} +/* Return the index of the first element + * (which will be removed if calling ringbufindex_peek) */ +int +ringbufindex_peek_get(const struct ringbufindex *r) +{ + /* Check if there are bytes in the buffer. If so, we return the + first one. If there are no bytes left, we return -1. + */ + if(((r->put_ptr - r->get_ptr) & r->mask) > 0) { + return (r->get_ptr + 1) & r->mask; + } else { + return -1; + } +} +/* Return the ring buffer size */ +int +ringbufindex_size(const struct ringbufindex *r) +{ + return r->mask + 1; +} +/* Return the number of elements currently in the ring buffer */ +int +ringbufindex_elements(const struct ringbufindex *r) +{ + return (r->put_ptr - r->get_ptr) & r->mask; +} +/* Is the ring buffer full? */ +int +ringbufindex_full(const struct ringbufindex *r) +{ + return ((r->put_ptr - r->get_ptr) & r->mask) == r->mask; +} +/* Is the ring buffer empty? */ +int +ringbufindex_empty(const struct ringbufindex *r) +{ + return ringbufindex_elements(r) == 0; +} diff --git a/platform/jn516x/lib/ringbufindex.h b/platform/jn516x/lib/ringbufindex.h new file mode 100644 index 000000000..c39f99d18 --- /dev/null +++ b/platform/jn516x/lib/ringbufindex.h @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2015, SICS Swedish ICT. + * 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 Institute 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 INSTITUTE 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 INSTITUTE 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. + * + * This file is part of the Contiki operating system. + * + */ + +/** + * \file + * Header file for the ringbufindex library + * \author + * Simon Duquennoy + */ + +#ifndef __RINGBUFINDEX_H__ +#define __RINGBUFINDEX_H__ + +#include "contiki-conf.h" + +struct ringbufindex { + uint8_t mask; + /* These must be 8-bit quantities to avoid race conditions. */ + uint8_t put_ptr, get_ptr; +}; + +/* Initialize a ring buffer. The size must be a power of two */ +void ringbufindex_init(struct ringbufindex *r, uint8_t size); +/* Put one element to the ring buffer */ +int ringbufindex_put(struct ringbufindex *r); +/* Check if there is space to put an element. + * Return the index where the next element is to be added */ +int ringbufindex_peek_put(const struct ringbufindex *r); +/* Remove the first element and return its index */ +int ringbufindex_get(struct ringbufindex *r); +/* Return the index of the first element + * (which will be removed if calling ringbufindex_peek) */ +int ringbufindex_peek_get(const struct ringbufindex *r); +/* Return the ring buffer size */ +int ringbufindex_size(const struct ringbufindex *r); +/* Return the number of elements currently in the ring buffer */ +int ringbufindex_elements(const struct ringbufindex *r); +/* Is the ring buffer full? */ +int ringbufindex_full(const struct ringbufindex *r); +/* Is the ring buffer empty? */ +int ringbufindex_empty(const struct ringbufindex *r); + +#endif /* __RINGBUFINDEX_H__ */ diff --git a/platform/jn516x/lib/slip.c b/platform/jn516x/lib/slip.c new file mode 100644 index 000000000..31828e7e3 --- /dev/null +++ b/platform/jn516x/lib/slip.c @@ -0,0 +1,447 @@ +/* + * Copyright (c) 2014, SICS Swedish ICT. + * 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 Institute 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 INSTITUTE 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 INSTITUTE 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. + * + * This file is part of the Contiki operating system. + * + */ + +/** + * \file + * Alternative implementation for SLIP: + * 1. Accepts more than two packet + * 2. Disables UART rx interrupt when buffer is full + * (thus invoking flow control if configured) + * \author + * Niklas Finne + * Beshr Al Nahas + * + */ + +#include "contiki.h" + +#include +#include "net/ip/uip.h" +#include "net/ipv4/uip-fw.h" +#define BUF ((struct uip_tcpip_hdr *)&uip_buf[UIP_LLH_LEN]) + +#include "dev/slip.h" + +#define DEBUG 0 +#if DEBUG +#include +#define PRINTF(...) printf(__VA_ARGS__) +#define PUTCHAR(X) do { putchar(X); putchar('\n'); } while(0) +#else +#define PRINTF(...) do {} while(0) +#define PUTCHAR(X) do {} while(0) +#endif + +#define SLIP_END 0300 +#define SLIP_ESC 0333 +#define SLIP_ESC_END 0334 +#define SLIP_ESC_ESC 0335 +#define SLIP_NEUTRAL 0 /* means: none of the above */ +#define SLIP_ESC_XON 0336 +#define SLIP_ESC_XOFF 0337 +#define XON ((unsigned char)17) +#define XOFF ((unsigned char)19) +#if UART_XONXOFF_FLOW_CTRL +volatile unsigned char xonxoff_state = XON; +#endif /* UART_XONXOFF_FLOW_CTRL */ + +PROCESS(slip_process, "SLIP driver"); + +#include "dev/uart0.h" +#define STORE_UART_INTERRUPTS uart0_store_interrupts +#define RESTORE_UART_INTERRUPTS uart0_restore_interrupts +#define DISABLE_UART_INTERRUPTS uart0_disable_interrupts +#define ENABLE_UART_INTERRUPTS uart0_enable_interrupts + +/** + * @brief A block of code may be made atomic by wrapping it with this + * macro. Something which is atomic cannot be interrupted by interrupts. + */ +/* A specific ATMOIC that disables UART interrupts only */ +#define ATOMIC(blah) \ + { \ + /* STORE_UART_INTERRUPTS(); */ \ + DISABLE_UART_INTERRUPTS(); \ + { blah } \ + /* RESTORE_UART_INTERRUPTS(); */ \ + ENABLE_UART_INTERRUPTS(); \ + } + +/* A generic ATMOIC that disables all interrupts */ +#define GLOBAL_ATOMIC(blah) \ + { \ + MICRO_DISABLE_INTERRUPTS(); \ + { blah } \ + MICRO_ENABLE_INTERRUPTS(); \ + } + +#if 1 +#define SLIP_STATISTICS(statement) +#else +uint16_t slip_drop_bytes, slip_overflow, slip_error_drop; +/* No used in this file */ +uint16_t slip_rubbish, slip_twopackets, slip_ip_drop; +unsigned long slip_received, slip_frames; +#define SLIP_STATISTICS(statement) statement +#endif + +/* Must be at least one byte larger than UIP_BUFSIZE (for SLIP_END)! */ +#ifdef SLIP_CONF_RX_BUFSIZE +#define RX_BUFSIZE SLIP_CONF_RX_BUFSIZE + +#if RX_BUFSIZE < (UIP_BUFSIZE - UIP_LLH_LEN + 16) +#error "SLIP_CONF_RX_BUFSIZE too small for UIP_BUFSIZE" +#endif + +#else +#define RX_BUFSIZE (UIP_CONF_BUFFER_SIZE * 2) +#endif + +/* + * Variables begin and end manage the buffer space in a cyclic + * fashion. The first used byte is at begin and end is one byte past + * the last. I.e. [begin, end) is the actively used space. + */ + +static volatile uint16_t begin, end, end_counter; +static uint8_t rxbuf[RX_BUFSIZE]; +static volatile uint8_t is_dropping = 0; +static volatile uint8_t is_full = 0; + +static void (*input_callback)(void) = NULL; +/*---------------------------------------------------------------------------*/ +void +slip_set_input_callback(void (*c)(void)) +{ + input_callback = c; +} +static void +slip_write_char(uint8_t c) +{ + /* Escape SLIP control characters */ + if(c == SLIP_END) { + slip_arch_writeb(SLIP_ESC); + c = SLIP_ESC_END; + } else if(c == SLIP_ESC) { + slip_arch_writeb(SLIP_ESC); + c = SLIP_ESC_ESC; + } +#if UART_XONXOFF_FLOW_CTRL + /* Escape XON/XOFF characters */ + else if(c == XON) { + slip_arch_writeb(SLIP_ESC); + c = SLIP_ESC_XON; + } else if(c == XOFF) { + slip_arch_writeb(SLIP_ESC); + c = SLIP_ESC_XOFF; + } +#endif /* UART_XONXOFF_FLOW_CTRL */ + slip_arch_writeb(c); +} +/*---------------------------------------------------------------------------*/ +uint8_t +slip_write(const void *_ptr, int len) +{ + const uint8_t *ptr = _ptr; + uint16_t i; + uint8_t c; + + slip_arch_writeb(SLIP_END); + + for(i = 0; i < len; ++i) { + c = *ptr++; + slip_write_char(c); + } + slip_arch_writeb(SLIP_END); + + return len; +} +/*---------------------------------------------------------------------------*/ +/* slip_send: forward (IPv4) packets with {UIP_FW_NETIF(..., slip_send)} + * was used in slip-bridge.c + */ +uint8_t +slip_send(void) +{ + uint16_t i; + uint8_t *ptr; + uint8_t c; + + slip_arch_writeb(SLIP_END); + + ptr = &uip_buf[UIP_LLH_LEN]; + for(i = 0; i < uip_len; ++i) { + if(i == UIP_TCPIP_HLEN) { + ptr = (uint8_t *)uip_appdata; + } + c = *ptr++; + slip_write_char(c); + } + slip_arch_writeb(SLIP_END); + + return UIP_FW_OK; +} +/*---------------------------------------------------------------------------*/ +static void +rxbuf_init(void) +{ + begin = end = end_counter = 0; + is_dropping = 0; +} +/*---------------------------------------------------------------------------*/ +/* Upper half does the polling. */ +static uint16_t +slip_poll_handler(uint8_t *outbuf, uint16_t blen) +{ + uint16_t len; + uint16_t pos; + uint8_t c; + uint8_t state; + + if(end_counter == 0 && is_full == 0) { + return 0; + } + for(len = 0, pos = begin, state = c = SLIP_NEUTRAL; + len < blen + 1; /* +1 for SLIP_END! */ + ) { + + c = rxbuf[pos++]; + + if(pos == RX_BUFSIZE) { + /* Circular buffer: warp around */ + pos = 0; + } + if(c == SLIP_END) { + /* End of packet */ + break; + } + if(len >= blen) { + /* End of buffer with no SLIP_END + * ==> something wrong happened */ + break; + } + switch(c) { + case SLIP_ESC: + state = SLIP_ESC; + break; + case SLIP_ESC_END: + if(state == SLIP_ESC) { + outbuf[len++] = SLIP_END; + state = SLIP_NEUTRAL; + } else { + outbuf[len++] = c; + } break; + case SLIP_ESC_ESC: + if(state == SLIP_ESC) { + outbuf[len++] = SLIP_ESC; + state = SLIP_NEUTRAL; + } else { + outbuf[len++] = c; + } break; +#if UART_XONXOFF_FLOW_CTRL + case SLIP_ESC_XON: + if(state == SLIP_ESC) { + outbuf[len++] = XON; + state = SLIP_NEUTRAL; + } else { + outbuf[len++] = c; + } break; + case SLIP_ESC_XOFF: + if(state == SLIP_ESC) { + outbuf[len++] = XOFF; + state = SLIP_NEUTRAL; + } else { + outbuf[len++] = c; + } break; +#endif /* UART_XONXOFF_FLOW_CTRL */ + default: + outbuf[len++] = c; + state = SLIP_NEUTRAL; + break; + } + } + + /* Update counters */ + if(c == SLIP_END) { + ATOMIC(begin = pos; + if(end_counter) { + end_counter--; + } + ) + PUTCHAR('P'); + } else { + /* Something went wrong, no SLIP_END found, drop everything */ + ATOMIC(rxbuf_init(); + is_dropping = 1; + ) + SLIP_STATISTICS(slip_error_drop++); + len = 0; + PRINTF("SLIP: *** out of sync!\n"); + } + + if(end_counter > 0) { + /* One more packet is buffered, need to be polled again! */ + process_poll(&slip_process); + } + return len; +} +/*---------------------------------------------------------------------------*/ +PROCESS_THREAD(slip_process, ev, data) +{ + PROCESS_BEGIN(); + + rxbuf_init(); + + while(1) { + PROCESS_YIELD_UNTIL(ev == PROCESS_EVENT_POLL); + + /* Move packet from rxbuf to buffer provided by uIP. */ + uip_len = slip_poll_handler(&uip_buf[UIP_LLH_LEN], + UIP_BUFSIZE - UIP_LLH_LEN); + + PRINTF("SLIP: recv bytes %u frames RECV: %u. is_full %u, is_dropping %u.\n", + end_counter, uip_len, is_full, is_dropping); + + /* We have free space now, resume slip RX */ + if(is_full) { + is_full = 0; + ENABLE_UART_INTERRUPTS(); + } + + if(uip_len > 0) { + if(input_callback) { + input_callback(); + } +#ifdef SLIP_CONF_TCPIP_INPUT + SLIP_CONF_TCPIP_INPUT(); +#else + tcpip_input(); +#endif + } + } + + PROCESS_END(); +} +/*---------------------------------------------------------------------------*/ +/* Return status from slip_input_byte: + * -1 means RX buffer overflow ==> stop reading + * 0 means do not exit power saving mode + * 1 means exit power saving mode + **/ +int +slip_input_byte(unsigned char c) +{ + static int in_frame = 0; + uint16_t next, next_next; + int error_return_code = is_full ? -1 : 0; + int success_return_code = is_full ? -1 : 1; + + SLIP_STATISTICS(slip_received++); + +#if UART_XONXOFF_FLOW_CTRL + if(c == XOFF || c == XON) { + xonxoff_state = c; + return 1; + } else { + /* ANY char would be XON */ + xonxoff_state = XON; + } +#endif /* UART_XONXOFF_FLOW_CTRL */ + + if(is_dropping) { + /* Make sure to drop full frames when overflow or + * out of sync happens */ + if(c != SLIP_END) { + SLIP_STATISTICS(slip_drop_bytes++); + } else { + is_dropping = 0; + in_frame = 0; + } + return error_return_code; + } + + if(!in_frame && c == SLIP_END) { + /* Ignore slip end when not receiving frame */ + return error_return_code; + /* increment and wrap */ + } + next = end + 1; + if(next >= RX_BUFSIZE) { + next = 0; + } + next_next = next + 1; + if(next_next >= RX_BUFSIZE) { + next_next = 0; + /* Next byte will overflow. Stop accepting. */ + } + if(next_next == begin) { + is_full = 1; + /* disable UART interrupts */ + DISABLE_UART_INTERRUPTS(); + process_poll(&slip_process); + } + + /* Buffer is full. We can't store anymore. + * Shall not happen normally, + * because of overflow protection above. */ + if(next == begin) { + is_dropping = 1; + SLIP_STATISTICS(slip_overflow++); + is_full = 1; + /* disable UART interrupts */ + DISABLE_UART_INTERRUPTS(); + process_poll(&slip_process); + return -1; + } + + rxbuf[end] = c; + end = next; + in_frame = 1; + + if(c == SLIP_END) { + in_frame = 0; + end_counter++; + SLIP_STATISTICS(slip_frames++); + process_poll(&slip_process); + return success_return_code; + } + return error_return_code; +} +/*---------------------------------------------------------------------------*/ +#if SLIP_BRIDGE_CONF_NO_PUTCHAR +int +putchar(int c) +{ + uart0_writeb(c); + return 1; +} +#endif diff --git a/platform/jn516x/lib/sprintf.c b/platform/jn516x/lib/sprintf.c new file mode 100644 index 000000000..8dbfa10a0 --- /dev/null +++ b/platform/jn516x/lib/sprintf.c @@ -0,0 +1,235 @@ +/* + File: printf.c + + Copyright (c) 2004,2008 Kustaa Nyholm / SpareTimeLabs + + All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, + are permitted provided that the following conditions are met: + + Redistributions of source code must retain the above copyright notice, this list + of conditions and the following disclaimer. + + 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. + + Neither the name of the Kustaa Nyholm or SpareTimeLabs 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 COPYRIGHT HOLDERS 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 COPYRIGHT HOLDER 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. + + */ + +/* + * This is BSD code obtained from http://www.sparetimelabs.com/printfrevisited/index.html + * From the web page: + * "The code is GPL and BSD lincensed, download the BSD licensed version from the link + * above or use the GPL licensed code from this page below." + * + * modified by Beshr Al Nahas and Simon Duquennoy + */ + +#include "contiki-conf.h" +#include +#include +#include +#include +#include +#include "dev/uart0.h" + +static char *bf, buf[14], uc, zs; +static unsigned int num; + +static void +out(char c) +{ + *bf++ = c; +} +static void +outDgt(char dgt) +{ + out(dgt + (dgt < 10 ? '0' : (uc ? 'A' : 'a') - 10)); + zs = 1; +} +static void +divOut(unsigned int div) +{ + unsigned char dgt = 0; + while(num >= div) { + num -= div; + dgt++; + } + if(zs || dgt > 0) { + outDgt(dgt); + } +} +int +vsnprintf(char *str, size_t n, const char *fmt, __VALIST va) +{ + char ch, *p, *str_orig = str; + char next_ch; + + while((ch = *fmt++) && str - str_orig < n) { + if(ch != '%') { + *str++ = ch; + } else { + char lz = 0; + char w = 0; + ch = *(fmt++); + if(ch == '0') { + ch = *(fmt++); + lz = 1; + } + if(ch >= '0' && ch <= '9') { + w = 0; + while(ch >= '0' && ch <= '9') { + w = (((w << 2) + w) << 1) + ch - '0'; + ch = *fmt++; + } + } + bf = buf; + p = bf; + zs = 0; +start_format: + next_ch = *fmt; + switch(ch) { + case 0: + goto abort; + case 'l': + if(next_ch == 'x' + || next_ch == 'X' + || next_ch == 'u' + || next_ch == 'd') { + ch = *(fmt++); + goto start_format; + } + case 'u': + case 'd': + num = va_arg(va, unsigned int); + if(ch == 'd' && (int)num < 0) { + num = -(int)num; + out('-'); + } + divOut(1000000000); + divOut(100000000); + divOut(10000000); + divOut(1000000); + divOut(100000); + divOut(10000); + divOut(1000); + divOut(100); + divOut(10); + outDgt(num); + break; + case 'p': + case 'x': + case 'X': + uc = ch == 'X'; + num = va_arg(va, unsigned int); + /* divOut(0x100000000UL); */ + divOut(0x10000000); + divOut(0x1000000); + divOut(0x100000); + divOut(0x10000); + divOut(0x1000); + divOut(0x100); + divOut(0x10); + outDgt(num); + break; + case 'c': + out((char)(va_arg(va, int))); + break; + case 's': + p = va_arg(va, char *); + break; + case '%': + out('%'); + default: + break; + } + *bf = 0; + bf = p; + + while(*bf++ && w > 0) { + w--; + } + while(w-- > 0) { + if(str - str_orig < n) { + *str++ = lz ? '0' : ' '; + } else { + goto abort; + } + } + while((ch = *p++)) { + if(str - str_orig < n) { + *str++ = ch; + } else { + goto abort; + } + } + } + } + +abort: + if(str - str_orig < n) { + *str = '\0'; + } else { + *(--str) = '\0'; + } return str - str_orig; +} +int +sprintf(char *str, const char *fmt, ...) +{ + int m; + __VALIST va; + va_start(va, fmt); + m = vsnprintf(str, 0xffffffff, fmt, va); + va_end(va); + return m; +} +int +snprintf(char *str, size_t n, const char *fmt, ...) +{ + int m; + __VALIST va; + va_start(va, fmt); + m = vsnprintf(str, n, fmt, va); + va_end(va); + return m; +} +int +printf(const char *fmt, ...) +{ + int m, i; + char str[256]; + __VALIST va; + va_start(va, fmt); + m = vsnprintf(str, sizeof(str), fmt, va); + va_end(va); + for(i = 0; i < m; i++) { + putchar(str[i]); + } + return m; +} +int +puts(const char *s) +{ + char c; + while(c = *s++) { + putchar(c); + } + putchar('\n'); + return strlen(s); +} diff --git a/platform/jn516x/platform-conf.h b/platform/jn516x/platform-conf.h new file mode 100644 index 000000000..60497645f --- /dev/null +++ b/platform/jn516x/platform-conf.h @@ -0,0 +1,263 @@ +/* + * Copyright (c) 2015, SICS Swedish ICT. + * 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 Institute 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 INSTITUTE 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 INSTITUTE 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. + * + * This file is part of the Contiki operating system. + * + */ + +#ifndef PLATFORM_CONF_H +#define PLATFORM_CONF_H + +#include +#include + +#undef putchar + +/* Delay between GO signal and SFD + * Measured 153us between GO and preamble. Add 5 bytes (preamble + SFD) air time: 153+5*32 = 313 */ +#define RADIO_DELAY_BEFORE_TX ((unsigned)US_TO_RTIMERTICKS(313)) +/* Delay between GO signal and start listening + * Measured 104us: between GO signal and start listening */ +#define RADIO_DELAY_BEFORE_RX ((unsigned)US_TO_RTIMERTICKS(104)) + +/* Micromac configuration */ + +#ifndef MIRCOMAC_CONF_BUF_NUM +#define MIRCOMAC_CONF_BUF_NUM 2 +#endif + +#ifndef MICROMAC_CONF_CHANNEL +#define MICROMAC_CONF_CHANNEL 26 +#endif + +#ifdef RF_CHANNEL +#define MICROMAC_CONF_CHANNEL RF_CHANNEL +#endif + +/* Timer conversion + * RTIMER 16M = 256 * 62500(RADIO) == 2^8 * 62500 */ +#define RADIO_TO_RTIMER(X) ((rtimer_clock_t)((X) << (int32_t)8L)) + +#define DR_11744_DIO2 12 +#define DR_11744_DIO3 13 +#define DR_11744_DIO4 14 +#define DR_11744_DIO5 15 +#define DR_11744_DIO6 16 +#define DR_11744_DIO7 17 + +#define TSCH_DEBUG 0 + +#if TSCH_DEBUG +#define TSCH_DEBUG_INIT() do { \ + vAHI_DioSetDirection(0, (1 << DR_11744_DIO2) | (1 << DR_11744_DIO3) | (1 << DR_11744_DIO4) | (1 << DR_11744_DIO5) | (1 << DR_11744_DIO6) | (1 << DR_11744_DIO7)); \ + vAHI_DioSetOutput(0, (1 << DR_11744_DIO2) | (1 << DR_11744_DIO3) | (1 << DR_11744_DIO4) | (1 << DR_11744_DIO5) | (1 << DR_11744_DIO6) | (1 << DR_11744_DIO7)); } while(0); +#define TSCH_DEBUG_INTERRUPT() do { \ + static dio_state = 0; \ + dio_state = !dio_state; \ + if(dio_state) { \ + vAHI_DioSetOutput((1 << DR_11744_DIO2), 0); \ + } else { \ + vAHI_DioSetOutput(0, (1 << DR_11744_DIO2)); \ + } \ +} while(0); +#define TSCH_DEBUG_RX_EVENT() do { \ + static dio_state = 0; \ + dio_state = !dio_state; \ + if(dio_state) { \ + vAHI_DioSetOutput((1 << DR_11744_DIO4), 0); \ + } else { \ + vAHI_DioSetOutput(0, (1 << DR_11744_DIO4)); \ + } \ +} while(0); +#define TSCH_DEBUG_TX_EVENT() do { \ + static dio_state = 0; \ + dio_state = !dio_state; \ + if(dio_state) { \ + vAHI_DioSetOutput((1 << DR_11744_DIO5), 0); \ + } else { \ + vAHI_DioSetOutput(0, (1 << DR_11744_DIO5)); \ + } \ +} while(0); +#define TSCH_DEBUG_SLOT_START() do { \ + static dio_state = 0; \ + dio_state = !dio_state; \ + if(dio_state) { \ + vAHI_DioSetOutput((1 << DR_11744_DIO3), 0); \ + } else { \ + vAHI_DioSetOutput(0, (1 << DR_11744_DIO3)); \ + } \ +} while(0); +#define TSCH_DEBUG_SLOT_END() +#endif /* TSCH_DEBUG */ + +#ifndef BAUD2UBR +#define BAUD2UBR(X) (X) +#endif /* BAUD2UBR */ + +/* UART baud rates */ +#define UART_RATE_4800 0 +#define UART_RATE_9600 1 +#define UART_RATE_19200 2 +#define UART_RATE_38400 3 +#define UART_RATE_76800 4 +#define UART_RATE_115200 5 +#define UART_RATE_230400 6 +#define UART_RATE_460800 7 +#define UART_RATE_500000 8 +#define UART_RATE_576000 9 +#define UART_RATE_921600 10 +#define UART_RATE_1000000 11 + +#define PLATFORM_HAS_LEDS 1 +#define PLATFORM_HAS_BUTTON (SENSOR_BOARD_DR1174 == 1) +#define PLATFORM_HAS_LIGHT (SENSOR_BOARD_DR1175 == 1) +#define PLATFORM_HAS_HT (SENSOR_BOARD_DR1175 == 1) +#define PLATFORM_HAS_POT (SENSOR_BOARD_DR1199 == 1) +#define PLATFORM_HAS_BATTERY 0 /* sensor driver not implemented */ +#define PLATFORM_HAS_SHT11 0 +#define PLATFORM_HAS_RADIO 1 + +/* CPU target speed in Hz + * RTIMER and peripherals clock is F_CPU/2 */ +#define F_CPU 32000000UL + +/* LED ports */ +/* + #define LEDS_PxDIR P5DIR + #define LEDS_PxOUT P5OUT + #define LEDS_CONF_RED 0x10 + #define LEDS_CONF_GREEN 0x20 + #define LEDS_CONF_YELLOW 0x40 + #define JENNIC_CONF_BUTTON_PIN (IRQ_DIO9|IRQ_DIO10) + */ + +#define CC_CONF_REGISTER_ARGS 1 +#define CC_CONF_FUNCTION_POINTER_ARGS 1 +#define CC_CONF_FASTCALL +#define CC_CONF_VA_ARGS 1 +#define CC_CONF_INLINE inline + +#define CCIF +#define CLIF + +#ifdef HAVE_STDINT_H +#include +#else +#ifndef uint8_t +typedef unsigned char uint8_t; +typedef unsigned short uint16_t; +typedef unsigned long uint32_t; +typedef signed char int8_t; +typedef short int16_t; +typedef long int32_t; +typedef unsigned long long uint64_t; +typedef long long int64_t; +#endif +#endif /* !HAVE_STDINT_H */ + +/* Types for clocks and uip_stats */ +typedef uint16_t uip_stats_t; +typedef uint32_t clock_time_t; + +/* Core rtimer.h defaults to 16 bit timer unless RTIMER_CLOCK_LT is defined */ +typedef uint32_t rtimer_clock_t; +#define RTIMER_CLOCK_LT(a, b) ((int32_t)((a) - (b)) < 0) +/* 10ms timer tick */ +#define CLOCK_CONF_SECOND 100 + +/* Shall we calibrate the DCO periodically? */ +#define DCOSYNCH_CONF_ENABLED 1 + +/* How often shall we attempt to calibrate DCO? + * PS: It should be calibrated upon temperature changes, + * but the naive approach of periodic calibration is fine too */ +#ifndef DCOSYNCH_PERIOD +#define DCOSYNCH_PERIOD (5 * 60) +#endif /* VCO_CALIBRATION_INTERVAL */ + +/* Disable UART HW flow control */ +#ifndef UART_HW_FLOW_CTRL +#define UART_HW_FLOW_CTRL 0 +#endif /* UART_HW_FLOW_CTRL */ + +/* Disable UART SW flow control */ +#ifndef UART_XONXOFF_FLOW_CTRL +#define UART_XONXOFF_FLOW_CTRL 1 +#endif /* UART_XONXOFF_FLOW_CTRL */ + +#ifndef UART_BAUD_RATE +#define UART_BAUD_RATE UART_RATE_1000000 +#endif /* UART_BAUD_RATE */ + +#ifndef UART1_BAUD_RATE +#define UART1_BAUD_RATE UART_RATE_1000000 +#endif +#define ENABLE_ADVANCED_BAUD_SELECTION (UART_BAUD_RATE > UART_RATE_115200) + +/* Set this to zero only if we are using SLIP */ +#ifndef SLIP_BRIDGE_CONF_NO_PUTCHAR +#define SLIP_BRIDGE_CONF_NO_PUTCHAR 1 +#endif /* SLIP_BRIDGE_CONF_NO_PUTCHAR */ + +/* Enable this to get the 32.768kHz oscillator */ +#ifndef USE_EXTERNAL_OSCILLATOR +#define USE_EXTERNAL_OSCILLATOR 0 +#endif /* USE_EXTERNAL_OSCILLATOR */ + +/* Extension of LED definitions from leds.h for various JN516x dev boards +JN516x Dongle: + LEDS_RED Red LED on dongle + LEDS_GREEN Green LED on dongle + Note: Only one LED can be switch on at the same time + +DR1174-only: + LEDS_GP0 LED D3 on DR1174 + LEDS_GP1 LED D6 on DR1174 + +DR1174+DR1199: + LEDS_RED LED D1 on DR1199 + LEDS_GREEN LED D2 on DR1199 + LEDS_BLUE LED D3 on DR1199 + LEDS_GP0 LED D3 on DR1174 + LEDS_GP1 LED D6 on DR1174 + +DR1174+DR1175: + LEDS_RED Red led in RGB-led with level control on DR1175 + LEDS_GREEN Green led in RGB-led with level control on DR1175 + LEDS_BLUE Blue led in RGB-led with level control on DR1175 + LEDS_WHITE White power led with level control on DR1175 + LEDS_GP0 LEDS D3 on DR1174 + LEDS_GP1 LEDS D6 on DR1174 +*/ +#define LEDS_WHITE 8 +#define LEDS_GP0 16 +#define LEDS_GP1 32 +#define LEDS_GP2 64 +#define LEDS_GP3 128 +#define LEDS_CONF_ALL 255 +#endif /* PLATFORM_CONF_H */ diff --git a/regression-tests/22-compile-nxp-ports/Makefile b/regression-tests/22-compile-nxp-ports/Makefile new file mode 100644 index 000000000..7ff68eaef --- /dev/null +++ b/regression-tests/22-compile-nxp-ports/Makefile @@ -0,0 +1,16 @@ +EXAMPLESDIR=../../examples +TOOLSDIR=../../tools + +# build jn516x examples, covering IPv6, RPL, CoAP, Rime, Nullrdc, Contikimac +EXAMPLES = \ +jn516x/dr1175-sensors/jn516x \ +jn516x/rime/jn516x \ +jn516x/rpl/border-router/jn516x \ +jn516x/rpl/node/jn516x \ +jn516x/rpl/coap-dongle-node/jn516x \ +jn516x/rpl/coap-dr1175-node/jn516x \ +jn516x/rpl/coap-dr1199-node/jn516x + +TOOLS= + +include ../Makefile.compile-test diff --git a/tools/jn516x/JennicModuleProgrammer b/tools/jn516x/JennicModuleProgrammer new file mode 100644 index 000000000..eef29c284 Binary files /dev/null and b/tools/jn516x/JennicModuleProgrammer differ diff --git a/tools/jn516x/Makefile b/tools/jn516x/Makefile new file mode 100644 index 000000000..be3caa44b --- /dev/null +++ b/tools/jn516x/Makefile @@ -0,0 +1,25 @@ +ifndef HOST_OS + ifeq ($(OS),Windows_NT) + HOST_OS := Windows + else + HOST_OS := $(shell uname) + endif +endif + +ifeq ($(HOST_OS),Windows) + SERIALDUMP = serialdump-windows +endif + +ifeq ($(HOST_OS),Darwin) + SERIALDUMP = serialdump-macos +endif + +ifndef SERIALDUMP + # Assume Linux + SERIALDUMP = serialdump-linux +endif + +all: $(SERIALDUMP) + +$(SERIALDUMP): serialdump.c + $(CC) -O2 -o $@ $< diff --git a/tools/jn516x/mote-list.py b/tools/jn516x/mote-list.py new file mode 100644 index 000000000..170b04fdb --- /dev/null +++ b/tools/jn516x/mote-list.py @@ -0,0 +1,94 @@ +#!/usr/bin/python + +# Copyright (c) 2015, SICS Swedish ICT +# 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 Institute 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 INSTITUTE 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 INSTITUTE 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. +# +# This file is part of the Contiki operating system. +# + +import sys, os, platform +import multiprocessing + +# detect the operating system +sysname = platform.system() +if "Linux" in sysname: + IS_WINDOWS = False + FLASH_PROGRAMMER_DEFAULT_PATH = "/usr/jn-toolchain/tools/flashprogrammer/JennicModuleProgrammer" + import motelist_lib.linux_motelist_impl as motelist_impl # @UnusedImport + +elif ("Win" in sysname) or ("NT" in sysname): + IS_WINDOWS = True + FLASH_PROGRAMMER_DEFAULT_PATH = 'C:\\NXP\\bstudio_nxp\\sdk\\JN-SW-4163\\Tools\\flashprogrammer\\FlashCLI.exe' + import motelist_lib.windows_motelist_impl as motelist_impl # @Reimport @UnusedImport + +else: + print ("OS ('{}') is not supported".format(os.name)) + + +def main(): + # use the default location + flash_programmer = FLASH_PROGRAMMER_DEFAULT_PATH + if len(sys.argv) > 2: + flash_programmer=sys.argv[1] + + serial_dumper = "" + if len(sys.argv) > 3: + serial_dumper=sys.argv[3] + + motes = motelist_impl.list_motes(flash_programmer) + if motes: + motes.sort() + print 'Found %d JN516X motes at:' %(len(motes)) + motes_str = '' + for m in motes: + motes_str += "%s " %(str(m)) + print motes_str + + firmware_file='#' + if len(sys.argv) > 2: + firmware_file = sys.argv[2] + elif len(sys.argv) > 1: + firmware_file = sys.argv[1] + + if firmware_file[0] == '\\': + firmware_file = firmware_file[1:] + + if firmware_file not in ['#', '!', '?', '%']: + print '\nBatch programming all connected motes...\n' + motelist_impl.program_motes(flash_programmer, motes, firmware_file) + elif firmware_file == '?' or firmware_file == '!': + should_display_mac_list = (firmware_file == '!') + motelist_impl.print_info(flash_programmer, motes, should_display_mac_list) + elif firmware_file == '%': + print '\nLogging from all connected motes...\n' + motelist_impl.serialdump_ports(flash_programmer, serial_dumper, motes) + else: + print '\nNo firmware file specified.\n' + +if __name__ == '__main__': + multiprocessing.freeze_support() + main() diff --git a/tools/jn516x/motelist_lib/__init__.py b/tools/jn516x/motelist_lib/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tools/jn516x/motelist_lib/linux_motelist_impl.py b/tools/jn516x/motelist_lib/linux_motelist_impl.py new file mode 100644 index 000000000..231c7814f --- /dev/null +++ b/tools/jn516x/motelist_lib/linux_motelist_impl.py @@ -0,0 +1,220 @@ +# Copyright (c) 2015, SICS Swedish ICT +# 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 Institute 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 INSTITUTE 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 INSTITUTE 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. +# +# This file is part of the Contiki operating system. +# +# Author(s): +# Janis Judvaitis +# Atis Elsts + +import os, glob, re +import multiprocessing, subprocess + +FTDI_VENDOR_ID = "0403" +FTDI_PRODUCT_ID = "6001" + +doPrintVendorID = False + +def read_line(filename): + """helper function to read a single line from a file""" + line = "Unknown" + try: + with open(filename) as f: + line = f.readline().strip() + finally: + return line + +# try to extract descriptions from sysfs. this was done by experimenting, +# no guarantee that it works for all devices or in the future... + +def usb_sysfs_hw_string(sysfs_path): + """given a path to a usb device in sysfs, return a string describing it""" + snr = read_line(sysfs_path + '/serial') + if snr: + snr_txt = '%s' % (snr,) + else: + snr_txt = '' + if doPrintVendorID: + return 'USB VID:PID=%s:%s SNR=%s' % ( + read_line(sysfs_path + '/idVendor'), + read_line(sysfs_path + '/idProduct'), + snr_txt + ) + else: + return snr_txt + +def usb_string(sysfs_path): + # Get dir name in /sys/bus/usb/drivers/usb for current usb dev + dev = os.path.basename(os.path.realpath(sysfs_path)) + dev_dir = os.path.join("/sys/bus/usb/drivers/usb", dev) + + try: + # Go to usb dev directory + product = read_line(os.path.join(dev_dir, "product")) + manufacturer = read_line(os.path.join(dev_dir, "manufacturer")) + result = product + " by " + manufacturer + except: + result = "Unknown device" + + return result + +def describe(device): + """ + Get a human readable description. + For USB-Serial devices try to run lsusb to get a human readable description. + For USB-CDC devices read the description from sysfs. + """ + base = os.path.basename(device) + # USB-Serial devices + sys_dev_path = '/sys/class/tty/%s/device/driver/%s' % (base, base) + if os.path.exists(sys_dev_path): + sys_usb = os.path.dirname(os.path.dirname(os.path.realpath(sys_dev_path))) + return usb_string(sys_usb) + + # Arduino wants special handling + sys_dev_path = '/sys/class/tty/%s/device/driver/' % (base) + for x in os.listdir(sys_dev_path): + # Driver directory's name contains device ID in /sys/bus/usb/drivers/usb + temp = x.split(":") + if len(temp) == 2: + # No Arduino adds, need to save space! + return usb_string(temp[0]).replace("(www.arduino.cc)", "").strip() + + # USB-CDC devices + sys_dev_path = '/sys/class/tty/%s/device/interface' % (base,) + if os.path.exists(sys_dev_path): + return read_line(sys_dev_path) + + return base + +def hwinfo(device): + """Try to get a HW identification using sysfs""" + base = os.path.basename(device) + if os.path.exists('/sys/class/tty/%s/device' % (base,)): + # PCI based devices + sys_id_path = '/sys/class/tty/%s/device/id' % (base,) + if os.path.exists(sys_id_path): + return read_line(sys_id_path) + # USB-Serial devices + sys_dev_path = '/sys/class/tty/%s/device/driver/%s' % (base, base) + if os.path.exists(sys_dev_path): + sys_usb = os.path.dirname(os.path.dirname(os.path.realpath(sys_dev_path))) + return usb_sysfs_hw_string(sys_usb) + # USB-CDC devices + if base.startswith('ttyACM'): + sys_dev_path = '/sys/class/tty/%s/device' % (base,) + if os.path.exists(sys_dev_path): + return usb_sysfs_hw_string(sys_dev_path + '/..') + return 'n/a' # XXX directly remove these from the list? + +####################################### + +def is_nxp_mote(device): + base = os.path.basename(device) + # USB-Serial device? + sys_dev_path = '/sys/class/tty/%s/device/driver/%s' % (base, base) + if not os.path.exists(sys_dev_path): + return False + + path_usb = os.path.dirname(os.path.dirname(os.path.realpath(sys_dev_path))) + + dev = os.path.basename(os.path.realpath(path_usb)) + dev_dir = os.path.join("/sys/bus/usb/drivers/usb", dev) + + try: + idProduct = read_line(os.path.join(dev_dir, "idProduct")) + idVendor = read_line(os.path.join(dev_dir, "idVendor")) + if idVendor != FTDI_VENDOR_ID or idProduct != FTDI_PRODUCT_ID: + return False + product = read_line(os.path.join(dev_dir, "product")) + manufacturer = read_line(os.path.join(dev_dir, "manufacturer")) + if manufacturer != "NXP": + return False + except: + return False + return True + + +def list_motes(flash_programmer): + devices = glob.glob('/dev/ttyUSB*')# + glob.glob('/dev/ttyACM*') + return [d for d in devices if is_nxp_mote(d)] + + +def extract_information(port, stdout_value): + mac_str='Unknown' # not supported on Linux + info='' # not properly supported on Linux + is_program_success='' + + info = describe(port) + ", SerialID: " + hwinfo(port) + + res = re.compile('(Success)').search(stdout_value) + if res: + is_program_success = str(res.group(1)) + else: + res = re.compile('(Error .*)\n').search(stdout_value) + if res: + is_program_success = str(res.group(1)) + + return [mac_str, info, is_program_success] + + +def program_motes(flash_programmer, motes, firmware_file): + for m in motes: + cmd = [flash_programmer, '-v', '-s', m, '-I', '38400', '-P', '1000000', '-f', firmware_file] + cmd = " ".join(cmd) + proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,) + stdout_value, stderr_value = proc.communicate('through stdin to stdout') + [mac_str, info, is_program_success] = extract_information(m, stdout_value) + print m, is_program_success + + errors = (stderr_value) + if errors != '': + print 'Errors:', errors + + +def print_info(flash_programmer, motes, do_mac_only): + if do_mac_only: + print "Listing Mac addresses (not supported on Linux):" + else: + print "Listing mote info:" + + for m in motes: + [mac_str, info, is_program_success] = extract_information(m, '') + if do_mac_only: + print m, mac_str + else: + print m, '\n', info, '\n' + +def serialdump(args): + port_name = args[0] + serial_dumper = args[1] + rv = subprocess.call(serial_dumper + ' -b1000000 ' + port_name, shell=True) + +def serialdump_ports(flash_programmer, serial_dumper, ports): + p = multiprocessing.Pool() + p.map(serialdump, zip(ports, [serial_dumper] * len(ports))) + p.close() diff --git a/tools/jn516x/motelist_lib/windows_motelist_impl.py b/tools/jn516x/motelist_lib/windows_motelist_impl.py new file mode 100644 index 000000000..a4528484b --- /dev/null +++ b/tools/jn516x/motelist_lib/windows_motelist_impl.py @@ -0,0 +1,142 @@ +# Copyright (c) 2015, SICS Swedish ICT +# 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 Institute 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 INSTITUTE 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 INSTITUTE 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. +# +# This file is part of the Contiki operating system. +# +# Author(s): +# Simon Duquennoy +# Atis Elsts + +import os, re, subprocess, multiprocessing + +def list_motes(flash_programmer): + #There is no COM0 in windows. We use this to trigger an error message that lists all valid COM ports + cmd = [flash_programmer, '-c', 'COM0'] + proc = subprocess.Popen(cmd, shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,) + stdout_value, stderr_value = proc.communicate('through stdin to stdout') + com_str = (stderr_value) + #print '\tpass through:', repr(stdout_value) + #print '\tstderr :', com_str + + ## Extract COM ports from output: + ## Example com_str: "Available ports: ['COM15', 'COM10']" + res = re.compile('\[((?:\'COM\d+\'.?.?)+)\]').search(com_str) + + ports = [] + if res: + port_str=str(res.group(1)) + ports=port_str.replace('\'', '').replace(',', '').split() + return ports + +def extract_information(port, stdout_value): + mac_str='' + info='' + is_program_success='' + + #print 'output: ', stdout_value + +# res = re.compile('Connecting to device on (COM\d+)').search(stdout_value) +# if res: +# port_str = str(res.group(1)) + + ### extracting the following information + ''' + Devicelabel: JN516x, BL 0x00080006 + FlashLabel: Internal Flash (256K) + Memory: 0x00008000 bytes RAM, 0x00040000 bytes Flash + ChipPartNo: 8 + ChipRevNo: 1 + ROM Version: 0x00080006 + MAC Address: 00:15:8D:00:00:35:DD:FB + ZB License: 0x00.00.00.00.00.00.00.00.00.00.00.00.00.00.00.00 + User Data: 00:00:00:00:00:00:00:00 + FlashMID: 0xCC + FlashDID: 0xEE + MacLocation: 0x00000010 + Sector Length: 0x08000 + Bootloader Version: 0x00080006 + ''' + + res = re.compile('(Devicelabel.*\sFlashLabel.*\sMemory.*\sChipPartNo.*\sChipRevNo.*\sROM Version.*\sMAC Address.*\sZB License.*\sUser Data.*\sFlashMID.*\sFlashDID.*\sMacLocation.*\sSector Length.*\sBootloader Version\:\s+0x\w{8})').search(stdout_value) + if res: + info = str(res.group(1)) + + res = re.compile('MAC Address\:\s+((?:\w{2}\:?){8})').search(stdout_value) + if res: + mac_str = str(res.group(1)) + + res = re.compile('(Program\ssuccessfully\swritten\sto\sflash)').search(stdout_value) + if res: + is_program_success = str(res.group(1)) + + return [mac_str, info, is_program_success] + +def program_motes(flash_programmer, motes, firmware_file): + for m in motes: + cmd = [flash_programmer, '-c', m, '-B', '1000000', '-s', '-w', '-f', firmware_file] + proc = subprocess.Popen(cmd, shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,) + stdout_value, stderr_value = proc.communicate('through stdin to stdout') + [mac_str, info, is_program_success] = extract_information(m, stdout_value) + print m, mac_str, is_program_success + + errors = (stderr_value) + if errors != '': + print 'Errors:', errors + +def print_info(flash_programmer, motes, do_mac_only): + if do_mac_only: + print "Listing Mac addresses:" + else: + print "Listing mote info:" + for m in motes: + cmd=[flash_programmer, '-c', m, '-B', '1000000'] + proc = subprocess.Popen(cmd, shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,) + stdout_value, stderr_value = proc.communicate('through stdin to stdout') + [mac_str, info, is_program_success] = extract_information(m, stdout_value) + + errors = (stderr_value) + + if do_mac_only: + print m, mac_str + else: + print m, '\n', info, '\n' + + if errors != '': + print 'Errors:', errors + +def serialdump(args): + port_name = args[0] + serial_dumper = args[1] + cmd = [serial_dumper, '-b1000000', "/dev/" + port_name.lower()] + if os.name == "posix" or os.name == "cygwin": + cmd = " ".join(cmd) + rv = subprocess.call(cmd, shell=True) + +def serialdump_ports(flash_programmer, serial_dumper, ports): + p = multiprocessing.Pool() + p.map(serialdump, zip(ports, [serial_dumper] * len(ports))) + p.close() diff --git a/tools/jn516x/serialdump.c b/tools/jn516x/serialdump.c new file mode 100644 index 000000000..26b0884e2 --- /dev/null +++ b/tools/jn516x/serialdump.c @@ -0,0 +1,396 @@ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define BAUDRATE B115200 +#define BAUDRATE_S "115200" +#ifdef linux +#define MODEMDEVICE "/dev/ttyS0" +#else +#define MODEMDEVICE "/dev/com1" +#endif /* linux */ + +#define SLIP_END 0300 +#define SLIP_ESC 0333 +#define SLIP_ESC_END 0334 +#define SLIP_ESC_ESC 0335 + +#define CSNA_INIT 0x01 + +#define BUFSIZE 40 +#define HCOLS 20 +#define ICOLS 18 + +#define MODE_START_DATE 0 +#define MODE_DATE 1 +#define MODE_START_TEXT 2 +#define MODE_TEXT 3 +#define MODE_INT 4 +#define MODE_HEX 5 +#define MODE_SLIP_AUTO 6 +#define MODE_SLIP 7 +#define MODE_SLIP_HIDE 8 + +static unsigned char rxbuf[2048]; + +static int +usage(int result) +{ + printf("Usage: serialdump [-x] [-s[on]] [-i] [-bSPEED] [SERIALDEVICE]\n"); + printf(" -x for hexadecimal output\n"); + printf(" -i for decimal output\n"); + printf(" -s for automatic SLIP mode\n"); + printf(" -so for SLIP only mode (all data is SLIP packets)\n"); + printf(" -sn to hide SLIP packages\n"); + printf(" -T[format] to add time for each text line\n"); + printf(" (see man page for strftime() for format description)\n"); + return result; +} + +static void +print_hex_line(unsigned char *prefix, unsigned char *outbuf, int index) +{ + int i; + + printf("\r%s", prefix); + for(i = 0; i < index; i++) { + if((i % 4) == 0) { + printf(" "); + } + printf("%02X", outbuf[i] & 0xFF); + } + printf(" "); + for(i = index; i < HCOLS; i++) { + if((i % 4) == 0) { + printf(" "); + } + printf(" "); + } + for(i = 0; i < index; i++) { + if(outbuf[i] < 30 || outbuf[i] > 126) { + printf("."); + } else { + printf("%c", outbuf[i]); + } + } +} + +int +main(int argc, char **argv) +{ + struct termios options; + fd_set mask, smask; + int fd; + speed_t speed = BAUDRATE; + char *speedname = BAUDRATE_S; + char *device = MODEMDEVICE; + char *timeformat = NULL; + unsigned char buf[BUFSIZE], outbuf[HCOLS]; + unsigned char mode = MODE_START_TEXT; + int nfound, flags = 0; + unsigned char lastc = '\0'; + + int index = 1; + while(index < argc) { + if(argv[index][0] == '-') { + switch(argv[index][1]) { + case 'b': + /* set speed */ + if(strcmp(&argv[index][2], "38400") == 0) { + speed = B38400; + speedname = "38400"; + } else if(strcmp(&argv[index][2], "19200") == 0) { + speed = B19200; + speedname = "19200"; + } else if(strcmp(&argv[index][2], "57600") == 0) { + speed = B57600; + speedname = "57600"; + } else if(strcmp(&argv[index][2], "115200") == 0) { + speed = B115200; + speedname = "115200"; + } else if(strcmp(&argv[index][2], "230400") == 0) { + speed = B230400; + speedname = "230400"; + } else if(strcmp(&argv[index][2], "460800") == 0) { + speed = B460800; + speedname = "460800"; + } else if(strcmp(&argv[index][2], "500000") == 0) { + speed = B500000; + speedname = "500000"; + } else if(strcmp(&argv[index][2], "576000") == 0) { + speed = B576000; + speedname = "576000"; + } else if(strcmp(&argv[index][2], "921600") == 0) { + speed = B921600; + speedname = "921600"; + } else if(strcmp(&argv[index][2], "1000000") == 0) { + speed = B1000000; + speedname = "1000000"; + } else { + fprintf(stderr, "unsupported speed: %s\n", &argv[index][2]); + return usage(1); + } + break; + case 'x': + mode = MODE_HEX; + break; + case 'i': + mode = MODE_INT; + break; + case 's': + switch(argv[index][2]) { + case 'n': + mode = MODE_SLIP_HIDE; + break; + case 'o': + mode = MODE_SLIP; + break; + default: + mode = MODE_SLIP_AUTO; + break; + } + break; + case 'T': + if(strlen(&argv[index][2]) == 0) { + timeformat = "%Y-%m-%d %H:%M:%S"; + } else { + timeformat = &argv[index][2]; + } + mode = MODE_START_DATE; + break; + case 'h': + return usage(0); + default: + fprintf(stderr, "unknown option '%c'\n", argv[index][1]); + return usage(1); + } + index++; + } else { + device = argv[index++]; + if(index < argc) { + fprintf(stderr, "too many arguments\n"); + return usage(1); + } + } + } + fprintf(stderr, "connecting to %s (%s)", device, speedname); + +#ifdef O_SYNC + fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY /*| O_DIRECT*/ | O_SYNC); + if(fd < 0 && errno == EINVAL){ // O_SYNC not supported (e.g. raspberian) + fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_DIRECT); + } +#else + fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_SYNC ); +#endif + if(fd < 0) { + fprintf(stderr, "\n"); + perror("open"); + exit(-1); + } + fprintf(stderr, " [OK]\n"); + + if(fcntl(fd, F_SETFL, 0) < 0) { + perror("could not set fcntl"); + exit(-1); + } + + if(tcgetattr(fd, &options) < 0) { + perror("could not get options"); + exit(-1); + } + /* fprintf(stderr, "serial options set\n"); */ + cfsetispeed(&options, speed); + cfsetospeed(&options, speed); + /* Enable the receiver and set local mode */ + options.c_cflag |= (CLOCAL | CREAD); + /* Mask the character size bits and turn off (odd) parity */ + options.c_cflag &= ~(CSIZE | PARENB | PARODD); + /* Select 8 data bits */ + options.c_cflag |= CS8; + + /* Raw input */ + options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); + /* Raw output */ + options.c_oflag &= ~OPOST; + + if(tcsetattr(fd, TCSANOW, &options) < 0) { + perror("could not set options"); + exit(-1); + } + + /* Make read() return immediately */ + /* if (fcntl(fd, F_SETFL, FNDELAY) < 0) { */ + /* perror("\ncould not set fcntl"); */ + /* exit(-1); */ + /* } */ + + FD_ZERO(&mask); + FD_SET(fd, &mask); + FD_SET(fileno(stdin), &mask); + + index = 0; + for(;;) { + smask = mask; + nfound = select(FD_SETSIZE, &smask, (fd_set *) 0, (fd_set *) 0, (struct timeval *) 0); + if(nfound < 0) { + if(errno == EINTR) { + fprintf(stderr, "interrupted system call\n"); + continue; + } + /* something is very wrong! */ + perror("select"); + exit(1); + } + + if(FD_ISSET(fileno(stdin), &smask)) { + /* data from standard in */ + int n = read(fileno(stdin), buf, sizeof(buf)); + if(n < 0) { + perror("could not read"); + exit(-1); + } else if(n > 0) { + /* because commands might need parameters, lines needs to be + separated which means the terminating LF must be sent */ + /* while(n > 0 && buf[n - 1] < 32) { */ + /* n--; */ + /* } */ + if(n > 0) { + int i; + /* fprintf(stderr, "SEND %d bytes\n", n);*/ + /* write slowly */ + for(i = 0; i < n; i++) { + if(write(fd, &buf[i], 1) <= 0) { + perror("write"); + exit(1); + } else { + fflush(NULL); + usleep(6000); + } + } + } + } else { + /* End of input, exit. */ + exit(0); + } + } + + if(FD_ISSET(fd, &smask)) { + int i, j, n = read(fd, buf, sizeof(buf)); + if(n < 0) { + perror("could not read"); + exit(-1); + } + + for(i = 0; i < n; i++) { + switch(mode) { + case MODE_START_TEXT: + case MODE_TEXT: + printf("%c", buf[i]); + break; + case MODE_START_DATE: { + time_t t; + t = time(&t); + strftime(outbuf, HCOLS, timeformat, localtime(&t)); + printf("%s|", outbuf); + mode = MODE_DATE; + } + /* continue into the MODE_DATE */ + case MODE_DATE: + printf("%c", buf[i]); + if(buf[i] == '\n') { + mode = MODE_START_DATE; + } + break; + case MODE_INT: + printf("%03d ", buf[i]); + if(++index >= ICOLS) { + index = 0; + printf("\n"); + } + break; + case MODE_HEX: + rxbuf[index++] = buf[i]; + if(index >= HCOLS) { + print_hex_line("", rxbuf, index); + index = 0; + printf("\n"); + } + break; + + case MODE_SLIP_AUTO: + case MODE_SLIP_HIDE: + if(!flags && (buf[i] != SLIP_END)) { + /* Not a SLIP packet? */ + printf("%c", buf[i]); + break; + } + /* continue to slip only mode */ + case MODE_SLIP: + switch(buf[i]) { + case SLIP_ESC: + lastc = SLIP_ESC; + break; + + case SLIP_END: + if(index > 0) { + if(flags != 2 && mode != MODE_SLIP_HIDE) { + /* not overflowed: show packet */ + print_hex_line("SLIP: ", rxbuf, index > HCOLS ? HCOLS : index); + printf("\n"); + } + lastc = '\0'; + index = 0; + flags = 0; + } else { + flags = !flags; + } + break; + + default: + if(lastc == SLIP_ESC) { + lastc = '\0'; + + /* Previous read byte was an escape byte, so this byte will be + interpreted differently from others. */ + switch(buf[i]) { + case SLIP_ESC_END: + buf[i] = SLIP_END; + break; + case SLIP_ESC_ESC: + buf[i] = SLIP_ESC; + break; + } + } + + rxbuf[index++] = buf[i]; + if(index >= sizeof(rxbuf)) { + fprintf(stderr, "**** slip overflow\n"); + index = 0; + flags = 2; + } + break; + } + break; + } + } + + /* after processing for some output modes */ + if(index > 0) { + switch(mode) { + case MODE_HEX: + print_hex_line("", rxbuf, index); + break; + } + } + fflush(stdout); + } + } +}