Beispiel #1
0
int main(int argc, char** argv) {
    gs_int32_t ch;
    me = argv[0];
    
    while ((ch = getopt(argc, argv, "hvt")) != -1) {
        switch(ch) {
            case 'h':
                print_usage_exit("help");
                break;
            case 'v':
                verbose=1;
                break;
            case 't':
                withtrace=1;
                break;
            default:
                break;
        }
    }
    
    argc -= optind;
    argv += optind;
    
    /* initialize host library and the sgroup  */
    
    if (argc<=1) {
        print_usage_exit("Not enough arguments");
    }
    
    init(argc, argv);
    
    process_data();
    
    gslog(LOG_EMERG,"%s::internal error reached unexpected end", me);
}
Beispiel #2
0
int main (int argc, char *argv[])
{
	int c;
	int r;
	int width = 0;
	int height = 0;
	int nrects = 0;
	unsigned int seed = 0;
	int (**tf) (int, int, int);
	
	while ((c = getopt(argc, argv, "w:h:n:s:?")) != -1) {
		switch (c) {
			case 'w':
				width = atoi(optarg);
				break;
			case 'h':
				height = atoi(optarg);
				break;
			case 'n':
				nrects = atoi(optarg);
				break;
			case 's':
				seed = (unsigned int) atoi(optarg);
				break;
			case '?':
			default:
				print_usage_exit();
				break;
		}
	}

	if (width == 0 ||
	    height == 0 ||
	    nrects == 0) {
		print_usage_exit();
	}
	
	if (seed == 0) {
		seed = s_gettimeofday();
	}
	
	printf("width = %d, height = %d, nrects = %d, seed = %u\n", width, height, nrects, seed);
	
	srand(seed);
	
	for (tf = test_functions; *tf; tf++) {
		r = (*tf)(width, height, nrects);
		if (r != 0) {
			printf("test failed, exiting with %d\n", r);
			exit(r);
		}
	}
	return 0;
}
int main(int argc, char *argv[])
{
    fd_set rfds;
    struct timeval tv;
    int retval;
    pid_t pid;
    char *cpSerialDevice = NULL;

    {
        static struct option long_options[] =
        {
            /* Required arguments */
            {"serial",                  required_argument,  NULL, 's'},

            /* Program options */
            {"help",                    no_argument,        NULL, 'h'},
            {"foreground",              no_argument,        NULL, 'f'},
            {"verbosity",               required_argument,  NULL, 'v'},
            {"baud",                    required_argument,  NULL, 'B'},
            {"interface",               required_argument,  NULL, 'I'},
            {"reset",                   no_argument,        NULL, 'R'},
            {"confignotify",            required_argument,  NULL, 'C'},
            {"activityled",             required_argument,  NULL, 'A'},

            /* Module options */
            {"frontend",                required_argument,  NULL, 'F'},
            {"diversity",               no_argument,        NULL, 'D'},
            
            /* 6LoWPAN network options */
            {"mode",                    required_argument,  NULL, 'm'},
            {"region",                  required_argument,  NULL, 'r'},
            {"channel",                 required_argument,  NULL, 'c'},
            {"pan",                     required_argument,  NULL, 'p'},
            {"network",                 required_argument,  NULL, 'j'},
            {"profile",                 required_argument,  NULL, 'P'},
            {"prefix",                  required_argument,  NULL, '6'},

            /* Security options */
            {"key",                     required_argument,  NULL, 'k'},
            {"authscheme",              required_argument,  NULL, 'a'},
            
            /* Radius with PAP options */
            {"radiusip",                required_argument,  NULL, 'i'},
            
            { NULL, 0, NULL, 0}
        };
        signed char opt;
        int option_index;

        while ((opt = getopt_long(argc, argv, "s:hfv:B:I:RC:A:F:Dm:r:c:p:j:P:6:k:a:i:", long_options, &option_index)) != -1) 
        {
            switch (opt) 
            {
                case 'h':
                    print_usage_exit(argv);
                    break;
                case 'f':
                    daemonize = 0;
                    break;
                case 'v':
                    verbosity = atoi(optarg);
                    break;
                case 'B':
                {
                    char *pcEnd;
                    errno = 0;
                    u32BaudRate = strtoul(optarg, &pcEnd, 0);
                    if (errno)
                    {
                        printf("Baud rate '%s' cannot be converted to 32 bit integer (%s)\n", optarg, strerror(errno));
                        print_usage_exit(argv);
                    }
                    if (*pcEnd != '\0')
                    {
                        printf("Baud rate '%s' contains invalid characters\n", optarg);
                        print_usage_exit(argv);
                    }
                    break;
                }
                case 's':
                    cpSerialDevice = optarg;
                    break;
                    
                case 'C':
                {
                    struct stat sStat;
                    
                    /* Check if the given program exists and is executable */
                    if (stat(optarg, &sStat) == 0)
                    {
                        /* File stat'd ok */
                        pcConfigProgram = optarg;
                        vprConfigChanged = ConfigChangedCallback;
                    }
                    else
                    {
                        printf("Config stat notification program '%s' (%s)\n", optarg, strerror(errno));
                        print_usage_exit(argv);
                    }
                    break;
                }
                
                case 'A':
                {
                    char *pcEnd;
                    uint32_t u32ActivityLED;
                    errno = 0;
                    u32ActivityLED = strtoul(optarg, &pcEnd, 0);
                    if (errno)
                    {
                        printf("Activity LED '%s' cannot be converted to 32 bit integer (%s)\n", optarg, strerror(errno));
                        print_usage_exit(argv);
                    }
                    if (*pcEnd != '\0')
                    {
                        printf("Activity LED '%s' contains invalid characters\n", optarg);
                        print_usage_exit(argv);
                    }
                    eActivityLED = u32ActivityLED;
                    break;
                }
                
                case 'F':
                    if (strcmp(optarg, "SP") == 0)
                    {
                        eRadioFrontEnd = E_FRONTEND_STANDARD_POWER;
                    }
                    else if (strcmp(optarg, "HP") == 0)
                    {
                        eRadioFrontEnd = E_FRONTEND_HIGH_POWER;
                    }
                    else if (strcmp(optarg, "ETSI") == 0)
                    {
                        eRadioFrontEnd = E_FRONTEND_ETSI;
                    }
                    else
                    {
                        printf("Unknown mode '%s' specified. Supported modes are 'coordinator', 'router', 'commissioning'\n", optarg);
                        print_usage_exit(argv);
                    }
                    break;
                    
                case 'D':
                    iAntennaDiversity = 1;
                    break;
                    
                case 'm':
                    if (strcmp(optarg, "coordinator") == 0)
                    {
                        eModuleMode = E_MODE_COORDINATOR;
                    }
                    else if (strcmp(optarg, "router") == 0)
                    {
                        eModuleMode = E_MODE_ROUTER;
                    }
                    else if (strcmp(optarg, "commissioning") == 0)
                    {
                        eModuleMode = E_MODE_COMMISSIONING;
                    }
                    else
                    {
                        printf("Unknown mode '%s' specified. Supported modes are 'coordinator', 'router', 'commissioning'\n", optarg);
                        print_usage_exit(argv);
                    }
                    break;
                    
                case 'r':
                {
                    char *pcEnd;
                    uint32_t u32Region;
                    errno = 0;
                    u32Region = strtoul(optarg, &pcEnd, 0);
                    if (errno)
                    {
                        printf("Region '%s' cannot be converted to 32 bit integer (%s)\n", optarg, strerror(errno));
                        print_usage_exit(argv);
                    }
                    if (*pcEnd != '\0')
                    {
                        printf("Region '%s' contains invalid characters\n", optarg);
                        print_usage_exit(argv);
                    }
                    if (u32Region > E_REGION_MAX)
                    {
                        printf("Invalid region '%s' specified\n", optarg);
                        print_usage_exit(argv);
                    }
                    eRegion = (uint8_t)u32Region;
                    break;
                }
                case 'c':
                {
                    char *pcEnd;
                    uint32_t u32Channel;
                    errno = 0;
                    u32Channel = strtoul(optarg, &pcEnd, 0);
                    if (errno)
                    {
                        printf("Channel '%s' cannot be converted to 32 bit integer (%s)\n", optarg, strerror(errno));
                        print_usage_exit(argv);
                    }
                    if (*pcEnd != '\0')
                    {
                        printf("Channel '%s' contains invalid characters\n", optarg);
                        print_usage_exit(argv);
                    }
                    if ( !((u32Channel == E_CHANNEL_AUTOMATIC) ||
                          ((u32Channel >= E_CHANNEL_MINIMUM) && 
                           (u32Channel <= E_CHANNEL_MAXIMUM))))
                    {
                        printf("Invalid Channel '%s' specified\n", optarg);
                        print_usage_exit(argv);
                    }
                    eChannel = (uint8_t)u32Channel;
                    break;
                }
                case 'p':
                {
                    char *pcEnd;
                    uint32_t u32PanID;
                    errno = 0;
                    u32PanID = strtoul(optarg, &pcEnd, 0);
                    if (errno)
                    {
                        printf("PAN ID '%s' cannot be converted to 32 bit integer (%s)\n", optarg, strerror(errno));
                        print_usage_exit(argv);
                    }
                    if (*pcEnd != '\0')
                    {
                        printf("PAN ID '%s' contains invalid characters\n", optarg);
                        print_usage_exit(argv);
                    }
                    if (u32PanID > 0xFFFF)
                    {
                        printf("Invalid PAN ID '%s' specified\n", optarg);
                        print_usage_exit(argv);
                    }
                    u16PanID = (uint16_t)u32PanID;
                    break;
                }
                case 'j':
                {
                    char *pcEnd;
                    uint32_t u32JenNetID;
                    errno = 0;
                    u32JenNetID = strtoul(optarg, &pcEnd, 0);
                    if (errno)
                    {
                        printf("JenNet ID '%s' cannot be converted to 32 bit integer (%s)\n", optarg, strerror(errno));
                        print_usage_exit(argv);
                    }
                    if (*pcEnd != '\0')
                    {
                        printf("JenNet ID '%s' contains invalid characters\n", optarg);
                        print_usage_exit(argv);
                    }
                    u32UserData = u32JenNetID;
                    break;
                }
                case 'P':
                {
                    char *pcEnd;
                    uint32_t u32JenNetProfile;
                    errno = 0;
                    u32JenNetProfile = strtoul(optarg, &pcEnd, 0);
                    if (errno)
                    {
                        printf("JenNet Profile '%s' cannot be converted to 32 bit integer (%s)\n", optarg, strerror(errno));
                        print_usage_exit(argv);
                    }
                    if (*pcEnd != '\0')
                    {
                        printf("JenNet Profile '%s' contains invalid characters\n", optarg);
                        print_usage_exit(argv);
                    }
                    if (u32JenNetProfile > 0xFF)
                    {
                        printf("Invalid JenNet Profile '%s' specified\n", optarg);
                        print_usage_exit(argv);
                    }
                    u8JenNetProfile = (uint8_t)u32JenNetProfile;
                    break;
                }
                case '6':
                {
                    int result;
                    struct in6_addr address;
                    
                    result = inet_pton(AF_INET6, optarg, &address);
                    if (result <= 0)
                    {
                        if (result == 0)
                        {
                            printf("Unknown host: %s\n", optarg);
                        }
                        else if (result < 0)
                        {
                            perror("inet_pton failed");
                        }
                        exit(EXIT_FAILURE);
                    }
                    else
                    {
                        u64NetworkPrefix =  ((uint64_t)address.s6_addr[0] << 56) | 
                                            ((uint64_t)address.s6_addr[1] << 48) | 
                                            ((uint64_t)address.s6_addr[2] << 40) | 
                                            ((uint64_t)address.s6_addr[3] << 32) |
                                            ((uint64_t)address.s6_addr[4] << 24) | 
                                            ((uint64_t)address.s6_addr[5] << 16) | 
                                            ((uint64_t)address.s6_addr[6] <<  8) | 
                                            ((uint64_t)address.s6_addr[7] <<  0);
                    }
                    break;
                }
                case  'I':
                    cpTunDevice = optarg;
                    break;
                    
                case  'R':
                    iResetCoordinator = 1;
                    break;
                    
                case 'k':
                {
                    int result;
                    
                    /* The network key is specified like an IPv6 address, in 8 groups of 16-bit hexadecimal values separated by colons (:) */
                    result = inet_pton(AF_INET6, optarg, &sSecurityKey);
                    if (result <= 0)
                    {
                        if (result == 0)
                        {
                            printf("Could not parse network key: %s\n", optarg);
                        }
                        else if (result < 0)
                        {
                            perror("inet_pton failed");
                        }
                        exit(EXIT_FAILURE);
                    }
                    iSecureNetwork = 1;
                    break;
                }
                
                case 'a':
                {
                    char *pcEnd;
                    uint32_t u32AuthScheme;
                    errno = 0;
                    u32AuthScheme = strtoul(optarg, &pcEnd, 0);
                    if (errno)
                    {
                        printf("Authorisation scheme '%s' cannot be converted to 32 bit integer (%s)\n", optarg, strerror(errno));
                        print_usage_exit(argv);
                    }
                    if (*pcEnd != '\0')
                    {
                        printf("Authorisation scheme '%s' contains invalid characters\n", optarg);
                        print_usage_exit(argv);
                    }

                    switch(u32AuthScheme)
                    {
                        case 0:
                            printf("Warning - no authorisation scheme selected\n");
                            eAuthScheme = u32AuthScheme;
                            break;
                            
                        case (1):
                            eAuthScheme = u32AuthScheme;
                            break;
                            
                        default:
                            printf("Unknown authorisation scheme selected (%d)\n", u32AuthScheme);
                            print_usage_exit(argv);
                            break;
                    }
                    break;
                }
                
                case 'i':
                {
                    switch(eAuthScheme)
                    {
                        case (E_AUTH_SCHEME_RADIUS_PAP):
                        {
                            int result = inet_pton(AF_INET6, optarg, &uAuthSchemeData.sRadiusPAP.sAuthServerIP);
                            if (result <= 0)
                            {
                                if (result == 0)
                                {
                                    printf("Unknown host: %s\n", optarg);
                                }
                                else if (result < 0)
                                {
                                    perror("inet_pton failed");
                                }
                                exit(EXIT_FAILURE);
                            }
                            break;
                        }
                        
                        default:
                            printf("Option '-i' is not appropriate for authorisation scheme %d\n", eAuthScheme);
                            break;
                    }
                    break;
                }
                    
                default: /* '?' */
                    print_usage_exit(argv);
            }
        }
    }
    
    /* Log everything into syslog */
    daemon_log_ident = daemon_ident_from_argv0(argv[0]);
    
    if (!cpSerialDevice)
    {
        print_usage_exit(argv);
    }
    
    if (daemonize)
    {
        /* Prepare for return value passing from the initialization procedure of the daemon process */
        if (daemon_retval_init() < 0) {
            daemon_log(LOG_ERR, "Failed to create pipe.");
            return 1;
        }

        /* Do the fork */
        if ((pid = daemon_fork()) < 0)
        {
            /* Exit on error */
            daemon_log(LOG_ERR, "Failed to fork() daemon process.");
            daemon_retval_done();
            return 1;
        } 
        else if (pid)
        { /* The parent */
            int ret;

            /* Wait for 20 seconds for the return value passed from the daemon process */
            if ((ret = daemon_retval_wait(20)) < 0)
            {
                daemon_log(LOG_ERR, "Could not recieve return value from daemon process: %s", strerror(errno));
                return 255;
            }

            if (ret == 0)
            {
                daemon_log(LOG_INFO, "Daemon process started.");
            }
            else
            {
                daemon_log(LOG_ERR, "Daemon returned %i.", ret);
            }
            return ret;
        } 
        else
        { /* The daemon */
            /* Close FDs */
            if (daemon_close_all(-1) < 0)
            {
                daemon_log(LOG_ERR, "Failed to close all file descriptors: %s", strerror(errno));

                /* Send the error condition to the parent process */
                daemon_retval_send(1);
                goto finish;
            }

            daemon_log_use = DAEMON_LOG_SYSLOG;

            /* Send OK to parent process */
            daemon_retval_send(0);

            daemon_log(LOG_INFO, "Daemon started");
        }
    }
    else
    {
        /* Running foreground - set verbosity */
        if (verbosity > LOG_WARNING)
        {
            daemon_set_verbosity(verbosity);
        }
    }

    FD_ZERO(&rfds);
    /* Wait up to five seconds. */
    tv.tv_sec = 5;
    tv.tv_usec = 0;
    
    if ((serial_open(cpSerialDevice, u32BaudRate) < 0) || (eTunDeviceOpen(cpTunDevice) != E_TUN_OK))
    {
        goto finish;
    }
    
    /* Install signal handlers */
    signal(SIGTERM, vQuitSignalHandler);
    signal(SIGINT, vQuitSignalHandler);
    
    eJennicModuleStart();
    
    while (bRunning)
    {
        int max_fd = 0;
        
        /* Wait up to one second each loop. */
        tv.tv_sec = 1;
        tv.tv_usec = 0;
        
        FD_ZERO(&rfds);
        FD_SET(serial_fd, &rfds);
        if (serial_fd > max_fd)
        {
            max_fd = serial_fd;
        }
        FD_SET(tun_fd, &rfds);
        if (tun_fd > max_fd)
        {
            max_fd = tun_fd;
        }

        /* Wait for data on one either the serial port or the TUN interface. */
        retval = select(max_fd + 1, &rfds, NULL, NULL, &tv);

        if (retval == -1)
        {
            daemon_log(LOG_ERR, "error in select(): %s", strerror(errno));
        }
        else if (retval)
        {
            int i;
            /* Got data on one of the file descriptors */
            for (i = 0; i < max_fd + 1; i++)
            {
                if (FD_ISSET(i, &rfds) && (i == serial_fd))
                {
                    if(bSL_ReadMessage(&sIncomingMsg.u8Type, &sIncomingMsg.u16Length, sizeof(sIncomingMsg.u8Message), sIncomingMsg.u8Message))
                    {
                        if (eJennicModuleProcessMessage(sIncomingMsg.u8Type, sIncomingMsg.u16Length, sIncomingMsg.u8Message) != E_MODULE_OK)
                        {
                            daemon_log(LOG_ERR, "Error communicating with border router module");
                            bRunning = FALSE;
                        }
                    }
                }
                else if (FD_ISSET(i, &rfds) && (i == tun_fd))
                {
                    if (eTunDeviceReadPacket() != E_TUN_OK)
                    {
                        daemon_log(LOG_ERR, "Error handling tun packet");
                    }
                    /* Kick the state machine to prompt the sending of a ping packet if necessary. */
                    if (eJennicModuleStateMachine(1) != E_MODULE_OK)
                    {
                        daemon_log(LOG_ERR, "Error communicating with border router module");
                        bRunning = FALSE;
                    }
                }
                else if (FD_ISSET(i, &rfds))
                {
                    daemon_log(LOG_DEBUG, "Data on unknown file desciptor (%d)", i);
                }
                else
                {
                    /* Should not get here */
                }
            }
        }
        else
        {
            /* Select timeout */
            if (eJennicModuleStateMachine(1) != E_MODULE_OK)
            {
                daemon_log(LOG_ERR, "Error communicating with border router module");
                bRunning = FALSE;
            }
        }
    }
    
    if (iResetCoordinator)
    {
        daemon_log(LOG_INFO, "Resetting Coordinator Module");    
        eJennicModuleReset();
    }
    
finish:
    if (daemonize)
    {
        daemon_log(LOG_INFO, "Daemon process exiting");  
    }
    return 0;
}
Beispiel #4
0
static void init(gs_int32_t argc, gs_sp_t argv[]) {
    void *pblk;
    gs_int32_t x, y, schema, pblklen, lcv;
    gs_sp_t c;
    gs_int8_t name[1024];
    gs_sp_t instance_name;
    gs_sp_t data_sink_name;
    gs_sp_t query_name;
    endpoint gshub;
    endpoint data_sink;
    endpoint dummyep;
    gs_uint32_t tip1,tip2,tip3,tip4;
    struct sockaddr_in server;
    
    if( (argc!=4) ) {
        print_usage_exit("Wrong number of paramters");
    }
    sprintf(name,"gsexit: %s %s %s %s ",argv[0],argv[1],argv[2],argv[3]);
    
    gsopenlog(name);
    
    
    if (sscanf(argv[0],"%u.%u.%u.%u:%hu",&tip1,&tip2,&tip3,&tip4,&(gshub.port))!= 5 ) {
        gslog(LOG_EMERG,"HUB IP NOT DEFINED");
        exit(1);
    }
    
    gshub.ip=htonl(tip1<<24|tip2<<16|tip3<<8|tip4);
    gshub.port=htons(gshub.port);
    instance_name=strdup(argv[1]);
    query_name=strdup(argv[2]);
    data_sink_name=strdup(argv[3]);
    
    if (set_hub(gshub)!=0) {
        gslog(LOG_EMERG,"Could not set hub");
        exit(1);
    }
    if (set_instance_name(instance_name)!=0) {
        gslog(LOG_EMERG,"Could not set instance name");
        exit(1);
    }
    
    if (get_initinstance(gshub,instance_name,&dummyep,1)!=0) {
        gslog(LOG_EMERG,"Did not receive signal that GS is initiated\n");
    }
    
    if (get_streamsink(gshub,data_sink_name,&data_sink,1) !=0 ) {
        gslog(LOG_EMERG,"Could not find data sink");
        exit(0);
    }
    
    if (ftaapp_init(BUFSIZE)!=0) {
        gslog(LOG_EMERG,"%s::error:could not initialize gscp\n", me);
        exit(1);
    }
    
    signal(SIGTERM, hand);
    signal(SIGINT, hand);
    signal(SIGPIPE, hand);
    
    if (verbose!=0) gslog(LOG_DEBUG,"Initializing FTAs\n");
    
    pblk = 0;
    pblklen = 0;
    
    fs.fta_id=ftaapp_add_fta(query_name,pblk?0:1,pblk?0:1,0,pblklen,pblk);
    if (fs.fta_id.streamid==0){
        gslog(LOG_EMERG,"%s::error:could not initialize fta %s\n",
              me,query_name);
        exit(1);
    }
    
    if ((c=ftaapp_get_fta_ascii_schema_by_name(query_name))==0){
        gslog(LOG_EMERG,"%s::error:could not get ascii schema for %s\n",
              me,query_name);
        exit(1);
    }
    
    //ftaapp_get_fta_ascii_schema_by_name uses static buffer so make a copy
    fs.asciischema=strdup(c);
    
    
    // Set parser version here
    parserversion=get_schemaparser_version();
    
    if ((fs.schema=ftaapp_get_fta_schema(fs.fta_id))<0) {
        gslog(LOG_EMERG,"%s::error:could not get schema for query\n",
              me,query_name);
        exit(1);
    }
    
    // Use all available fields
    if ((fs.numfields=ftaschema_tuple_len(fs.schema))<0) {
        gslog(LOG_EMERG,"%s::error:could not get number of fields for query %s\n",
              me,query_name);
        exit(1);
    }
    
    // Important that we only open the socket to the data sink AFTER we have subscribed to the output query as it uses it as a signal
    
    socket_desc = socket(AF_INET , SOCK_STREAM , 0);
    if (socket_desc == -1)
    {
        gslog(LOG_EMERG,"ERROR:could not create socket for data stream");
        exit(0);
    }
    server.sin_addr.s_addr = data_sink.ip;
    server.sin_family = AF_INET;
    server.sin_port = data_sink.port;
    
    if (connect(socket_desc , (struct sockaddr *)&server , sizeof(server)) < 0)
    {
        gslog(LOG_EMERG,"ERROR: could not open connection to data source");
        exit(0);
    }
    if (set_streamsubscription(gshub,instance_name,data_sink_name) !=0 ) {
        gslog(LOG_EMERG,"Could not announce streamsubscription for exit process");
        exit(0);
    }
  
    
}
int main(int argc, char *argv[])
{
	pid_t pid;
    const char *pcFD_GPIO   = NULL;
    const char *pcI2Cbus    = NULL;
    uint8_t     u8I2CAddress = 0;
    const char *pcPWR_GPIO  = NULL;
    
    {
        static struct option long_options[] =
        {
            /* Program options */
            {"help",                    no_argument,        NULL, 'h'},
            {"foreground",              no_argument,        NULL, 'f'},
            {"verbosity",               required_argument,  NULL, 'v'},
            
            {"gpio-fd",                 required_argument,  NULL, 0},
            {"i2c-bus",                 required_argument,  NULL, 1},
            {"i2c-address",             required_argument,  NULL, 2},
            {"gpio-pwr",                required_argument,  NULL, 3},

            { NULL, 0, NULL, 0}
        };
        signed char opt;
        int option_index;

        while ((opt = getopt_long(argc, argv, "hfv:", long_options, &option_index)) != -1) 
        {
            switch (opt) 
            {
                case 'h':
                    print_usage_exit(argv);
                    break;
                case 'f':
                    daemonize = 0;
                    break;
                case 'v':
                    verbosity = atoi(optarg);
                    break;
                
                case 0:
                    pcFD_GPIO = optarg;
                    break;
                    
                case 1:
                    pcI2Cbus = optarg;
                    break;
                    
                case 2:
                {
                    char *pcEnd;
                    errno = 0;
                    uint32_t u32I2CAddress = strtoul(optarg, &pcEnd, 0);
                    if (errno)
                    {
                        fprintf(stderr, "I2C Address '%s' cannot be converted to 32 bit integer (%s)\n", optarg, strerror(errno));
                        print_usage_exit(argv);
                    }
                    if (*pcEnd != '\0')
                    {
                        fprintf(stderr, "I2C Address '%s' contains invalid characters\n", optarg);
                        print_usage_exit(argv);
                    }
                    if (u32I2CAddress > 0x7F)
                    {
                        fprintf(stderr, "I2C Address '%s' outside allowable range (0x01 - 0x7F)\n", optarg);
                        print_usage_exit(argv);
                    }
                    u8I2CAddress = u32I2CAddress;
                    break;
                }
                
                case 3:
                    pcPWR_GPIO = optarg;
                    break;
                    
                default: /* '?' */
                    print_usage_exit(argv);
            }
        }
    }
    
    if (!pcFD_GPIO)
    {
        fprintf(stderr, "GPIO for field detect pin must be specified\n");
        print_usage_exit(argv);
    }
    
    if (!pcI2Cbus)
    {
        fprintf(stderr, "I2C bus must be specified\n");
        print_usage_exit(argv);
    }
    
    if (!u8I2CAddress)
    {
        fprintf(stderr, "I2C address must be specified\n");
        print_usage_exit(argv);
    }
    
    /* Log everything into syslog */
    daemon_log_ident = daemon_ident_from_argv0(argv[0]);
    
    if (daemonize)
    {
        /* Prepare for return value passing from the initialization procedure of the daemon process */
        if (daemon_retval_init() < 0) {
            daemon_log(LOG_ERR, "Failed to create pipe.");
            return 1;
        }

        /* Do the fork */
        if ((pid = daemon_fork()) < 0)
        {
            /* Exit on error */
            daemon_log(LOG_ERR, "Failed to fork() daemon process.");
            daemon_retval_done();
            return 1;
        } 
        else if (pid)
        { /* The parent */
            int ret;

            /* Wait for 20 seconds for the return value passed from the daemon process */
            if ((ret = daemon_retval_wait(20)) < 0)
            {
                daemon_log(LOG_ERR, "Could not recieve return value from daemon process: %s", strerror(errno));
                return 255;
            }

            if (ret == 0)
            {
                daemon_log(LOG_INFO, "Daemon process started.");
            }
            else
            {
                daemon_log(LOG_ERR, "Daemon returned %i.", ret);
            }
            return ret;
        } 
        else
        { /* The daemon */
            /* Close FDs */
            if (daemon_close_all(-1) < 0)
            {
                daemon_log(LOG_ERR, "Failed to close all file descriptors: %s", strerror(errno));

                /* Send the error condition to the parent process */
                daemon_retval_send(1);
                goto finish;
            }

            daemon_log_use = DAEMON_LOG_SYSLOG;

            /* Send OK to parent process */
            daemon_retval_send(0);

            daemon_log(LOG_INFO, "Daemon started");
        }
    }
    else
    {
        /* Running foreground - set verbosity */
        if (verbosity > LOG_WARNING)
        {
            daemon_set_verbosity(verbosity);
        }
    }

    /* Install signal handlers */
    signal(SIGTERM, vQuitSignalHandler);
    signal(SIGINT, vQuitSignalHandler);

    if (eNtagSetup(pcPWR_GPIO, pcFD_GPIO, pcI2Cbus, u8I2CAddress) == E_NFC_OK)
    {
        if (eNdefSetup() == E_NFC_OK)
        {
            while (bRunning != 0)
            {
                if (eNtagWait(30000) == E_NFC_READER_PRESENT)
                {
                    /* Tag detected */
                    while ((eNtagPresent() == E_NFC_READER_PRESENT) && bRunning)
                    {
                        sleep(1);
                        
                        teNfcStatus eStatus = eNtagRfUnlocked();
                        
                        switch (eStatus)
                        {
                            case (E_NFC_OK):
                                vHandleTag();
                                break;
                                
                            case (E_NFC_RF_LOCKED):
                                DEBUG_PRINTF("RF Locked\n");
                                break;
                                
                            default:
                                break;
                        }
                        //usleep(100000);
                        //sleep(1);
                    }
                }
                else
                {
                    /* Blank the tag */
                    tsNdefData sData;
                    eNdefInitData(&sData, 0, 0);
                    eNdefWriteData(&sData);
                }
            }
        }
    }
    else
    {
        DEBUG_PRINTF("Failed to init NTAG\n");
    }
    
finish:
    if (daemonize)
    {
        daemon_log(LOG_INFO, "Daemon process exiting");  
    }
    return 0;
}
Beispiel #6
0
static void process_options (int argc, char *argv[])
{
	int error = 0;

	while( 1 ) {
		int optind = 0;

		static struct option longopts[] = {
			{"pipe",      no_argument,	 NULL, 'p'},
			{"datasize",  required_argument, NULL, 's'},
			{"loops",     required_argument, NULL, 'l'},
			{"groups",    required_argument, NULL, 'g'},
			{"fds",	      required_argument, NULL, 'f'},
			{"threads",   no_argument,	 NULL, 'T'},
			{"processes", no_argument,	 NULL, 'P'},
			{"help",      no_argument,	 NULL, 'h'},
			{NULL, 0, NULL, 0}
		};

		int c = getopt_long(argc, argv, "ps:l:g:f:TPh",
				    longopts, &optind);
		if (c == -1) {
			break;
		}
		switch (c) {
		case 'p':
			use_pipes = 1;
			break;

		case 's':
			if (!(argv[optind] && (datasize = atoi(optarg)) > 0)) {
				fprintf(stderr, "%s: --datasize|-s requires an integer > 0\n", argv[0]);
				error = 1;
			}
			break;

		case 'l':
			if (!(argv[optind] && (loops = atoi(optarg)) > 0)) {
				fprintf(stderr, "%s: --loops|-l requires an integer > 0\n", argv[0]);
				error = 1;
			}
			break;

		case 'g':
			if (!(argv[optind] && (num_groups = atoi(optarg)) > 0)) {
				fprintf(stderr, "%s: --groups|-g requires an integer > 0\n", argv[0]);
				error = 1;
			}
			break;

		case 'f':
			if (!(argv[optind] && (num_fds = atoi(optarg)) > 0)) {
				fprintf(stderr, "%s: --fds|-f requires an integer > 0\n", argv[0]);
				error = 1;
			}
			break;

		case 'T':
			process_mode = 0;
			break;
		case 'P':
			process_mode = 1;
			break;

		case 'h':
			print_usage_exit();

		default:
			error = 1;
		}
	}

	if( error ) {
		exit(1);
	}
}
Beispiel #7
0
int main(int argc, char *argv[])
{
	unsigned int i, num_groups = 10, total_children;
	struct timeval start, stop, diff;
	unsigned int num_fds = 20;
	int readyfds[2], wakefds[2];
	char dummy;
	pthread_t *pth_tab;

	if (argv[1] && strcmp(argv[1], "-pipe") == 0) {
		use_pipes = 1;
		argc--;
		argv++;
	}

	if (argc >= 2 && (num_groups = atoi(argv[1])) == 0)
		print_usage_exit();

	printf("Running with %d*40 (== %d) tasks.\n",
			num_groups, num_groups*40);

	fflush(NULL);

	if (argc > 2) {
		if ( !strcmp(argv[2], "process") )
			process_mode = 1;
		else if ( !strcmp(argv[2], "thread") )
			process_mode = 0;
		else
			print_usage_exit();
	}

	if (argc > 3)
		loops = atoi(argv[3]);

	pth_tab = malloc(num_fds * 2 * num_groups * sizeof(pthread_t));

	if (!pth_tab)
		barf("main:malloc()");

	fdpair(readyfds);
	fdpair(wakefds);

	total_children = 0;
	for (i = 0; i < num_groups; i++)
		total_children += group(pth_tab+total_children, num_fds, readyfds[1], wakefds[0]);

	/* Wait for everyone to be ready */
	for (i = 0; i < total_children; i++)
		if (read(readyfds[0], &dummy, 1) != 1)
			barf("Reading for readyfds");

	gettimeofday(&start, NULL);

	/* Kick them off */
	if (write(wakefds[1], &dummy, 1) != 1)
		barf("Writing to start them");

	/* Reap them all */
	for (i = 0; i < total_children; i++)
		reap_worker(pth_tab[i]);

	gettimeofday(&stop, NULL);

	/* Print time... */
	timersub(&stop, &start, &diff);
	printf("Time: %lu.%03lu\n", diff.tv_sec, diff.tv_usec/1000);
	exit(0);
}
Beispiel #8
0
int main(int argc, char *argv[])
{
    tsChipDetails   sChipDetails;
    int             iUartFd;
    struct termios  sUartOptions;
    
    tsFW_Info sFW_Info;
    int iVerify = 0;

    printf("JennicModuleProgrammer Version: %s\n", Version);
    
    {
        static struct option long_options[] =
        {
            {"help",                    no_argument,        NULL,       'h'},
            {"verbosity",               required_argument,  NULL,       'V'},
            {"initialbaud",             required_argument,  NULL,       'I'},
            {"programbaud",             required_argument,  NULL,       'P'},
            {"serial",                  required_argument,  NULL,       's'},
            {"firmware",                required_argument,  NULL,       'f'},
            {"verify",                  no_argument,        NULL,       'v'},
            {"mac",                     required_argument,  NULL,       'm'},
            { NULL, 0, NULL, 0}
        };
        signed char opt;
        int option_index;
        
        while ((opt = getopt_long(argc, argv, "hs:V:f:vI:P:m:", long_options, &option_index)) != -1) 
        {
            switch (opt) 
            {
                case 0:
                    
                case 'h':
                    print_usage_exit(argv);
                    break;
                case 'V':
                    iVerbosity = atoi(optarg);
                    break;
                case 'v':
                    iVerify = 1;
                    break;
                case 'I':
                {
                    char *pcEnd;
                    errno = 0;
                    iInitialSpeed = strtoul(optarg, &pcEnd, 0);
                    if (errno)
                    {
                        printf("Initial baud rate '%s' cannot be converted to 32 bit integer (%s)\n", optarg, strerror(errno));
                        print_usage_exit(argv);
                    }
                    if (*pcEnd != '\0')
                    {
                        printf("Initial baud rate '%s' contains invalid characters\n", optarg);
                        print_usage_exit(argv);
                    }
                    break;
                }
                case 'P':
                {
                    char *pcEnd;
                    errno = 0;
                    iProgramSpeed = strtoul(optarg, &pcEnd, 0);
                    if (errno)
                    {
                        printf("Program baud rate '%s' cannot be converted to 32 bit integer (%s)\n", optarg, strerror(errno));
                        print_usage_exit(argv);
                    }
                    if (*pcEnd != '\0')
                    {
                        printf("Program baud rate '%s' contains invalid characters\n", optarg);
                        print_usage_exit(argv);
                    }
                    break;
                }
                case 's':
                    cpSerialDevice = optarg;
                    break;
                case 'f':
                    pcFirmwareFile = optarg;
                    break;
                case 'm':
                    pcMAC_Address = optarg;
                    u64MAC_Address = strtoll(pcMAC_Address, (char **) NULL, 16);
                    pu64MAC_Address = &u64MAC_Address;
                    break;

                default: /* '?' */
                    print_usage_exit(argv);
            }
        }
    }

    if ((!cpSerialDevice))
    {
        /* Missing parameters */
        print_usage_exit(argv);
    }
    
    if (UART_eInitialise((char *)cpSerialDevice, iInitialSpeed, &iUartFd, &sUartOptions) != E_STATUS_OK)
    {
        fprintf(stderr, "Error opening serial port\n");
        return -1;
    }

    if (iInitialSpeed != iProgramSpeed)
    {
        if (iVerbosity > 1)
        {
            printf("Setting baudrate: %d\n", iProgramSpeed);
        }

        /* Talking at initial speed - change bootloader to programming speed */
        if (BL_eSetBaudrate(iUartFd, iProgramSpeed) != E_STATUS_OK)
        {
            printf("Error setting baudrate\n");
            return -1;
        }
        /* change local port to programming speed */
        if (UART_eSetBaudRate(iUartFd, &sUartOptions, iProgramSpeed) != E_STATUS_OK)
        {
            printf("Error setting baudrate\n");
            return -1;
        }
    }


    /* Read module details at initial baud rate */
    if (BL_eGetChipDetails(iUartFd, &sChipDetails) != E_STATUS_OK)
    {
        fprintf(stderr, "Error reading module information - check cabling and power\n");
        return -1;
    }

    
    if (iVerbosity > 0)
    {
        const char *pcPartName;
        
        switch (sChipDetails.u32ChipId)
        {
            case (CHIP_ID_JN5148_REV2A):    pcPartName = "JN5148";      break;
            case (CHIP_ID_JN5148_REV2B):    pcPartName = "JN5148";      break;
            case (CHIP_ID_JN5148_REV2C):    pcPartName = "JN5148";      break;
            case (CHIP_ID_JN5148_REV2D):    pcPartName = "JN5148J01";   break;
            case (CHIP_ID_JN5148_REV2E):    pcPartName = "JN5148Z01";   break;
            
            case (CHIP_ID_JN5142_REV1A):    pcPartName = "JN5142";      break;
            case (CHIP_ID_JN5142_REV1B):    pcPartName = "JN5142";      break;
            case (CHIP_ID_JN5142_REV1C):    pcPartName = "JN5142J01";   break;

            case (CHIP_ID_JN5168):          pcPartName = "JN516x";      break;
            
            default:                        pcPartName = "Unknown";     break;
        }
        
        printf("Detected Chip: %s\n", pcPartName);
        
        printf("MAC Address:   %02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X\n", 
                sChipDetails.au8MacAddress[0] & 0xFF, sChipDetails.au8MacAddress[1] & 0xFF, sChipDetails.au8MacAddress[2] & 0xFF, sChipDetails.au8MacAddress[3] & 0xFF, 
                sChipDetails.au8MacAddress[4] & 0xFF, sChipDetails.au8MacAddress[5] & 0xFF, sChipDetails.au8MacAddress[6] & 0xFF, sChipDetails.au8MacAddress[7] & 0xFF);
    }


    if (pcFirmwareFile)
    {
        /* Have file to program */
    
        if (iFW_Open(&sFW_Info, (char *)pcFirmwareFile))
        {
            /* Error with file. FW module has displayed error so just exit. */
            return -1;
        }

        if (BL_eReprogram(iUartFd, &sChipDetails, &sFW_Info) != E_STATUS_OK)
        {
            return -1;
        }
    }
    
    printf("Success\n");
    return 0;
}
int main(int argc, char *argv[])
{
    int ret, i;
    struct ftdi_device_list *devlist, *curdev;
    struct ftdi_context ftdic;
    struct ftdi_eeprom  eeprom;

    for (i = 0; i < CBUS_NUM; i++)
    {
        apcCBUS[i] = NULL;
    }

    {
        static struct option long_options[] =
        {

            {"help",                    no_argument,        NULL, 'h'},
            {"verbosity",               required_argument,  NULL, 'V'},

            {"vid",                     required_argument,  NULL, 'v'},
            {"pid",                     required_argument,  NULL, 'p'},

            {"manufacturer",            required_argument,  NULL, 'm'},
            {"description",             required_argument,  NULL, 'd'},

            {"serial",                  required_argument,  NULL, 's'},
            {"autoserial",              required_argument,  NULL, 'a'},

            {"C0",                      required_argument,  NULL, '0'},
            {"C1",                      required_argument,  NULL, '1'},
            {"C2",                      required_argument,  NULL, '2'},
            {"C3",                      required_argument,  NULL, '3'},
            {"C4",                      required_argument,  NULL, '4'},

            { NULL, 0, NULL, 0}
        };
        signed char opt;
        int option_index;

        while ((opt = getopt_long(argc, argv, "hV:v:p:m:d:s:a:0:1:2:3:4:", long_options, &option_index)) != -1)
        {
            switch (opt)
            {
            case 'h':
                print_usage_exit(argv);
                break;

            case 'V':
                if (iMyStrtoul(&u32Verbosity, optarg, "verbosity", 2))
                {
                    return EXIT_FAILURE;
                }
                break;

            case 'v':
                if (iMyStrtoul(&u32VID, optarg, "vendor id", 0xFFFF))
                {
                    return EXIT_FAILURE;
                }
                break;

            case 'p':
                if (iMyStrtoul(&u32PID, optarg, "product id", 0xFFFF))
                {
                    return EXIT_FAILURE;
                }
                break;

            case 'm':
                pcManufacturer = optarg;
                break;

            case 'd':
                pcDescription = optarg;
                break;

            case 's':
                pcSerial = optarg;
                break;

            case 'a':
                pcAutoSerial = optarg;
                break;

            case '0':
                apcCBUS[0] = optarg;
                break;

            case '1':
                apcCBUS[1] = optarg;
                break;

            case '2':
                apcCBUS[2] = optarg;
                break;

            case '3':
                apcCBUS[3] = optarg;
                break;

            case '4':
                apcCBUS[4] = optarg;
                break;

            default: /* '?' */
                print_usage_exit(argv);
            }
        }
    }

    printf("FTProg FTDI Programmer version %s\n\r", Version);

    /* Handle serial numbers */
    if (pcSerial && pcAutoSerial)
    {
        fprintf(stderr, "Please specify only one of serial number and autoserial\n\r");
        return EXIT_FAILURE;
    }

    if (pcSerial)
    {
        if (strlen(pcSerial) != 8)
        {
            fprintf(stderr, "Serial number must be 8 character string\n\r");
            return EXIT_FAILURE;
        }
    }

    if (pcAutoSerial)
    {
        int fd;
        if (strlen(pcAutoSerial) != 2)
        {
            fprintf(stderr, "Serial number prefix must be 2 character string\n\r");
            return EXIT_FAILURE;
        }

        pcSerial = malloc(sizeof(char) * 9);
        if (!pcSerial)
        {
            fprintf(stderr, "Memory error\n");
            return EXIT_FAILURE;
        }
        pcSerial[0] = pcAutoSerial[0];
        pcSerial[1] = pcAutoSerial[1];

        if ((fd = open("/dev/urandom", O_RDONLY)) < 0)
        {
            fprintf(stderr, "Could not open /dev/urandom (%s)\n\r", strerror(errno));
            return EXIT_FAILURE;
        }
        for (i = 2; i < 8; i++)
        {
            uint32_t j;
            read(fd, &j, 1);
            pcSerial[i] = "0123456789ABCDEF"[j % 16];
        }
        close(fd);

        pcSerial[8] = '\0';
        if (u32Verbosity > 0)
        {
            printf("Autogenerated serial number: '%s'\n", pcSerial);
        }
    }


    for (i = 0; i < CBUS_NUM; i++)
    {
        if (apcCBUS[i])
        {
            int j, iFound = 0;
            for (j = 0; j < (sizeof(asCBUSModeLookup)/sizeof(tsCBUSModeLookup)); j++)
            {
                if (strcmp(apcCBUS[i], asCBUSModeLookup[j].pcDescription) == 0)
                {
                    iFound = 1;
                    apsCBUS_Function[i] = &asCBUSModeLookup[j];
                }
            }
            if (!iFound)
            {
                fprintf(stderr, "Invalid C%d '%s'\n\r", i, apcCBUS[i]);
                return EXIT_FAILURE;
            }
        }
    }

    if (ftdi_init(&ftdic) < 0)
    {
        fprintf(stderr, "ftdi_init failed\n");
        return EXIT_FAILURE;
    }

    if ((ret = ftdi_usb_find_all(&ftdic, &devlist, u32VID, u32PID)) < 0)
    {
        fprintf(stderr, "ftdi_usb_find_all failed: %d (%s)\n", ret, ftdi_get_error_string(&ftdic));
        return EXIT_FAILURE;
    }

    printf("Number of FTDI devices found: %d\n", ret);

    for (i=0, curdev = devlist; curdev != NULL; i++, curdev = curdev->next)
    {
        printf(" Updating device: %d\n\r", i);

        if ((ret = ftdi_usb_open_dev(&ftdic, curdev->dev)) < 0)
        {
            fprintf(stderr, "ftdi_usb_open_dev failed: %d (%s)\n", ret, ftdi_get_error_string(&ftdic));
            return EXIT_FAILURE;
        }

        // Read out FTDIChip-ID of R type chips
        if (ftdic.type == TYPE_R)
        {
            unsigned char *pcEepromBuffer = NULL;
            unsigned int chipid;

            if ((ret = ftdi_read_chipid(&ftdic, &chipid)) < 0)
            {
                fprintf(stderr, "ftdi_read_chipid failed: %d (%s)\n", ret, ftdi_get_error_string(&ftdic));
                return EXIT_FAILURE;
            }

            printf("  FTDI chipid: %X\n", chipid);

            /* EEPROM is 160 bytes */
            ftdi_eeprom_setsize(&ftdic, &eeprom, 160);

            printf("  EEPROM size: %d bytes\n", ftdic.eeprom_size);
            pcEepromBuffer = malloc(ftdic.eeprom_size);
            if (!pcEepromBuffer)
            {
                fprintf(stderr, "Memory error!");
                return EXIT_FAILURE;
            }
            else
            {

                int i;
                if ((ret = ftdi_read_eeprom(&ftdic, pcEepromBuffer)) < 0)
                {
                    fprintf(stderr, "ftdi_read_eeprom failed: %d (%s)\n", ret, ftdi_get_error_string(&ftdic));
                    return EXIT_FAILURE;
                }
                if ((ret = ftdi_eeprom_decode(&eeprom, pcEepromBuffer, ftdic.eeprom_size)) < 0)
                {
                    if (ret != -1)
                    {
                        /* Avoid errors due to hard coded size causing checksum to fail. */
                        fprintf(stderr, "Error decoding eeprom buffer: %d (%s)\n", ret, ftdi_get_error_string(&ftdic));
                        return EXIT_FAILURE;
                    }
                }

                if (u32Verbosity > 0)
                {
                    printf("    Current Vendor: %d, %s\n", eeprom.vendor_id, eeprom.manufacturer);
                    printf("    Current Product: %d, %s\n", eeprom.product_id, eeprom.product);
                    printf("    Current Serial: %s\n", eeprom.serial);

                    if (u32Verbosity >= 2)
                    {
                        printf("      Current EEPROM Contents\n\r");
                        for (i = 0; i < ftdic.eeprom_size; i+=2)
                        {
                            if ((i % 16) == 0)
                            {
                                printf("        %04x:", i/2);
                            }
                            printf(" 0x%02x%02x", pcEepromBuffer[i],pcEepromBuffer[i+1]);
                            if ((i % 16) == 14)
                            {
                                printf("\n\r");
                            }
                        }
                    }
                }

                if (pcManufacturer)
                {
                    printf("  Setting manufacturer: '%s'\n\r", pcManufacturer);
                    free(eeprom.manufacturer);
                    eeprom.manufacturer     = pcManufacturer;
                }

                if (pcDescription)
                {
                    printf("  Setting description: '%s'\n\r", pcDescription);
                    free(eeprom.product);
                    eeprom.product          = pcDescription;
                }

                if (pcSerial)
                {
                    printf("  Setting serial number: '%s'\n\r", pcSerial);
                    free(eeprom.serial);
                    eeprom.serial           = pcSerial;
                }

                for (i = 0; i < CBUS_NUM; i++)
                {
                    if (apcCBUS[i])
                    {
                        /* Argument given */
                        printf("  Setting C%d: '%s' (%d)\n\r", i,
                               apsCBUS_Function[i]->pcDescription,
                               apsCBUS_Function[i]->iCBUSMode);

                        eeprom.cbus_function[i] = apsCBUS_Function[i]->iCBUSMode;
                    }
                }

                /* EEPROM is 160 bytes */
                ftdi_eeprom_setsize(&ftdic, &eeprom, 160);

                if ((ret = ftdi_eeprom_build(&eeprom, pcEepromBuffer)) < 0)
                {
                    fprintf(stderr, "ftdi_eeprom_build failed: %d (%s)\n\r", ret, ftdi_get_error_string(&ftdic));
                    return -1;
                }

                if ((ret = ftdi_write_eeprom(&ftdic, pcEepromBuffer)) < 0)
                {
                    fprintf(stderr, "ftdi_write_eeprom failed: %d (%s)\n", ret, ftdi_get_error_string(&ftdic));
                    return -1;
                }
                printf("  Wrote new EEPROM data successfully\n\r");
            }
        }

        if ((ret = ftdi_usb_close(&ftdic)) < 0)
        {
            fprintf(stderr, "ftdi_usb_close failed: %d (%s)\n\r", ret, ftdi_get_error_string(&ftdic));
            return EXIT_FAILURE;
        }
    }

    ftdi_list_free(&devlist);
    ftdi_deinit(&ftdic);
    return EXIT_SUCCESS;
}
Beispiel #10
0
int main(int argc, char *argv[])
{
  ih_net_client_t *client;
  ih_core_message_t *ping_message;
  ping_client_context_t ping_client_context;
  ih_pingpong_ping_t *ping;
  ih_audit_log_t *log;

  unsigned short server_port;
  char *server_ip;
  char *ping_string;

  unsigned short message_count;

  signal(SIGPIPE, SIG_IGN);

  if (argc < 4) {
    print_usage_exit();
  }
  server_ip = argv[1];
  server_port = atoi(argv[2]);
  ping_string = argv[3];

  ping_client_context.pong_received = ih_core_bool_false;
  ping_client_context.pongs_received = 0;

  log = ih_audit_log_create(stdout);
  if (!log) {
    ih_core_trace_exit("ih_audit_log_create");
  }

  client = ih_net_client_create(server_ip, server_port, server_port,
      IH_NET_ENGINE_NO_GET_NAME_FUNCTION, &ping_client_context, log);
  if (!client) {
    ih_core_trace_exit("ih_net_client_create");
  }

  if (!ih_net_client_register_engine(client, IH_NET_ENGINE_PING,
          IH_PINGPONG_MESSAGE_TYPE_COUNT)) {
    ih_core_trace_exit("ih_net_client_register_engine");
  }

  ih_net_client_register_message_handler(client, IH_NET_ENGINE_PING,
      IH_PINGPONG_MESSAGE_PONG, handle_pong);

  for (message_count = 0; message_count < PING_CLIENT_SEND_MESSAGE_COUNT;
       message_count++) {

    ping = ih_pingpong_ping_create(ping_string);
    if (ping) {
      ping_message = ih_pingpong_message_create
        (IH_CORE_MESSAGEY_NO_CLIENT_SOCKET, IH_PINGPONG_MESSAGE_PING);
      if (ping_message) {
        if (ih_pingpong_ping_add_to_message(ping, ping_message)) {
          if (!ih_net_client_send_message(client, ping_message)) {
            ih_core_trace_exit("ih_net_client_send_message() failed");
          }
        } else {
          ih_core_trace("ih_pingpong_ping_add_to_message");
          ih_core_message_destroy(ping_message);
        }
      } else {
        ih_core_trace("ih_pingpong_message_create");
      }
      ih_pingpong_ping_destroy(ping);
    } else {
      ih_core_trace_exit("ih_pingpong_ping_create");
    }
  }

  do {
    ih_net_client_process_messages(client);
    usleep(PING_CLIENT_SLEEP_MICROSECONDS);
  } while (ping_client_context.pongs_received
      < PING_CLIENT_SEND_MESSAGE_COUNT);

  ih_net_client_destroy(client);
  ih_audit_log_destroy(log);

  return 0;
}
Beispiel #11
0
int main(int argc, char *argv[]) {
    pid_t sid;
    char upgfile[512];
    int tPid;
    struct stat stat_buf;
    int use_storage_firmware = 0;
    if(argc < 2) {
        print_usage_exit(1);
    }
    /* FIX ME !!!
     * If we need further parameters for this procedure, then we should use
     * opt parser and formal parameters.
     * */
    if(argv[1][0] == '-') {
        switch(argv[1][1]) {
            case 'b':
                strcpy(upgfile, "/tmp/mnt/USB/firmware.bin");
                if(stat(upgfile, &stat_buf)) {
                    printf("There is no \"firmware.bin\" in USB or USB is not inserted\n");
                    print_usage_exit(1);
                }
                else {
                    use_storage_firmware = 1;
                    printf("Using \"firmware.bin\" in USB to upgrade.\n");
                }
                strcpy(upgfile, "/usr/sbin/ezpup /tmp/mnt/USB/firmware.bin");
                break;
            case 's':
                strcpy(upgfile, "/tmp/mnt/SD/firmware.bin");
                if(stat(upgfile, &stat_buf)) {
                    printf("There is no \"firmware.bin\" in SD card or SD card is inserted\n");
                    print_usage_exit(1);
                }
                else {
                    use_storage_firmware = 2;
                    printf("Using \"firmware.bin\" in SD card to upgrade.\n");
                }
                strcpy(upgfile, "/usr/sbin/ezpup /tmp/mnt/SD/firmware.bin");
                break;
            case 'a':
                strcpy(upgfile, "/tmp/mnt/SD/firmware.bin");
                if(stat(upgfile, &stat_buf)) {
                    printf("There is no \"firmware.bin\" in SD card or SD card is inserted\n");
                    strcpy(upgfile, "/tmp/mnt/USB/firmware.bin");
                    if(stat(upgfile, &stat_buf)) {
                        printf("There is no \"firmware.bin\" in USB or USB is not inserted\n");
                        print_usage_exit(1);
                    }
                    else {
                        use_storage_firmware = 1;
                        printf("Using \"firmware.bin\" in USB to upgrade.\n");
                        strcpy(upgfile, "/usr/sbin/ezpup /tmp/mnt/USB/firmware.bin");
                    }
                }
                else {
                    use_storage_firmware = 2;
                    printf("Using \"firmware.bin\" in SD card to upgrade.\n");
                    strcpy(upgfile, "/usr/sbin/ezpup /tmp/mnt/SD/firmware.bin");
                }
                break;
            case 'u':
                if(argc == 3) {
                    snprintf(upgfile, sizeof(upgfile), "wget %s -O /tmp/firmware 2>&1 | cat > /tmp/fw_log.txt", argv[2]);
                    system(upgfile);
                    if(!check_wget_ok("/tmp/fw_log.txt")) {
                        printf("Unable to get URL %s\n", argv[2]);
                        print_usage_exit(1);
                    }
                    snprintf(upgfile, sizeof(upgfile), "/usr/sbin/ezpup /tmp/firmware");
                    printf("Get firmware from %s successfully, using /tmp/firmware to upgrade.\n", argv[2]);
                }
                else {
                    print_usage_exit(1);
                }
                break;
        }
    } else {
        snprintf(upgfile, sizeof(upgfile), "/usr/sbin/ezpup %s", argv[1]);
    }
    tPid = fork();
    if(tPid < 0)
    {
        reboot(RB_AUTOBOOT);
        exit(1); // Error on fork
    }
    else if(tPid > 0)
    {
        exit(0);
    }
    else
    {
        FILE *fp;
        sid = setsid();
        if (sid < 0)
            exit(EXIT_FAILURE);
#if defined(PLATFORM_AXA)
        system("/usr/sbin/ezp-i2c gauge host booting");
#endif
        system("/sbin/stop_services.sh");
        system("/sbin/reserve_link.sh");
        system(upgfile);
        system("/tmp/ezp-i2c gauge upgrade finish");
        fp = fopen("/tmp/fw_incorrect", "r");
        if(fp) {
            printf("Upgrade failed, firmware incorrect\n");
            fclose(fp);
        } else {
            printf("Upgrade successfully\n");
            fp = fopen("/tmp/fw_correct", "w+");
            if(fp) {
                fprintf(fp, "success\n");
                fclose(fp);
            }
        }
        sleep(5);
        reboot(RB_AUTOBOOT);
    }
    return 0;
}