void power_off(void)
{
#if defined(HAVE_LCD_COLOR) && !defined(HAVE_LCD_SHUTDOWN)
    /* Clear the screen and backdrop to
    remove ghosting effect on shutdown */
    lcd_set_backdrop(NULL);
    lcd_set_background(LCD_WHITE);
    lcd_clear_display();
    lcd_update();
    sleep(HZ/16);
#endif

#ifndef BOOTLOADER
#ifdef IPOD_1G2G
    /* we cannot turn off the 1st gen/ 2nd gen yet. Need to figure out sleep mode. */
    system_reboot();
#else
    /* We don't turn off the ipod, we put it in a deep sleep */
    /* Clear latter part of iram (the part used by plugins/codecs) to ensure
     * that the OF behaves properly on boot. There is some kind of boot
     * failure flag there which otherwise may not be cleared.
     */
#if CONFIG_CPU == PP5022
    memset((void*)0x4000c000, 0, 0x14000);
#elif CONFIG_CPU == PP5020
    memset((void*)0x4000c000, 0, 0xc000);
#endif
    pcf50605_standby_mode();
#endif
#endif
}
Exemple #2
0
void system_exception_wait(void)
{
    if (evt_thread)
    {
        while (!quitting)
            SDL_Delay(10);
    }
    system_reboot();
}
Exemple #3
0
void fatal_error(void)
{
    extern int line;
    bool holdstatus=false;

    /* System font is 6 pixels wide */
#if defined(IPOD_1G2G) || defined(IPOD_3G)
    printf("Insert Firewire cable, or");
    printf("hold MENU+PLAY to reboot");
    printf("then REW+FF for disk mode");
#elif LCD_WIDTH >= (30*6)
    printf("Insert USB cable, or");
    printf("hold MENU+SELECT to reboot");
    printf("then SELECT+PLAY for disk mode");
#else
    printf("Insert USB cable, or");
    printf("hold MENU+SELECT to");
    printf("reboot then SELECT+PLAY");
    printf("for disk mode");
#endif
    lcd_update();

    usb_init();
    while (1) {
        if (button_hold() != holdstatus) {
            if (button_hold()) {
                holdstatus=true;
                lcd_puts(0, line, "Hold switch on!");
            } else {
                holdstatus=false;
                lcd_puts(0, line, "               ");
            }
            lcd_update();
        }
        if (usb_detect() == USB_INSERTED) {
            ata_sleepnow(); /* Immediately spindown the disk. */
            sleep(HZ*2);
#if CONFIG_CPU == PP5020
            memcpy((void *)0x40017f00, "diskmode\0\0hotstuff\0\0\1", 21);
#elif CONFIG_CPU == PP5022
            memcpy((void *)0x4001ff00, "diskmode\0\0hotstuff\0\0\1", 21);
#elif CONFIG_CPU == PP5002
            memcpy((void *)0x40017f00, "diskmodehotstuff\1", 17);
#endif /* CONFIG_CPU */
            system_reboot(); /* Reboot */
        }
        udelay(100000); /* 100ms */
    }

}
Exemple #4
0
static void sig_handler(int sig, siginfo_t *siginfo, void *context)
{
    /* safe guard variable - we call backtrace() only on first
     * UIE call. This prevent endless loop if backtrace() touches
     * memory regions which cause abort
     */
    static bool triggered = false;

    lcd_set_backdrop(NULL);
    lcd_set_drawmode(DRMODE_SOLID);
    lcd_set_foreground(LCD_BLACK);
    lcd_set_background(LCD_WHITE);
    unsigned line = 0;

    lcd_setfont(FONT_SYSFIXED);
    lcd_set_viewport(NULL);
    lcd_clear_display();

    /* get context info */
    ucontext_t *uc = (ucontext_t *)context;
    unsigned long pc = uc->uc_mcontext.pc;
    unsigned long sp = uc->uc_mcontext.gregs[29];

    lcd_putsf(0, line++, "%s at %08x", strsignal(sig), pc);

    if(sig == SIGILL || sig == SIGFPE || sig == SIGSEGV || sig == SIGBUS || sig == SIGTRAP)
        lcd_putsf(0, line++, "address 0x%08x", siginfo->si_addr);

    if(!triggered)
    {
        triggered = true;
        rb_backtrace(pc, sp, &line);
    }

#ifdef ROCKBOX_HAS_LOGF
    lcd_putsf(0, line++, "logf:");
    logf_panic_dump(&line);
#endif

    lcd_update();

    system_exception_wait(); /* If this returns, try to reboot */
    system_reboot();
    while (1);       /* halt */
}
Exemple #5
0
void usb_enable(bool on)
{
    /* This device specific code will eventually give way to proper USB
       handling, which should be the same for all PP5002 targets. */
    if (on)
    {
#ifdef IPOD_ARCH
        /* For iPod, we can only do one thing with USB mode atm - reboot
           into the flash-based disk-mode.  This does not return. */

        ata_sleepnow(); /* Immediately spindown the disk. */
        sleep(HZ*2);

        memcpy((void *)0x40017f00, "diskmodehotstuff\1", 17);

        system_reboot(); /* Reboot */
#endif
    }
}
Exemple #6
0
static void try_reboot(void)
{
#ifdef HAVE_DISK_STORAGE
    storage_sleepnow(); /* Immediately spindown the disk. */
    sleep(HZ*2);
#endif

#ifdef IPOD_ARCH  /* The following code is based on ipodlinux */
#if CONFIG_CPU == PP5020
    memcpy((void *)0x40017f00, "diskmode\0\0hotstuff\0\0\1", 21);
#elif CONFIG_CPU == PP5022
    memcpy((void *)0x4001ff00, "diskmode\0\0hotstuff\0\0\1", 21);
#endif /* CONFIG_CPU */
#endif /* IPOD_ARCH */

#ifdef IPOD_NANO2G
    memcpy((void *)0x0002bf00, "diskmodehotstuff\1\0\0\0", 20);
#endif

    system_reboot(); /* Reboot */
}
/* prompt user to plug USB and fix a problem */
static void prompt_usb(const char* msg1, const char* msg2)
{
    int button;
    lcd_clear_display();
    lcd_puts(0, 0, msg1);
    lcd_puts(0, 1, msg2);
#ifdef HAVE_LCD_BITMAP
    lcd_puts(0, 2, "Insert USB cable");
    lcd_puts(0, 3, "and fix it.");
#endif
    lcd_update();
    do
    {
        button = button_get(true);
        if (button == SYS_POWEROFF)
        {
            power_off();
        }
    } while (button != SYS_USB_CONNECTED);
    usb_screen();
    system_reboot();
}
Exemple #8
0
int8_t sms_process_memory_message(int8_t index) {
	int t = 0, len = 0;
	char *token;
	char *msg = getSMSBufferHelper();
	char state[16];
	char ok[8];
	char phoneNumber[32];
	char *phone;
	char answer = 0;

	uart_txf("+CMGR=%d", index);

	int8_t uart_state = uart_getTransactionState();
	if (uart_state != UART_SUCCESS)
		return uart_state;

	PARSE_FINDSTR_RET(token, COMMAND_RESULT_CMGR, UART_FAILED);
	PARSE_FIRSTSTRING(token, state, sizeof(state), ",\n", UART_FAILED);
	PARSE_NEXTSTRING(token, phoneNumber, sizeof(phoneNumber), ",\n",
			UART_FAILED);

	len = strlen(phoneNumber);
	for (t = 0; t < len; t++)
		if (phoneNumber[t] == '\"')
			phoneNumber[t] = 0;

	PARSE_SKIP(token, "\n", UART_FAILED);

	PARSE_NEXTSTRING(token, msg, MAX_SMS_SIZE, "\n", UART_FAILED);

	// Jump first \n to get the OK
	PARSE_SKIP(token, "\n", UART_FAILED);
	ok[0] = 0;
	PARSE_NEXTSTRING(token, ok, sizeof(ok), "\n", UART_FAILED);
	if (ok[0] != 'O' || ok[1] != 'K')
		return UART_FAILED;

	phone = &phoneNumber[1];
	switch (msg[0]) {
	case '1':
		sms_send_data_request(phone); // Send the phone without the \"
		break;
	case 'R':
	case '2':
		sms_send_message_number(phone, "Rebooting...");
		delallmsg();
		for (t = 0; t < 10; t++) {
			lcd_printf(LINEC, "REBOOT DEVICE");
			lcd_printf(LINE2, "   *** %d ***  ", (10 - t));
			lcd_progress_wait(1000);
		}

		//reset the board by issuing a SW BOR
		system_reboot("NET_COMMAND");
		return UART_SUCCESS;
	case 'E':
		events_send_data(phone);
		break;
	case 'C':
		config_send_configuration(phone);
		break;
	case 'U':
		event_force_event_by_id(EVT_SUBSAMPLE_TEMP, 5);
		event_force_event_by_id(EVT_SAVE_SAMPLE_TEMP, 10);
		event_force_event_by_id(EVT_UPLOAD_SAMPLES, 15);
		answer = 1;
		break;
	case 'A':
		state_alarm_on("SMS_TRIGGER");
		answer = 1;
		break;

	default:
		if (msg[0] != '$')
			return UART_SUCCESS;

		if (config_parse_configuration(msg) == UART_SUCCESS)
			answer = 1;
		else {
			sms_send_message_number(phone, "FAILED");
			return UART_SUCCESS;
		}
		break;
	}

	if (answer)
		sms_send_message_number(phone, "ACK");

	return UART_SUCCESS;
}
Exemple #9
0
void system_exception_wait(void)
{
    system_reboot();
}
//**************************************************
// ファイルローダー
// 戻り値 0:何もしない, 1:強制終了する
//**************************************************
int fileloader(const char* str0, const char* str1)
{
	char fname[COMMAND_LENGTH];
	int size = 0;

#if BOARD == BOARD_GR
	int led = digitalRead(PIN_LED0) | ( digitalRead(PIN_LED1)<<1) | (digitalRead(PIN_LED2)<<2)| (digitalRead(PIN_LED3)<<3);
#else
	int led = digitalRead(RB_LED);
#endif


	char tc[2];
	char *fs[4];

	StopFlg = false;

	tc[0] = CommandData[0];
	tc[1] = CommandData[1];

	//USB_Serial->println(">");
	while(true){

		//LEDを点灯する
#if BOARD == BOARD_GR
		digitalWrite(PIN_LED0, HIGH);
		digitalWrite(PIN_LED1, HIGH);
		digitalWrite(PIN_LED2, HIGH);
		digitalWrite(PIN_LED3, HIGH);
#else
		digitalWrite(RB_LED, HIGH);
#endif
		//コマンド待ち
		USB_Serial->println();
		USB_Serial->print("WAKAYAMA.RB Board Ver.");
		USB_Serial->print(str0);
		if(str1[0] != 0){
			USB_Serial->print(", mruby ");
			USB_Serial->print(str1);
		}
		USB_Serial->println(" (H [ENTER])");
		USB_Serial->print(">");

		lineinput((char*)CommandData);

		USB_Serial->println();

		//DEBUG_PRINT("CommandData[0]", (char)CommandData[0]);

		if(CommandData[0] == '.'){
			CommandData[0] = tc[0];
			CommandData[1] = tc[1];

			USB_Serial->print(">");
			USB_Serial->println((char*)CommandData);
		}
		tc[0] = CommandData[0];
		tc[1] = CommandData[1];

		//DEBUG_PRINT("CommandData", (char*)CommandData);

		if (CommandData[0] == 'Z'){
			EEP.format();
		}
		else if (CommandData[0] == 'D'){
			if(strlen(CommandData) > 2){

				//ファイル名を取得
				int len = strlen(CommandData);
				for(int i=0; i<len; i++){
					if(CommandData[i] == ' '){
						fs[0] = &CommandData[i+1];
						break;
					}
				}
				strcpy(fname, fs[0]);
				EEP.fdelete((const char*)fname);
			}
		}
		else if (CommandData[0] == 'G' || CommandData[0] == 'F'){
			if(strlen(CommandData) > 2){

				//ファイル名を取得
				int len = strlen(CommandData);
				for(int i=0; i<len; i++){
					if(CommandData[i] == ' '){
						fs[0] = &CommandData[i+1];
						break;
					}
				}
				strcpy(fname, fs[0]);

				readfile(fname, CommandData[0]);
			}
		}
		else if (CommandData[0] == 'R'){
			if(strlen(CommandData) > 2){

				//ファイル名を取得
				int len = strlen(CommandData);
				for(int i=0; i<len; i++){
					if(CommandData[i] == ' '){
						fs[0] = &CommandData[i+1];
						break;
					}
				}
				strcpy(fname, fs[0]);
				strcpy( (char*)RubyFilename, fname );

				len = strlen(RubyFilename);
				if(RubyFilename[len-4] != '.'
					|| RubyFilename[len-3] != 'm'
					|| RubyFilename[len-2] != 'r'
					|| RubyFilename[len-1] != 'b'){
	
					strcat(RubyFilename, ".mrb");				
				}

				//強制終了フラグを立てる
				StopFlg = true;
				break;
			}
		}
		else if(CommandData[0] == 'W' || CommandData[0] == 'U'){
			if(strlen(CommandData) > 3){
				//スペースを0に変えて、ポインタを取得
				int j = 0;
				int len = strlen(CommandData);
				for(int i=0; i<len; i++){
					if(CommandData[i] == ' '){
						CommandData[i] = 0;
						fs[j] = &CommandData[i+1];
						j++;
						if(j>2){	break;	}
					}
				}
				strcpy(fname, fs[0]);
				size = atoi(fs[1]);

				//0xFEアックを返さないようにする
				if(Ack_FE_mode == 1 && CommandData[0] == 'W'){ Ack_FE_mode = 0; }

				//ファイルを保存します
				writefile(fname, size, CommandData[0]);

				//Ack_FE_mode==0だったら、0xFEアックを返すように戻す
				if(Ack_FE_mode == 0 && CommandData[0] == 'W'){ Ack_FE_mode = 1; }

				for(int i=0; i<j; i++){ *(fs[i] - 1) = ' '; }
			}
		}
		else if(CommandData[0] == 'X' || CommandData[0] == 'V'){
			if(strlen(CommandData) > 3){
				//スペースを0に変えて、ポインタを取得
				int j = 0;
				int len = strlen(CommandData);
				for(int i=0; i<len; i++){
					if(CommandData[i] == ' '){
						CommandData[i] = 0;
						fs[j] = &CommandData[i+1];
						j++;
						if(j>2){	break;	}
					}
				}
				strcpy(fname, fs[0]);
				size = atoi(fs[1]);

				strcpy( (char*)RubyFilename, fname );

				len = strlen(RubyFilename);
				if(RubyFilename[len-4] != '.'
					|| RubyFilename[len-3] != 'm'
					|| RubyFilename[len-2] != 'r'
					|| RubyFilename[len-1] != 'b'){
	
					strcat(RubyFilename, ".mrb");				
				}

				//0xFEアックを返さないようにする
				if(Ack_FE_mode == 1 && CommandData[0] == 'X'){ Ack_FE_mode = 0; }

				//ファイルを保存します
				writefile(RubyFilename, size, CommandData[0]);

				//Ack_FE_mode==0だったら、0xFEアックを返すように戻す
				if(Ack_FE_mode == 0 && CommandData[0] == 'X'){ Ack_FE_mode = 1; }

				for(int i=0; i<j; i++){ *(fs[i] - 1) = ' '; }

				//強制終了フラグを立てる
				StopFlg = true;
				break;
			}
		}
		else if(CommandData[0] == 'E'){
			//ファームウェア書き込み待ちにする
			system_reboot( REBOOT_USERAPP );	//リセット後にユーザアプリを起動する
			//system_reboot( REBOOT_FIRMWARE );	//リセット後にファームウェアを起動する
		}
		else if (CommandData[0] == 'L'){
			USB_Serial->println();
			for(int i=0; i<64; i++){
					
				size = EEP.fdir( i, fname );
					
				if(fname[0] != 0){
					USB_Serial->print(" ");
					USB_Serial->print(fname);
					USB_Serial->print(" ");
					USB_Serial->print(size);
					USB_Serial->println(" byte");
				}
			}
		}
		else if(CommandData[0] == 'A'){
			EEP.viewFat();
		}
		else if(CommandData[0] == 'S'){
			if(strlen(CommandData) > 2){

				int len = strlen(CommandData);
				for(int i=0; i<len; i++){
					if(CommandData[i] == ' '){
						fs[0] = &CommandData[i+1];
						break;
					}
				}
				EEP.viewSector( atoi(fs[0]) );
			}
		}
		else if(CommandData[0] == 'Q'){
			break;
		}
		else if (CommandData[0] == 'C'){
			USB_Serial->println();
			USB_Serial->println(LICENSE_MRUBY);
			USB_Serial->println(LICENSE_MRUBYURL);
			USB_Serial->println(LICENSE_WRBB);
			USB_Serial->println(LICENSE_WRBBURL);
		}
		else{
			USB_Serial->println();
			if(Ack_FE_mode == 1){
				USB_Serial->print("*");
			}
			USB_Serial->println("EEPROM FileWriter Ver. 1.61.v1");
			USB_Serial->println(" Command List");
			USB_Serial->println(" L:List Filename..........>L [ENTER]");
			USB_Serial->println(" W:Write File.............>W Filename Size [ENTER]");
			USB_Serial->println(" G:Get File...............>G Filename [ENTER]");
			USB_Serial->println(" F:Get File B2A...........>F Filename [ENTER]");
			USB_Serial->println(" D:Delete File............>D Filename [ENTER]");
			USB_Serial->println(" Z:Delete All Files.......>Z [ENTER]");
			USB_Serial->println(" A:List FAT...............>A [ENTER]");
			USB_Serial->println(" R:Run File...............>R Filename [ENTER]");
			USB_Serial->println(" X:Execute File...........>X Filename Size [ENTER]");
			USB_Serial->println(" S:List Sector............>S Number [ENTER]");
			USB_Serial->println(" .:Repeat.................>. [ENTER]");
			USB_Serial->println(" Q:Quit...................>Q [ENTER]");
			USB_Serial->println(" E:System Reset...........>E [ENTER]");
			USB_Serial->println(" U:Write File B2A.........>U Filename Size [ENTER]");
			//USB_Serial->println(" V:Execute File B2A.......>V Filename Size [ENTER]");
			USB_Serial->println(" C:License................>C [ENTER]");
		}
	}

#if BOARD == BOARD_GR
	digitalWrite(PIN_LED0, led & 1);
	digitalWrite(PIN_LED1, (led >> 1) & 1);
	digitalWrite(PIN_LED2, (led >> 2) & 1);
	digitalWrite(PIN_LED3, (led >> 3) & 1);
#else
	digitalWrite(RB_LED, led);
#endif

	if(StopFlg == true){
		return 1;
	}

	return 0;
}
Exemple #11
0
int main(int argc, char *argv[])
{
    client_data_t data;
    int result;
    lwm2m_context_t * lwm2mH = NULL;
    int i;
    const char * localPort = "56830";
    const char * server = NULL;
    const char * serverPort = LWM2M_STANDARD_PORT_STR;
    char * name = "testlwm2mclient";
    int lifetime = 300;
    int batterylevelchanging = 0;
    time_t reboot_time = 0;
    int opt;
    bool bootstrapRequested = false;
    bool serverPortChanged = false;

#ifdef LWM2M_BOOTSTRAP
    lwm2m_client_state_t previousState = STATE_INITIAL;
#endif

    char * pskId = NULL;
    char * psk = NULL;
    uint16_t pskLen = -1;
    char * pskBuffer = NULL;

    /*
     * The function start by setting up the command line interface (which may or not be useful depending on your project)
     *
     * This is an array of commands describes as { name, description, long description, callback, userdata }.
     * The firsts tree are easy to understand, the callback is the function that will be called when this command is typed
     * and in the last one will be stored the lwm2m context (allowing access to the server settings and the objects).
     */
    command_desc_t commands[] =
    {
            {"list", "List known servers.", NULL, prv_output_servers, NULL},
            {"change", "Change the value of resource.", " change URI [DATA]\r\n"
                                                        "   URI: uri of the resource such as /3/0, /3/0/2\r\n"
                                                        "   DATA: (optional) new value\r\n", prv_change, NULL},
            {"update", "Trigger a registration update", " update SERVER\r\n"
                                                        "   SERVER: short server id such as 123\r\n", prv_update, NULL},
#ifdef LWM2M_BOOTSTRAP
            {"bootstrap", "Initiate a DI bootstrap process", NULL, prv_initiate_bootstrap, NULL},
            {"dispb", "Display current backup of objects/instances/resources\r\n"
                    "\t(only security and server objects are backupped)", NULL, prv_display_backup, NULL},
#endif
            {"ls", "List Objects and Instances", NULL, prv_object_list, NULL},
            {"disp", "Display current objects/instances/resources", NULL, prv_display_objects, NULL},
            {"dump", "Dump an Object", "dump URI"
                                       "URI: uri of the Object or Instance such as /3/0, /1\r\n", prv_object_dump, NULL},
            {"add", "Add support of object 1024", NULL, prv_add, NULL},
            {"rm", "Remove support of object 1024", NULL, prv_remove, NULL},
            {"quit", "Quit the client gracefully.", NULL, prv_quit, NULL},
            {"^C", "Quit the client abruptly (without sending a de-register message).", NULL, NULL, NULL},

            COMMAND_END_LIST
    };

    memset(&data, 0, sizeof(client_data_t));
    data.addressFamily = AF_INET6;

    opt = 1;
    while (opt < argc)
    {
        if (argv[opt] == NULL
            || argv[opt][0] != '-'
            || argv[opt][2] != 0)
        {
            print_usage();
            return 0;
        }
        switch (argv[opt][1])
        {
        case 'b':
            bootstrapRequested = true;
            if (!serverPortChanged) serverPort = LWM2M_BSSERVER_PORT_STR;
            break;
        case 'c':
            batterylevelchanging = 1;
            break;
        case 't':
            opt++;
            if (opt >= argc)
            {
                print_usage();
                return 0;
            }
            if (1 != sscanf(argv[opt], "%d", &lifetime))
            {
                print_usage();
                return 0;
            }
            break;
#ifdef WITH_TINYDTLS
        case 'i':
            opt++;
            if (opt >= argc)
            {
                print_usage();
                return 0;
            }
            pskId = argv[opt];
            break;
        case 's':
            opt++;
            if (opt >= argc)
            {
                print_usage();
                return 0;
            }
            psk = argv[opt];
            break;
#endif						
        case 'n':
            opt++;
            if (opt >= argc)
            {
                print_usage();
                return 0;
            }
            name = argv[opt];
            break;
        case 'l':
            opt++;
            if (opt >= argc)
            {
                print_usage();
                return 0;
            }
            localPort = argv[opt];
            break;
        case 'h':
            opt++;
            if (opt >= argc)
            {
                print_usage();
                return 0;
            }
            server = argv[opt];
            break;
        case 'p':
            opt++;
            if (opt >= argc)
            {
                print_usage();
                return 0;
            }
            serverPort = argv[opt];
            serverPortChanged = true;
            break;
        case '4':
            data.addressFamily = AF_INET;
            break;
        default:
            print_usage();
            return 0;
        }
        opt += 1;
    }

    if (!server)
    {
        server = (AF_INET == data.addressFamily ? DEFAULT_SERVER_IPV4 : DEFAULT_SERVER_IPV6);
    }

    /*
     *This call an internal function that create an IPV6 socket on the port 5683.
     */
    fprintf(stderr, "Trying to bind LWM2M Client to port %s\r\n", localPort);
    data.sock = create_socket(localPort, data.addressFamily);
    if (data.sock < 0)
    {
        fprintf(stderr, "Failed to open socket: %d %s\r\n", errno, strerror(errno));
        return -1;
    }

    /*
     * Now the main function fill an array with each object, this list will be later passed to liblwm2m.
     * Those functions are located in their respective object file.
     */
#ifdef WITH_TINYDTLS
    if (psk != NULL)
    {
        pskLen = strlen(psk) / 2;
        pskBuffer = malloc(pskLen);

        if (NULL == pskBuffer)
        {
            fprintf(stderr, "Failed to create PSK binary buffer\r\n");
            return -1;
        }
        // Hex string to binary
        char *h = psk;
        char *b = pskBuffer;
        char xlate[] = "0123456789ABCDEF";

        for ( ; *h; h += 2, ++b)
        {
            char *l = strchr(xlate, toupper(*h));
            char *r = strchr(xlate, toupper(*(h+1)));

            if (!r || !l)
            {
                fprintf(stderr, "Failed to parse Pre-Shared-Key HEXSTRING\r\n");
                return -1;
            }

            *b = ((l - xlate) << 4) + (r - xlate);
        }
    }
#endif

    char serverUri[50];
    int serverId = 123;
    sprintf (serverUri, "coap://%s:%s", server, serverPort);
#ifdef LWM2M_BOOTSTRAP
    objArray[0] = get_security_object(serverId, serverUri, pskId, pskBuffer, pskLen, bootstrapRequested);
#else
    objArray[0] = get_security_object(serverId, serverUri, pskId, pskBuffer, pskLen, false);
#endif
    if (NULL == objArray[0])
    {
        fprintf(stderr, "Failed to create security object\r\n");
        return -1;
    }
    data.securityObjP = objArray[0];

    objArray[1] = get_server_object(serverId, "U", lifetime, false);
    if (NULL == objArray[1])
    {
        fprintf(stderr, "Failed to create server object\r\n");
        return -1;
    }

    objArray[2] = get_object_device();
    if (NULL == objArray[2])
    {
        fprintf(stderr, "Failed to create Device object\r\n");
        return -1;
    }

    objArray[3] = get_object_firmware();
    if (NULL == objArray[3])
    {
        fprintf(stderr, "Failed to create Firmware object\r\n");
        return -1;
    }

    objArray[4] = get_object_location();
    if (NULL == objArray[4])
    {
        fprintf(stderr, "Failed to create location object\r\n");
        return -1;
    }

    objArray[5] = get_test_object();
    if (NULL == objArray[5])
    {
        fprintf(stderr, "Failed to create test object\r\n");
        return -1;
    }

    objArray[6] = get_object_conn_m();
    if (NULL == objArray[6])
    {
        fprintf(stderr, "Failed to create connectivity monitoring object\r\n");
        return -1;
    }

    objArray[7] = get_object_conn_s();
    if (NULL == objArray[7])
    {
        fprintf(stderr, "Failed to create connectivity statistics object\r\n");
        return -1;
    }

    int instId = 0;
    objArray[8] = acc_ctrl_create_object();
    if (NULL == objArray[8])
    {
        fprintf(stderr, "Failed to create Access Control object\r\n");
        return -1;
    }
    else if (acc_ctrl_obj_add_inst(objArray[8], instId, 3, 0, serverId)==false)
    {
        fprintf(stderr, "Failed to create Access Control object instance\r\n");
        return -1;
    }
    else if (acc_ctrl_oi_add_ac_val(objArray[8], instId, 0, 0b000000000001111)==false)
    {
        fprintf(stderr, "Failed to create Access Control ACL default resource\r\n");
        return -1;
    }
    else if (acc_ctrl_oi_add_ac_val(objArray[8], instId, 999, 0b000000000000001)==false)
    {
        fprintf(stderr, "Failed to create Access Control ACL resource for serverId: 999\r\n");
        return -1;
    }
    /*
     * The liblwm2m library is now initialized with the functions that will be in
     * charge of communication
     */
    lwm2mH = lwm2m_init(&data);
    if (NULL == lwm2mH)
    {
        fprintf(stderr, "lwm2m_init() failed\r\n");
        return -1;
    }
	
#ifdef WITH_TINYDTLS
    data.lwm2mH = lwm2mH;
#endif

    /*
     * We configure the liblwm2m library with the name of the client - which shall be unique for each client -
     * the number of objects we will be passing through and the objects array
     */
    result = lwm2m_configure(lwm2mH, name, NULL, NULL, OBJ_COUNT, objArray);
    if (result != 0)
    {
        fprintf(stderr, "lwm2m_configure() failed: 0x%X\r\n", result);
        return -1;
    }

    signal(SIGINT, handle_sigint);

    /**
     * Initialize value changed callback.
     */
    init_value_change(lwm2mH);

    /*
     * As you now have your lwm2m context complete you can pass it as an argument to all the command line functions
     * precedently viewed (first point)
     */
    for (i = 0 ; commands[i].name != NULL ; i++)
    {
        commands[i].userData = (void *)lwm2mH;
    }
    fprintf(stdout, "LWM2M Client \"%s\" started on port %s\r\n", name, localPort);
    fprintf(stdout, "> "); fflush(stdout);
    /*
     * We now enter in a while loop that will handle the communications from the server
     */
    while (0 == g_quit)
    {
        struct timeval tv;
        fd_set readfds;

        if (g_reboot)
        {
            time_t tv_sec;

            tv_sec = lwm2m_gettime();

            if (0 == reboot_time)
            {
                reboot_time = tv_sec + 5;
            }
            if (reboot_time < tv_sec)
            {
                /*
                 * Message should normally be lost with reboot ...
                 */
                fprintf(stderr, "reboot time expired, rebooting ...");
                system_reboot();
            }
            else
            {
                tv.tv_sec = reboot_time - tv_sec;
            }
        }
        else if (batterylevelchanging) 
        {
            update_battery_level(lwm2mH);
            tv.tv_sec = 5;
        }
        else 
        {
            tv.tv_sec = 60;
        }
        tv.tv_usec = 0;

        FD_ZERO(&readfds);
        FD_SET(data.sock, &readfds);
        FD_SET(STDIN_FILENO, &readfds);

        /*
         * This function does two things:
         *  - first it does the work needed by liblwm2m (eg. (re)sending some packets).
         *  - Secondly it adjusts the timeout value (default 60s) depending on the state of the transaction
         *    (eg. retransmission) and the time between the next operation
         */
        result = lwm2m_step(lwm2mH, &(tv.tv_sec));
        if (result != 0)
        {
            fprintf(stderr, "lwm2m_step() failed: 0x%X\r\n", result);
            if(previousState == STATE_BOOTSTRAPPING)
            {
#ifdef WITH_LOGS
                fprintf(stdout, "[BOOTSTRAP] restore security and server objects\r\n");
#endif
                prv_connections_free(lwm2mH);
                prv_restore_objects(lwm2mH);
                lwm2mH->state = STATE_INITIAL;
            }
            else return -1;
        }
#ifdef LWM2M_BOOTSTRAP
        update_bootstrap_info(&previousState, lwm2mH);
#endif
        /*
         * This part will set up an interruption until an event happen on SDTIN or the socket until "tv" timed out (set
         * with the precedent function)
         */
        result = select(FD_SETSIZE, &readfds, NULL, NULL, &tv);

        if (result < 0)
        {
            if (errno != EINTR)
            {
              fprintf(stderr, "Error in select(): %d %s\r\n", errno, strerror(errno));
            }
        }
        else if (result > 0)
        {
            uint8_t buffer[MAX_PACKET_SIZE];
            int numBytes;

            /*
             * If an event happens on the socket
             */
            if (FD_ISSET(data.sock, &readfds))
            {
                struct sockaddr_storage addr;
                socklen_t addrLen;

                addrLen = sizeof(addr);

                /*
                 * We retrieve the data received
                 */
                numBytes = recvfrom(data.sock, buffer, MAX_PACKET_SIZE, 0, (struct sockaddr *)&addr, &addrLen);

                if (0 > numBytes)
                {
                    fprintf(stderr, "Error in recvfrom(): %d %s\r\n", errno, strerror(errno));
                }
                else if (0 < numBytes)
                {
                    char s[INET6_ADDRSTRLEN];
                    in_port_t port;

#ifdef WITH_TINYDTLS
                    dtls_connection_t * connP;
#else
                    connection_t * connP;
#endif
                    if (AF_INET == addr.ss_family)
                    {
                        struct sockaddr_in *saddr = (struct sockaddr_in *)&addr;
                        inet_ntop(saddr->sin_family, &saddr->sin_addr, s, INET6_ADDRSTRLEN);
                        port = saddr->sin_port;
                    }
                    else if (AF_INET6 == addr.ss_family)
                    {
                        struct sockaddr_in6 *saddr = (struct sockaddr_in6 *)&addr;
                        inet_ntop(saddr->sin6_family, &saddr->sin6_addr, s, INET6_ADDRSTRLEN);
                        port = saddr->sin6_port;
                    }
                    fprintf(stderr, "%d bytes received from [%s]:%hu\r\n", numBytes, s, ntohs(port));

                    /*
                     * Display it in the STDERR
                     */
                    output_buffer(stderr, buffer, numBytes, 0);

                    connP = connection_find(data.connList, &addr, addrLen);
                    if (connP != NULL)
                    {
                        /*
                         * Let liblwm2m respond to the query depending on the context
                         */
#ifdef WITH_TINYDTLS
                        int result = connection_handle_packet(connP, buffer, numBytes);
						if (0 != result)
                        {
                             printf("error handling message %d\n",result);
                        }
#else
                        lwm2m_handle_packet(lwm2mH, buffer, numBytes, connP);
#endif
                        conn_s_updateRxStatistic(objArray[7], numBytes, false);
                    }
                    else
                    {
                        fprintf(stderr, "received bytes ignored!\r\n");
                    }
                }
            }

            /*
             * If the event happened on the SDTIN
             */
            else if (FD_ISSET(STDIN_FILENO, &readfds))
            {
                numBytes = read(STDIN_FILENO, buffer, MAX_PACKET_SIZE - 1);

                if (numBytes > 1)
                {
                    buffer[numBytes] = 0;
                    /*
                     * We call the corresponding callback of the typed command passing it the buffer for further arguments
                     */
                    handle_command(commands, (char*)buffer);
                }
                if (g_quit == 0)
                {
                    fprintf(stdout, "\r\n> ");
                    fflush(stdout);
                }
                else
                {
                    fprintf(stdout, "\r\n");
                }
            }
        }
    }

    /*
     * Finally when the loop is left smoothly - asked by user in the command line interface - we unregister our client from it
     */
    if (g_quit == 1)
    {
#ifdef LWM2M_BOOTSTRAP
        close_backup_object();
#endif
        lwm2m_close(lwm2mH);
    }
    close(data.sock);
    connection_free(data.connList);

    clean_security_object(objArray[0]);
    lwm2m_free(objArray[0]);
    clean_server_object(objArray[1]);
    lwm2m_free(objArray[1]);
    free_object_device(objArray[2]);
    free_object_firmware(objArray[3]);
    free_object_location(objArray[4]);
    free_test_object(objArray[5]);
    free_object_conn_m(objArray[6]);
    free_object_conn_s(objArray[7]);
    acl_ctrl_free_object(objArray[8]);

#ifdef MEMORY_TRACE
    if (g_quit == 1)
    {
        trace_print(0, 1);
    }
#endif

    return 0;
}
Exemple #12
0
static void init(void)
{
    int rc;
    bool mounted = false;
#if CONFIG_CHARGING && (CONFIG_CPU == SH7034)
    /* if nobody initialized ATA before, I consider this a cold start */
    bool coldstart = (PACR2 & 0x4000) != 0; /* starting from Flash */
#endif

    system_init();
    kernel_init();

#ifdef HAVE_ADJUSTABLE_CPU_FREQ
    set_cpu_frequency(CPUFREQ_NORMAL);
#ifdef CPU_COLDFIRE
    coldfire_set_pllcr_audio_bits(DEFAULT_PLLCR_AUDIO_BITS);
#endif
    cpu_boost(true);
#endif
    
    buffer_init();

    settings_reset();

    i2c_init();
    
    power_init();

    enable_irq();
#ifdef CPU_ARM
    enable_fiq();
#endif
    /* current_tick should be ticking by now */
    CHART("ticking");

    lcd_init();
#ifdef HAVE_REMOTE_LCD
    lcd_remote_init();
#endif
    font_init();

    CHART(">show_logo");
    show_logo();
    CHART("<show_logo");
    lang_init(core_language_builtin, language_strings, 
              LANG_LAST_INDEX_IN_ARRAY);

#ifdef DEBUG
    debug_init();
#else
#ifdef HAVE_SERIAL
    serial_setup();
#endif
#endif

#if CONFIG_RTC
    rtc_init();
#endif
#ifdef HAVE_RTC_RAM
    CHART(">settings_load(RTC)");
    settings_load(SETTINGS_RTC); /* early load parts of global_settings */
    CHART("<settings_load(RTC)");
#endif

    adc_init();

    usb_init();
#if CONFIG_USBOTG == USBOTG_ISP1362
    isp1362_init();
#elif CONFIG_USBOTG == USBOTG_M5636
    m5636_init();
#endif

    backlight_init();

    button_init();

    powermgmt_init();

#if CONFIG_TUNER
    radio_init();
#endif

    /* Keep the order of this 3 (viewportmanager handles statusbars)
     * Must be done before any code uses the multi-screen API */
    CHART(">gui_syncstatusbar_init");
    gui_syncstatusbar_init(&statusbars);
    CHART("<gui_syncstatusbar_init");
    CHART(">sb_skin_init");
    sb_skin_init();
    CHART("<sb_skin_init");
    CHART(">gui_sync_wps_init");
    gui_sync_wps_init();
    CHART("<gui_sync_wps_init");
    CHART(">viewportmanager_init");
    viewportmanager_init();
    CHART("<viewportmanager_init");

#if CONFIG_CHARGING && (CONFIG_CPU == SH7034)
    /* charger_inserted() can't be used here because power_thread()
       hasn't checked power_input_status() yet */
    if (coldstart && (power_input_status() & POWER_INPUT_MAIN_CHARGER)
        && !global_settings.car_adapter_mode
#ifdef ATA_POWER_PLAYERSTYLE
        && !ide_powered() /* relies on probing result from bootloader */
#endif
        )
    {
        rc = charging_screen(); /* display a "charging" screen */
        if (rc == 1)            /* charger removed */
            power_off();
        /* "On" pressed or USB connected: proceed */
        show_logo();  /* again, to provide better visual feedback */
    }
#endif

    CHART(">storage_init");
    rc = storage_init();
    CHART("<storage_init");
    if(rc)
    {
#ifdef HAVE_LCD_BITMAP
        lcd_clear_display();
        lcd_putsf(0, 1, "ATA error: %d", rc);
        lcd_puts(0, 3, "Press ON to debug");
        lcd_update();
        while(!(button_get(true) & BUTTON_REL)); /*DO NOT CHANGE TO ACTION SYSTEM */
        dbg_ports();
#endif
        panicf("ata: %d", rc);
    }

#ifdef HAVE_EEPROM_SETTINGS
    CHART(">eeprom_settings_init");
    eeprom_settings_init();
    CHART("<eeprom_settings_init");
#endif

#ifndef HAVE_USBSTACK
    usb_start_monitoring();
    while (usb_detect() == USB_INSERTED)
    {
#ifdef HAVE_EEPROM_SETTINGS
        firmware_settings.disk_clean = false;
#endif
        /* enter USB mode early, before trying to mount */
        if (button_get_w_tmo(HZ/10) == SYS_USB_CONNECTED)
#if (CONFIG_STORAGE & STORAGE_MMC)
            if (!mmc_touched() ||
                (mmc_remove_request() == SYS_HOTSWAP_EXTRACTED))
#endif
            {
                gui_usb_screen_run();
                mounted = true; /* mounting done @ end of USB mode */
            }
#ifdef HAVE_USB_POWER
        if (usb_powered())      /* avoid deadlock */
            break;
#endif
    }
#endif

    if (!mounted)
    {
        CHART(">disk_mount_all");
        rc = disk_mount_all();
        CHART("<disk_mount_all");
        if (rc<=0)
        {
            lcd_clear_display();
            lcd_puts(0, 0, "No partition");
            lcd_puts(0, 1, "found.");
#ifdef HAVE_LCD_BITMAP
            lcd_puts(0, 2, "Insert USB cable");
            lcd_puts(0, 3, "and fix it.");
#endif
            lcd_update();

            while(button_get(true) != SYS_USB_CONNECTED) {};
            gui_usb_screen_run();
            system_reboot();
        }
    }

#if defined(SETTINGS_RESET) || (CONFIG_KEYPAD == IPOD_4G_PAD) || \
    (CONFIG_KEYPAD == IRIVER_H10_PAD)
#ifdef SETTINGS_RESET
    /* Reset settings if holding the reset button. (Rec on Archos,
       A on Gigabeat) */
    if ((button_status() & SETTINGS_RESET) == SETTINGS_RESET)
#else
    /* Reset settings if the hold button is turned on */
    if (button_hold())
#endif
    {
        splash(HZ*2, str(LANG_RESET_DONE_CLEAR));
        settings_reset();
    }
    else
#endif
    {
        CHART(">settings_load(ALL)");
        settings_load(SETTINGS_ALL);
        CHART("<settings_load(ALL)");
    }

    CHART(">init_dircache(true)");
    rc = init_dircache(true);
    CHART("<init_dircache(true)");
    if (rc < 0)
    {
#ifdef HAVE_TAGCACHE
        remove(TAGCACHE_STATEFILE);
#endif
    }

    CHART(">settings_apply(true)");
    settings_apply(true);        
    CHART("<settings_apply(true)");
    CHART(">init_dircache(false)");
    init_dircache(false);
    CHART("<init_dircache(false)");
#ifdef HAVE_TAGCACHE
    CHART(">init_tagcache");
    init_tagcache();
    CHART("<init_tagcache");
#endif

#ifdef HAVE_EEPROM_SETTINGS
    if (firmware_settings.initialized)
    {
        /* In case we crash. */
        firmware_settings.disk_clean = false;
        CHART(">eeprom_settings_store");
        eeprom_settings_store();
        CHART("<eeprom_settings_store");
    }
#endif
    playlist_init();
    tree_mem_init();
    filetype_init();
    scrobbler_init();
#if CONFIG_CODEC == SWCODEC
    tdspeed_init();
#endif /* CONFIG_CODEC == SWCODEC */

#if CONFIG_CODEC != SWCODEC
    /* No buffer allocation (see buffer.c) may take place after the call to
       audio_init() since the mpeg thread takes the rest of the buffer space */
    mp3_init( global_settings.volume,
              global_settings.bass,
              global_settings.treble,
              global_settings.balance,
              global_settings.loudness,
              global_settings.avc,
              global_settings.channel_config,
              global_settings.stereo_width,
              global_settings.mdb_strength,
              global_settings.mdb_harmonics,
              global_settings.mdb_center,
              global_settings.mdb_shape,
              global_settings.mdb_enable,
              global_settings.superbass);

     /* audio_init must to know the size of voice buffer so init voice first */
    talk_init();
#endif /* CONFIG_CODEC != SWCODEC */

    CHART(">audio_init");
    audio_init();
    CHART("<audio_init");

#if (CONFIG_CODEC == SWCODEC) && defined(HAVE_RECORDING) && !defined(SIMULATOR)
    pcm_rec_init();
#endif

    /* runtime database has to be initialized after audio_init() */
    cpu_boost(false);

#if CONFIG_CHARGING
    car_adapter_mode_init();
#endif
#ifdef IPOD_ACCESSORY_PROTOCOL
    iap_setup(global_settings.serial_bitrate);
#endif
#ifdef HAVE_ACCESSORY_SUPPLY
    accessory_supply_set(global_settings.accessory_supply);
#endif
#ifdef HAVE_LINEOUT_POWEROFF
    lineout_set(global_settings.lineout_active);
#endif
#ifdef HAVE_HOTSWAP_STORAGE_AS_MAIN
    CHART("<check_bootfile(false)");
    check_bootfile(false); /* remember write time and filesize */
    CHART(">check_bootfile(false)");
#endif
    CHART("<settings_apply_skins");
    settings_apply_skins();
    CHART(">settings_apply_skins");
}
Exemple #13
0
//**************************************************
// リセットします
// System.reset()
//**************************************************
mrb_value mrb_system_reset(mrb_state *mrb, mrb_value self)
{
	system_reboot( REBOOT_USERAPP );	//リセット後にユーザアプリを起動する

	return mrb_nil_value();	//戻り値は無しですよ。
}
Exemple #14
0
int lwm2mclient_main()
{
    client_data_t data;
    int result;
    lwm2m_context_t * lwm2mH = NULL;
    int i;
    const char * localPort = "56830";
    //const char * server = "beta-devices.zatar.com";
	const char * server = "leshan.eclipse.org";
	//const char * server = "5.39.83.206";
    const char * serverPort = LWM2M_STANDARD_PORT_STR;
    char * name = "ZebraBlr";
    int lifetime = 300;
    int batterylevelchanging = 0;
    time_t reboot_time = 0;
    int opt;
    bool bootstrapRequested = false;
#ifdef LWM2M_BOOTSTRAP
    lwm2m_bootstrap_state_t previousBootstrapState = NOT_BOOTSTRAPPED;
#endif

    /*
     * The function start by setting up the command line interface (which may or not be useful depending on your project)
     *
     * This is an array of commands describes as { name, description, long description, callback, userdata }.
     * The firsts tree are easy to understand, the callback is the function that will be called when this command is typed
     * and in the last one will be stored the lwm2m context (allowing access to the server settings and the objects).
     */
    command_desc_t commands[] =
    {
            {"list", "List known servers.", NULL, prv_output_servers, NULL},
            {"change", "Change the value of resource.", " change URI [DATA]\r\n"
                                                        "   URI: uri of the resource such as /3/0, /3/0/2\r\n"
                                                        "   DATA: (optional) new value\r\n", prv_change, NULL},
            {"update", "Trigger a registration update", " update SERVER\r\n"
                                                        "   SERVER: short server id such as 123\r\n", prv_update, NULL},
#ifdef LWM2M_BOOTSTRAP
            {"bootstrap", "Initiate a DI bootstrap process", NULL, prv_initiate_bootstrap, NULL},
            {"disp", "Display current objects/instances/resources", NULL, prv_display_objects, NULL},
            {"dispb", "Display current backup of objects/instances/resources\r\n"
                    "\t(only security and server objects are backupped)", NULL, prv_display_backup, NULL},
#endif
            {"ls", "List Objects and Instances", NULL, prv_object_list, NULL},
            {"dump", "Dump an Object", "dump URI"
                                       "URI: uri of the Object or Instance such as /3/0, /1\r\n", prv_object_dump, NULL},
            {"quit", "Quit the client gracefully.", NULL, prv_quit, NULL},
            {"^C", "Quit the client abruptly (without sending a de-register message).", NULL, NULL, NULL},

            COMMAND_END_LIST
    };

    memset(&data, 0, sizeof(client_data_t));
/* Zebra change: Reddy
    while ((opt = getopt(argc, argv, "bcl:n:p:t:h:")) != -1)
    {
        switch (opt)
        {
        case 'b':
            bootstrapRequested = true;
            break;
        case 'c':
            batterylevelchanging = 1;
            break;
        case 't':
            sscanf(optarg, "%d", &lifetime);
            break;
        case 'n':
            name = optarg;
            break;
        case 'l':
            localPort = optarg;
            break;
        case 'h':
            server = optarg;
            break;
        case 'p':
            serverPort = optarg;
            break;
        default:
            print_usage();
            return 0;
        }
    }
*/
    /*
     *This call an internal function that create an IPV6 socket on the port 5683.
     */
    fprintf(stderr, "Trying to bind LWM2M Client to port %s\r\n", localPort);
    data.sock = create_socket(localPort);
    if (data.sock < 0)
    {
        fprintf(stderr, "Failed to open socket: %d\r\n", errno);
        return -1;
    }

    /*
     * Now the main function fill an array with each object, this list will be later passed to liblwm2m.
     * Those functions are located in their respective object file.
     */
    char serverUri[50];
    int serverId = 123;
    sprintf (serverUri, "coap://%s:%s", server, serverPort);
	fprintf(stderr, " LWM2M serverUri %s\r\n", serverUri);
#ifdef LWM2M_BOOTSTRAP
    objArray[0] = get_security_object(serverId, serverUri, bootstrapRequested);
#else
    objArray[0] = get_security_object(serverId, serverUri, false);
#endif
    if (NULL == objArray[0])
    {
        fprintf(stderr, "Failed to create security object\r\n");
        return -1;
    }
    data.securityObjP = objArray[0];

    objArray[1] = get_server_object(serverId, "U", lifetime, false);
    if (NULL == objArray[1])
    {
        fprintf(stderr, "Failed to create server object\r\n");
        return -1;
    }

    objArray[2] = get_object_device();
    if (NULL == objArray[2])
    {
        fprintf(stderr, "Failed to create Device object\r\n");
        return -1;
    }

    objArray[3] = get_object_firmware();
    if (NULL == objArray[3])
    {
        fprintf(stderr, "Failed to create Firmware object\r\n");
        return -1;
    }

    objArray[4] = get_object_location();
    if (NULL == objArray[4])
    {
        fprintf(stderr, "Failed to create location object\r\n");
        return -1;
    }

    objArray[5] = get_test_object();
    if (NULL == objArray[5])
    {
        fprintf(stderr, "Failed to create test object\r\n");
        return -1;
    }

    objArray[6] = get_object_conn_m();
    if (NULL == objArray[6])
    {
        fprintf(stderr, "Failed to create connectivity monitoring object\r\n");
        return -1;
    }

    objArray[7] = get_object_conn_s();
    if (NULL == objArray[7])
    {
        fprintf(stderr, "Failed to create connectivity statistics object\r\n");
        return -1;
    }

    int instId = 0;
    objArray[8] = acc_ctrl_create_object();
    if (NULL == objArray[8])
    {
        fprintf(stderr, "Failed to create Access Control object\r\n");
        return -1;
    }
    else if (acc_ctrl_obj_add_inst(objArray[8], instId, 3, 0, serverId)==false)
    {
        fprintf(stderr, "Failed to create Access Control object instance\r\n");
        return -1;
    }
    else if (acc_ctrl_oi_add_ac_val(objArray[8], instId, 0, 0b000000000001111)==false)
    {
        fprintf(stderr, "Failed to create Access Control ACL default resource\r\n");
        return -1;
    }
    else if (acc_ctrl_oi_add_ac_val(objArray[8], instId, 999, 0b000000000000001)==false)
    {
        fprintf(stderr, "Failed to create Access Control ACL resource for serverId: 999\r\n");
        return -1;
    }
    /*
     * The liblwm2m library is now initialized with the functions that will be in
     * charge of communication
     */
    lwm2mH = lwm2m_init(prv_connect_server, prv_buffer_send, &data);
    if (NULL == lwm2mH)
    {
        fprintf(stderr, "lwm2m_init() failed\r\n");
        return -1;
    }

#ifdef LWM2M_BOOTSTRAP
    /*
     * Bootstrap state initialization
     */
    if (bootstrapRequested)
    {
        lwm2mH->bsState = BOOTSTRAP_REQUESTED;
    }
    else
    {
        lwm2mH->bsState = NOT_BOOTSTRAPPED;
    }
#endif

    /*
     * We configure the liblwm2m library with the name of the client - which shall be unique for each client -
     * the number of objects we will be passing through and the objects array
     */
    result = lwm2m_configure(lwm2mH, name, NULL, NULL, OBJ_COUNT, objArray);
    if (result != 0)
    {
        fprintf(stderr, "lwm2m_configure() failed: 0x%X\r\n", result);
        return -1;
    }

    signal(SIGINT, handle_sigint);

    /*
     * This function start your client to the LWM2M servers
     */
    result = lwm2m_start(lwm2mH);
    if (result != 0)
    {
        fprintf(stderr, "lwm2m_start() failed: 0x%X\r\n", result);
        return -1;
    }

    /**
     * Initialize value changed callback.
     */
    init_value_change(lwm2mH);

    /*
     * As you now have your lwm2m context complete you can pass it as an argument to all the command line functions
     * precedently viewed (first point)
     */
    for (i = 0 ; commands[i].name != NULL ; i++)
    {
        commands[i].userData = (void *)lwm2mH;
    }
    fprintf(stdout, "LWM2M Client \"%s\" started on port %s\r\n", name, localPort);
    fprintf(stdout, "> "); fflush(stdout);
    /*
     * We now enter in a while loop that will handle the communications from the server
     */
    while (0 == g_quit)
    {
        struct timeval tv;
        fd_set readfds;

        if (g_reboot)
        {
            time_t tv_sec;

            tv_sec = lwm2m_gettime();

            if (0 == reboot_time)
            {
                reboot_time = tv_sec + 5;
            }
            if (reboot_time < tv_sec)
            {
                /*
                 * Message should normally be lost with reboot ...
                 */
                fprintf(stderr, "reboot time expired, rebooting ...");
                system_reboot();
            }
            else
            {
                tv.tv_sec = reboot_time - tv_sec;
            }
        }
        else if (batterylevelchanging) 
        {
            update_battery_level(lwm2mH);
            tv.tv_sec = 5;
        }
        else 
        {
            tv.tv_sec = 60;
        }
        tv.tv_usec = 0;

        FD_ZERO(&readfds);
        FD_SET(data.sock, &readfds);
        FD_SET(STDIN_FILENO, &readfds);

        /*
         * This function does two things:
         *  - first it does the work needed by liblwm2m (eg. (re)sending some packets).
         *  - Secondly it adjusts the timeout value (default 60s) depending on the state of the transaction
         *    (eg. retransmission) and the time between the next operation
         */
        result = lwm2m_step(lwm2mH, &(tv.tv_sec));
        if (result != 0)
        {
            fprintf(stderr, "lwm2m_step() failed: 0x%X\r\n", result);
            return -1;
        }
#ifdef LWM2M_BOOTSTRAP
        update_bootstrap_info(&previousBootstrapState, lwm2mH);
#endif
        /*
         * This part will set up an interruption until an event happen on SDTIN or the socket until "tv" timed out (set
         * with the precedent function)
         */
        //result = select(FD_SETSIZE, &readfds, NULL, NULL, &tv);

        if (result < 0)
        {
            if (errno != EINTR)
            {
              fprintf(stderr, "Error in select(): %d\r\n", errno);
            }
        }
        else if (result > 0)
        {
            uint8_t buffer[MAX_PACKET_SIZE];
            int numBytes;

            /*
             * If an event happens on the socket
             */
            if (FD_ISSET(data.sock, &readfds))
            {
                //struct sockaddr_storage addr;
				struct sockaddr addr;
                uint32 addrLen;

                addrLen = sizeof(addr);

                /*
                 * We retrieve the data received
                 */
                //numBytes = recvfrom(data.sock, buffer, MAX_PACKET_SIZE, 0, (struct sockaddr *)&addr, &addrLen);
				numBytes = recvfrom(data.sock, buffer, MAX_PACKET_SIZE,0);

                if (0 > numBytes)
                {
                    fprintf(stderr, "Error in recvfrom(): %d\r\n", errno);
                }
                else if (0 < numBytes)
                {
                    char s[INET6_ADDRSTRLEN];
                    uint16 port;
                    connection_t * connP;

                    if (AF_INET == addr.sa_family)
                    {
                        struct sockaddr_in *saddr = (struct sockaddr_in *)&addr;
                        //inet_ntop(saddr->sin_family, &saddr->sin_addr, s, INET6_ADDRSTRLEN);
                        port = saddr->sin_port;
                    }
                    //else if (AF_INET6 == addr.ss_family)
                    //{
                    //    struct sockaddr_in6 *saddr = (struct sockaddr_in6 *)&addr;
                    //    inet_ntop(saddr->sin6_family, &saddr->sin6_addr, s, INET6_ADDRSTRLEN);
                    //    port = saddr->sin6_port;
                   // }
                    //fprintf(stderr, "%d bytes received from [%s]:%hu\r\n", numBytes, s, ntohs(port));

                    /*
                     * Display it in the STDERR
                     */
                    output_buffer(stderr, buffer, numBytes, 0);

                    connP = connection_find(data.connList, &addr, addrLen);
                    if (connP != NULL)
                    {
                        /*
                         * Let liblwm2m respond to the query depending on the context
                         */
                        lwm2m_handle_packet(lwm2mH, buffer, numBytes, connP);
                        conn_s_updateRxStatistic(objArray[7], numBytes, false);
                    }
                    else
                    {
                        fprintf(stderr, "received bytes ignored!\r\n");
                    }
                }
            }

            /*
             * If the event happened on the SDTIN
             */
            else if (FD_ISSET(STDIN_FILENO, &readfds))
            {
                numBytes = read(STDIN_FILENO, buffer, MAX_PACKET_SIZE - 1);

                if (numBytes > 1)
                {
                    buffer[numBytes] = 0;
                    fprintf(stderr, "STDIN %d bytes '%s'\r\n> ", numBytes, buffer);

                    /*
                     * We call the corresponding callback of the typed command passing it the buffer for further arguments
                     */
                    handle_command(commands, (char*)buffer);
                }
                if (g_quit == 0)
                {
                    fprintf(stdout, "\r\n> ");
                    fflush(stdout);
                }
                else
                {
                    fprintf(stdout, "\r\n");
                }
            }
        }
    }

    /*
     * Finally when the loop is left smoothly - asked by user in the command line interface - we unregister our client from it
     */
    if (g_quit == 1) {
#ifdef LWM2M_BOOTSTRAP
        close_backup_object();
#endif
        lwm2m_close(lwm2mH);
    }
    close(data.sock);
    connection_free(data.connList);

    return 0;
}