Contiki 2.5
contiki-main.c
1 /*
2  * Copyright (c) 2006, Technical University of Munich
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  * notice, this list of conditions and the following disclaimer in the
12  * documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the Institute nor the names of its contributors
14  * may be used to endorse or promote products derived from this software
15  * without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * This file is part of the Contiki operating system.
30  *
31  */
32 #define PRINTF(FORMAT,args...) printf_P(PSTR(FORMAT),##args)
33 
34 #define ANNOUNCE_BOOT 1 //adds about 600 bytes to program size
35 #if ANNOUNCE_BOOT
36 #define PRINTA(FORMAT,args...) printf_P(PSTR(FORMAT),##args)
37 #else
38 #define PRINTA(...)
39 #endif
40 
41 #define DEBUG 0
42 #if DEBUG
43 #define PRINTD(FORMAT,args...) printf_P(PSTR(FORMAT),##args)
44 #else
45 #define PRINTD(...)
46 #endif
47 
48 /* Track interrupt flow through mac, rdc and radio driver */
49 #if DEBUGFLOWSIZE
50 uint8_t debugflowsize,debugflow[DEBUGFLOWSIZE];
51 #define DEBUGFLOW(c) if (debugflowsize<(DEBUGFLOWSIZE-1)) debugflow[debugflowsize++]=c
52 #else
53 #define DEBUGFLOW(c)
54 #endif
55 
56 #include <avr/pgmspace.h>
57 #include <avr/fuse.h>
58 #include <avr/eeprom.h>
59 #include <stdio.h>
60 #include <string.h>
61 #include <dev/watchdog.h>
62 
63 #include "loader/symbols-def.h"
64 #include "loader/symtab.h"
65 
66 #include "params.h"
67 #include "radio/rf230bb/rf230bb.h"
68 #include "net/mac/frame802154.h"
69 #include "net/mac/framer-802154.h"
70 #include "net/sicslowpan.h"
71 
72 #include "contiki.h"
73 #include "contiki-net.h"
74 #include "contiki-lib.h"
75 
76 #include "dev/rs232.h"
77 #include "dev/serial-line.h"
78 #include "dev/slip.h"
79 
80 #ifdef RAVEN_LCD_INTERFACE
81 #include "raven-lcd.h"
82 #endif
83 
84 #if AVR_WEBSERVER
85 #include "httpd-fs.h"
86 #include "httpd-cgi.h"
87 #endif
88 
89 #ifdef COFFEE_FILES
90 #include "cfs/cfs.h"
91 #include "cfs/cfs-coffee.h"
92 #endif
93 
94 #if UIP_CONF_ROUTER&&0
95 #include "net/routing/rimeroute.h"
96 #include "net/rime/rime-udp.h"
97 #endif
98 
99 #include "net/rime.h"
100 
101 /* Get periodic prints from idle loop, from clock seconds or rtimer interrupts */
102 /* Use of rtimer will conflict with other rtimer interrupts such as contikimac radio cycling */
103 /* STAMPS will print ENERGEST outputs if that is enabled. */
104 #define PERIODICPRINTS 1
105 #if PERIODICPRINTS
106 //#define PINGS 64
107 #define ROUTES 600
108 #define STAMPS 60
109 #define STACKMONITOR 1024
110 uint32_t clocktime;
111 #define TESTRTIMER 0
112 #if TESTRTIMER
113 uint8_t rtimerflag=1;
114 struct rtimer rt;
115 void rtimercycle(void) {rtimerflag=1;}
116 #endif
117 #endif
118 
119 uint16_t ledtimer;
120 
121 /*-------------------------------------------------------------------------*/
122 /*----------------------Configuration of the .elf file---------------------*/
123 #if 1
124 /* The proper way to set the signature is */
125 #include <avr/signature.h>
126 #else
127 /* Older avr-gcc's may not define the needed SIGNATURE bytes. Do it manually if you get an error */
128 typedef struct {const unsigned char B2;const unsigned char B1;const unsigned char B0;} __signature_t;
129 #define SIGNATURE __signature_t __signature __attribute__((section (".signature")))
130 SIGNATURE = {
131  .B2 = 0x01,//SIGNATURE_2, //ATMEGA128rfa1
132  .B1 = 0xA7,//SIGNATURE_1, //128KB flash
133  .B0 = 0x1E,//SIGNATURE_0, //Atmel
134 };
135 #endif
136 
137 #if 1
138 /* JTAG, SPI enabled, Internal RC osc, Boot flash size 4K, 6CK+65msec delay, brownout disabled */
139 FUSES ={.low = 0xe2, .high = 0x99, .extended = 0xff,};
140 #else
141 /* JTAG+SPI, Boot 4096 words @ $F000, Internal oscillator, startup 6 CK +0 ms, Brownout 1.8 volts */
142 FUSES ={.low = 0xC2, .high = 0x99, .extended = 0xfe,};
143 #endif
144 
145 uint8_t
146 rng_get_uint8(void) {
147 #if 1
148  /* Upper two RSSI reg bits (RND_VALUE) are random in rf231 */
149  uint8_t j;
150  j = (PHY_RSSI>>6) | (PHY_RSSI>>4) | (PHY_RSSI>>4) | PHY_RSSI;
151 #else
152 /* Get a pseudo random number using the ADC */
153  uint8_t i,j;
154  ADCSRA=1<<ADEN; //Enable ADC, not free running, interrupt disabled, fastest clock
155  for (i=0;i<4;i++) {
156  ADMUX = 0; //toggle reference to increase noise
157  ADMUX =0x1E; //Select AREF as reference, measure 1.1 volt bandgap reference.
158  ADCSRA|=1<<ADSC; //Start conversion
159  while (ADCSRA&(1<<ADSC)); //Wait till done
160  j = (j<<2) + ADC;
161  }
162  ADCSRA=0; //Disable ADC
163 #endif
164  PRINTD("rng issues %d\n",j);
165  return j;
166 }
167 
168 /*-------------------------Low level initialization------------------------*/
169 /*------Done in a subroutine to keep main routine stack usage small--------*/
170 void initialize(void)
171 {
172  watchdog_init();
173  watchdog_start();
174 
175 /* The Raven implements a serial command and data interface via uart0 to a 3290p,
176  * which could be duplicated using another host computer.
177  */
178 #if !RF230BB_CONF_LEDONPORTE1 //Conflicts with USART0
179 #ifdef RAVEN_LCD_INTERFACE
180  rs232_init(RS232_PORT_0, USART_BAUD_38400,USART_PARITY_NONE | USART_STOP_BITS_1 | USART_DATA_BITS_8);
181  rs232_set_input(0,raven_lcd_serial_input);
182 #else
183  /* Generic or slip connection on uart0 */
184  rs232_init(RS232_PORT_0, USART_BAUD_38400,USART_PARITY_NONE | USART_STOP_BITS_1 | USART_DATA_BITS_8);
185 #endif
186 #endif
187 
188  /* Second rs232 port for debugging or slip alternative */
189  rs232_init(RS232_PORT_1, USART_BAUD_57600,USART_PARITY_NONE | USART_STOP_BITS_1 | USART_DATA_BITS_8);
190  /* Redirect stdout to second port */
191  rs232_redirect_stdout(RS232_PORT_1);
192  clock_init();
193 
194  if(MCUSR & (1<<PORF )) PRINTD("Power-on reset.\n");
195  if(MCUSR & (1<<EXTRF)) PRINTD("External reset!\n");
196  if(MCUSR & (1<<BORF )) PRINTD("Brownout reset!\n");
197  if(MCUSR & (1<<WDRF )) PRINTD("Watchdog reset!\n");
198  if(MCUSR & (1<<JTRF )) PRINTD("JTAG reset!\n");
199 
200 #if STACKMONITOR
201  /* Simple stack pointer highwater monitor. Checks for magic numbers in the main
202  * loop. In conjuction with PERIODICPRINTS, never-used stack will be printed
203  * every STACKMONITOR seconds.
204  */
205 {
206 extern uint16_t __bss_end;
207 uint16_t p=(uint16_t)&__bss_end;
208  do {
209  *(uint16_t *)p = 0x4242;
210  p+=10;
211  } while (p<SP-10); //don't overwrite our own stack
212 }
213 #endif
214 
215 #define CONF_CALIBRATE_OSCCAL 0
216 #if CONF_CALIBRATE_OSCCAL
217 void calibrate_rc_osc_32k();
218 {
219 extern uint8_t osccal_calibrated;
220 uint8_t i;
221  PRINTD("\nBefore calibration OSCCAL=%x\n",OSCCAL);
222  for (i=0;i<10;i++) {
224  PRINTD("Calibrated=%x\n",osccal_calibrated);
225 //#include <util/delay_basic.h>
226 //#define delay_us( us ) ( _delay_loop_2(1+(us*F_CPU)/4000000UL) )
227 // delay_us(50000);
228  }
229  clock_init();
230 }
231 #endif
232 
233  PRINTA("\n*******Booting %s*******\n",CONTIKI_VERSION_STRING);
234 
235 /* rtimers needed for radio cycling */
236  rtimer_init();
237 
238  /* Initialize process subsystem */
239  process_init();
240 
241  /* etimers must be started before ctimer_init */
242  process_start(&etimer_process, NULL);
243  ctimer_init();
244 
245  /* Start radio and radio receive process */
246  NETSTACK_RADIO.init();
247 
248 /* Get a random seed for the 802.15.4 packet sequence number.
249  * Some layers will ignore duplicates found in a history (e.g. Contikimac)
250  * causing the initial packets to be ignored after a short-cycle restart.
251  */
252  random_init(rng_get_uint8());
253 
254  /* Set addresses BEFORE starting tcpip process */
255 
256  rimeaddr_t addr;
257 
258  if (params_get_eui64(addr.u8)) {
259  PRINTA("Random EUI64 address generated\n");
260  }
261 
262 #if UIP_CONF_IPV6
263  memcpy(&uip_lladdr.addr, &addr.u8, sizeof(rimeaddr_t));
264 #elif WITH_NODE_ID
265  node_id=get_panaddr_from_eeprom();
266  addr.u8[1]=node_id&0xff;
267  addr.u8[0]=(node_id&0xff00)>>8;
268  PRINTA("Node ID from eeprom: %X\n",node_id);
269 #endif
270  rimeaddr_set_node_addr(&addr);
271 
272  rf230_set_pan_addr(params_get_panid(),params_get_panaddr(),(uint8_t *)&addr.u8);
273  rf230_set_channel(params_get_channel());
274  rf230_set_txpower(params_get_txpower());
275 
276 #if UIP_CONF_IPV6
277  PRINTA("EUI-64 MAC: %x-%x-%x-%x-%x-%x-%x-%x\n",addr.u8[0],addr.u8[1],addr.u8[2],addr.u8[3],addr.u8[4],addr.u8[5],addr.u8[6],addr.u8[7]);
278 #else
279  PRINTA("MAC address ");
280  uint8_t i;
281  for (i=sizeof(rimeaddr_t); i>0; i--){
282  PRINTA("%x:",addr.u8[i-1]);
283  }
284  PRINTA("\n");
285 #endif
286 
287  /* Initialize stack protocols */
288  queuebuf_init();
289  NETSTACK_RDC.init();
290  NETSTACK_MAC.init();
291  NETSTACK_NETWORK.init();
292 
293 #if ANNOUNCE_BOOT
294  PRINTA("%s %s, channel %u power %u",NETSTACK_MAC.name, NETSTACK_RDC.name,rf230_get_channel(),rf230_get_txpower());
295  if (NETSTACK_RDC.channel_check_interval) {//function pointer is zero for sicslowmac
296  unsigned short tmp;
297  tmp=CLOCK_SECOND / (NETSTACK_RDC.channel_check_interval == 0 ? 1:\
298  NETSTACK_RDC.channel_check_interval());
299  if (tmp<65535) PRINTA(", check rate %u Hz",tmp);
300  }
301  PRINTA("\n");
302 
303 #if UIP_CONF_IPV6_RPL
304  PRINTA("RPL Enabled\n");
305 #endif
306 #if UIP_CONF_ROUTER
307  PRINTA("Routing Enabled\n");
308 #endif
309 
310 #endif /* ANNOUNCE_BOOT */
311 
312  process_start(&tcpip_process, NULL);
313 
314 #ifdef RAVEN_LCD_INTERFACE
315  process_start(&raven_lcd_process, NULL);
316 #endif
317 
318  /* Autostart other processes */
319  autostart_start(autostart_processes);
320 
321  /*---If using coffee file system create initial web content if necessary---*/
322 #if COFFEE_FILES
323  int fa = cfs_open( "/index.html", CFS_READ);
324  if (fa<0) { //Make some default web content
325  PRINTA("No index.html file found, creating upload.html!\n");
326  PRINTA("Formatting FLASH file system for coffee...");
328  PRINTA("Done!\n");
329  fa = cfs_open( "/index.html", CFS_WRITE);
330  int r = cfs_write(fa, &"It works!", 9);
331  if (r<0) PRINTA("Can''t create /index.html!\n");
332  cfs_close(fa);
333 // fa = cfs_open("upload.html"), CFW_WRITE);
334 // <html><body><form action="upload.html" enctype="multipart/form-data" method="post"><input name="userfile" type="file" size="50" /><input value="Upload" type="submit" /></form></body></html>
335  }
336 #endif /* COFFEE_FILES */
337 
338 /* Add addresses for testing */
339 #if 0
340 {
341  uip_ip6addr_t ipaddr;
342  uip_ip6addr(&ipaddr, 0xaaaa, 0, 0, 0, 0, 0, 0, 0);
343  uip_ds6_addr_add(&ipaddr, 0, ADDR_AUTOCONF);
344 // uip_ds6_prefix_add(&ipaddr,64,0);
345 }
346 #endif
347 
348 /*--------------------------Announce the configuration---------------------*/
349 #if ANNOUNCE_BOOT
350 #if AVR_WEBSERVER
351 { uint8_t i;
352  char buf[80];
353  unsigned int size;
354 
355  for (i=0;i<UIP_DS6_ADDR_NB;i++) {
356  if (uip_ds6_if.addr_list[i].isused) {
357  httpd_cgi_sprint_ip6(uip_ds6_if.addr_list[i].ipaddr,buf);
358  PRINTA("IPv6 Address: %s\n",buf);
359  }
360  }
361  cli();
362  eeprom_read_block (buf,eemem_server_name, sizeof(eemem_server_name));
363  sei();
364  buf[sizeof(eemem_server_name)]=0;
365  PRINTA("%s",buf);
366  cli();
367  eeprom_read_block (buf,eemem_domain_name, sizeof(eemem_domain_name));
368  sei();
369  buf[sizeof(eemem_domain_name)]=0;
370  size=httpd_fs_get_size();
371 #ifndef COFFEE_FILES
372  PRINTA(".%s online with fixed %u byte web content\n",buf,size);
373 #elif COFFEE_FILES==1
374  PRINTA(".%s online with static %u byte EEPROM file system\n",buf,size);
375 #elif COFFEE_FILES==2
376  PRINTA(".%s online with dynamic %u KB EEPROM file system\n",buf,size>>10);
377 #elif COFFEE_FILES==3
378  PRINTA(".%s online with static %u byte program memory file system\n",buf,size);
379 #elif COFFEE_FILES==4
380  PRINTA(".%s online with dynamic %u KB program memory file system\n",buf,size>>10);
381 #endif /* COFFEE_FILES */
382 }
383 #else
384  PRINTA("Online\n");
385 #endif
386 #endif /* ANNOUNCE_BOOT */
387 
388 #if RF230BB_CONF_LEDONPORTE1
389  /* NB: PORTE1 conflicts with UART0 */
390  DDRE|=(1<<DDE1); //set led pin to output (Micheal Hatrtman board)
391  PORTE&=~(1<<PE1); //and low to turn led off
392 #endif
393 }
394 
395 #if ROUTES && UIP_CONF_IPV6
396 static void
397 ipaddr_add(const uip_ipaddr_t *addr)
398 {
399  uint16_t a;
400  int8_t i, f;
401  for(i = 0, f = 0; i < sizeof(uip_ipaddr_t); i += 2) {
402  a = (addr->u8[i] << 8) + addr->u8[i + 1];
403  if(a == 0 && f >= 0) {
404  if(f++ == 0) PRINTF("::");
405  } else {
406  if(f > 0) {
407  f = -1;
408  } else if(i > 0) {
409  PRINTF(":");
410  }
411  PRINTF("%x",a);
412  }
413  }
414 }
415 #endif
416 
417 /*-------------------------------------------------------------------------*/
418 /*------------------------- Main Scheduler loop----------------------------*/
419 /*-------------------------------------------------------------------------*/
420 int
421 main(void)
422 {
423  initialize();
424 
425  while(1) {
426  process_run();
427  watchdog_periodic();
428 
429  /* Turn off LED after a while */
430  if (ledtimer) {
431  if (--ledtimer==0) {
432 #if RF230BB_CONF_LEDONPORTE1
433  PORTE&=~(1<<PE1);
434 #endif
435 #if defined(RAVEN_LCD_INTERFACE)&&0
436  /* ledtimer can be set by received ping; ping the other way for testing */
437  extern void raven_ping6(void);
438  raven_ping6();
439 #endif
440  }
441  }
442 
443 #if 0
444 /* Various entry points for debugging in the AVR Studio simulator.
445  * Set as next statement and step into the routine.
446  */
447  NETSTACK_RADIO.send(packetbuf_hdrptr(), 42);
448  process_poll(&rf230_process);
449  packetbuf_clear();
450  len = rf230_read(packetbuf_dataptr(), PACKETBUF_SIZE);
452  NETSTACK_RDC.input();
453 #endif
454 
455 #if 0
456 /* Clock.c can trigger a periodic PLL calibration in the RF230BB driver.
457  * This can show when that happens.
458  */
459  extern uint8_t rf230_calibrated;
460  if (rf230_calibrated) {
461  PRINTD("\nRF230 calibrated!\n");
462  rf230_calibrated=0;
463  }
464 #endif
465 
466 /* Set DEBUGFLOWSIZE in contiki-conf.h to track path through MAC, RDC, and RADIO */
467 #if DEBUGFLOWSIZE
468  if (debugflowsize) {
469  debugflow[debugflowsize]=0;
470  PRINTF("%s",debugflow);
471  debugflowsize=0;
472  }
473 #endif
474 
475 #if PERIODICPRINTS
476 #if TESTRTIMER
477 /* Timeout can be increased up to 8 seconds maximum.
478  * A one second cycle is convenient for triggering the various debug printouts.
479  * The triggers are staggered to avoid printing everything at once.
480  */
481  if (rtimerflag) {
482  rtimer_set(&rt, RTIMER_NOW()+ RTIMER_ARCH_SECOND*1UL, 1,(void *) rtimercycle, NULL);
483  rtimerflag=0;
484 #else
485  if (clocktime!=clock_seconds()) {
486  clocktime=clock_seconds();
487 #endif
488 
489 #if STAMPS
490 if ((clocktime%STAMPS)==0) {
491 #if ENERGEST_CONF_ON
492 #include "lib/print-stats.h"
493  print_stats();
494 #elif RADIOSTATS
495 extern volatile unsigned long radioontime;
496  PRINTF("%u(%u)s\n",clocktime,radioontime);
497 #else
498  PRINTF("%us\n",clocktime);
499 #endif
500 
501 }
502 #endif
503 #if TESTRTIMER
504  clocktime+=1;
505 #endif
506 
507 #if PINGS && UIP_CONF_IPV6
508 extern void raven_ping6(void);
509 if ((clocktime%PINGS)==1) {
510  PRINTF("**Ping\n");
511  raven_ping6();
512 }
513 #endif
514 
515 #if ROUTES && UIP_CONF_IPV6
516 if ((clocktime%ROUTES)==2) {
517 
520 extern uip_ds6_netif_t uip_ds6_if;
521 
522  uint8_t i,j;
523  PRINTF("\nAddresses [%u max]\n",UIP_DS6_ADDR_NB);
524  for (i=0;i<UIP_DS6_ADDR_NB;i++) {
525  if (uip_ds6_if.addr_list[i].isused) {
526  ipaddr_add(&uip_ds6_if.addr_list[i].ipaddr);
527  PRINTF("\n");
528  }
529  }
530  PRINTF("\nNeighbors [%u max]\n",UIP_DS6_NBR_NB);
531  for(i = 0,j=1; i < UIP_DS6_NBR_NB; i++) {
532  if(uip_ds6_nbr_cache[i].isused) {
533  ipaddr_add(&uip_ds6_nbr_cache[i].ipaddr);
534  PRINTF("\n");
535  j=0;
536  }
537  }
538  if (j) PRINTF(" <none>");
539  PRINTF("\nRoutes [%u max]\n",UIP_DS6_ROUTE_NB);
540  for(i = 0,j=1; i < UIP_DS6_ROUTE_NB; i++) {
541  if(uip_ds6_routing_table[i].isused) {
542  ipaddr_add(&uip_ds6_routing_table[i].ipaddr);
543  PRINTF("/%u (via ", uip_ds6_routing_table[i].length);
544  ipaddr_add(&uip_ds6_routing_table[i].nexthop);
545  // if(uip_ds6_routing_table[i].state.lifetime < 600) {
546  PRINTF(") %lus\n", uip_ds6_routing_table[i].state.lifetime);
547  // } else {
548  // PRINTF(")\n");
549  // }
550  j=0;
551  }
552  }
553  if (j) PRINTF(" <none>");
554  PRINTF("\n---------\n");
555 }
556 #endif
557 
558 #if STACKMONITOR
559 if ((clocktime%STACKMONITOR)==3) {
560  extern uint16_t __bss_end;
561  uint16_t p=(uint16_t)&__bss_end;
562  do {
563  if (*(uint16_t *)p != 0x4242) {
564  PRINTF("Never-used stack > %d bytes\n",p-(uint16_t)&__bss_end);
565  break;
566  }
567  p+=10;
568  } while (p<RAMEND-10);
569 }
570 #endif
571 
572  }
573 #endif /* PERIODICPRINTS */
574 
575 #if RF230BB&&0
576 extern uint8_t rf230processflag;
577  if (rf230processflag) {
578  PRINTF("rf230p%d",rf230processflag);
579  rf230processflag=0;
580  }
581 #endif
582 
583 #if RF230BB&&0
584 extern uint8_t rf230_interrupt_flag;
585  if (rf230_interrupt_flag) {
586  // if (rf230_interrupt_flag!=11) {
587  PRINTF("**RI%u",rf230_interrupt_flag);
588  // }
589  rf230_interrupt_flag=0;
590  }
591 #endif
592  }
593  return 0;
594 }
595 
596 /*---------------------------------------------------------------------------*/
597 
598 void log_message(char *m1, char *m2)
599 {
600  PRINTF("%s%s\n", m1, m2);
601 }