Exemplo n.º 1
0
bool init_config() {
    do {
        if (init_lua_config() == false) {
            ERROR_LOG("%s", "初始化lua配置错误");
            break;
        }

        if (init_net_config() == false) {
            ERROR_LOG("%s", "初始化网络配置失败");
            break;
        }

        if (init_net() == false) {
            ERROR_LOG("%s", "初始化网络失败");
            break;
        }

        protocol_init();
        net::regist_connector_callback(connector_callback);

        connect_gs();

        return true;
    } while (false);

    return false;
}
Exemplo n.º 2
0
void
xmpp_core_init(void)
{
	CHAT_PROTOCOL_REC *rec;

	rec = g_new0(CHAT_PROTOCOL_REC, 1);
	rec->name = XMPP_PROTOCOL_NAME;
	rec->fullname = "XMPP, Extensible messaging and presence protocol";
	rec->chatnet = "xmppnet";
	rec->case_insensitive = FALSE;
	rec->create_chatnet = create_chatnet;
	rec->create_server_setup = create_server_setup;
	rec->create_server_connect = create_server_connect;
	rec->create_channel_setup = create_channel_setup;
	rec->destroy_server_connect =
	    (void (*)(SERVER_CONNECT_REC *))destroy_server_connect;
	rec->server_init_connect = xmpp_server_init_connect;
	rec->server_connect = (void (*)(SERVER_REC *))xmpp_server_connect;
	rec->channel_create = channel_create;
	rec->query_create = xmpp_query_create;
	chat_protocol_register(rec);
	g_free(rec);

	xmpp_commands_init();
	xmpp_servers_init();
	xmpp_servers_reconnect_init();
	xmpp_settings_init();
	protocol_init();
	rosters_init();
	stanzas_init();
	xep_init();

	module_register("xmpp", "core");
}
Exemplo n.º 3
0
void network_library_init(void)
{
    socket_init();
    address_module_init();
    //SET MAC_MLME Handler
    protocol_init();
}
Exemplo n.º 4
0
void
client_protocol(
    char        *hostname,
    char        *auth,
    char        *service,
    FILE        *input_file)
{
    GString *strbuf = g_string_new(NULL);
    char *req, *req1;

    g_string_append_printf(strbuf, "SERVICE %s\nOPTIONS features=%s\n",
        service, our_feature_string);

    req1 = g_malloc(1024);
    while(fgets(req1, 1024, input_file) != NULL)
	g_string_append(strbuf, req1);

    g_free(req1);
    protocol_init();

    req = g_string_free(strbuf, FALSE);

    start_host(hostname, auth, req);

    protocol_run();

    fflush(stdout);

    amfree(our_feature_string);

    return;
}
Exemplo n.º 5
0
void
client_protocol(
    char *hostname,
    char *auth,
    char *service,
    FILE *input_file)
{
    char *req, *req1;

    req = g_strdup_printf("SERVICE %s\nOPTIONS features=%s\n",
			  service, our_feature_string);
    req1 = malloc(1024);
    while(fgets(req1, 1024, input_file) != NULL) {
	vstrextend(&req, req1, NULL);
    }
    protocol_init();

    start_host(hostname, auth, req);

    protocol_run();

    fflush(stdout);

    amfree(our_feature_string);

    return;
}
Exemplo n.º 6
0
static void init() {

    int initialized = protocol_init() && caps_init() && signal_init() && comm_init() && injectable_init();
    
    if (!initialized) {
        fatal("Initialization failed.");
        cleanup();
        exit(EXIT_FAILURE);
    }
    
}
Exemplo n.º 7
0
void
TSPluginInit(int argc, const char *argv[])
{
  TSPluginRegistrationInfo info;
  char *end;
  int tmp;

  info.plugin_name = "output-header";
  info.vendor_name = "MyCompany";
  info.support_email = "*****@*****.**";

  if (TSPluginRegister(&info) != TS_SUCCESS) {
    TSError("[protocol] Plugin registration failed.");

    goto error;
  }


  /* default value */
  accept_port = 4666;
  server_port = 4666;

  if (argc < 3) {
    TSDebug("protocol", "Usage: protocol.so accept_port server_port");
    printf("[protocol_plugin] Usage: protocol.so accept_port server_port\n");
    printf("[protocol_plugin] Wrong arguments. Using deafult ports.\n");
  } else {
    tmp = strtol(argv[1], &end, 10);
    if (*end == '\0') {
      accept_port = tmp;
      TSDebug("protocol", "using accept_port %d", accept_port);
      printf("[protocol_plugin] using accept_port %d\n", accept_port);
    } else {
      printf("[protocol_plugin] Wrong argument for accept_port.");
      printf("Using deafult port %d\n", accept_port);
    }

    tmp = strtol(argv[2], &end, 10);
    if (*end == '\0') {
      server_port = tmp;
      TSDebug("protocol", "using server_port %d", server_port);
      printf("[protocol_plugin] using server_port %d\n", server_port);
    } else {
      printf("[protocol_plugin] Wrong argument for server_port.");
      printf("Using deafult port %d\n", server_port);
    }
  }

  protocol_init(accept_port, server_port);

error:
  TSError("[protocol] Plugin not initialized");
}
Exemplo n.º 8
0
void
TSPluginInit(int argc, const char *argv[])
{
  TSPluginRegistrationInfo info;

  info.plugin_name = "output-header";
  info.vendor_name = "MyCompany";
  info.support_email = "*****@*****.**";

  if (TSPluginRegister(TS_SDK_VERSION_3_0, &info) != TS_SUCCESS) {
    TSError("[PluginInit] Plugin registration failed.\n");
    goto error;
  }

  if (!check_ts_version()) {
    TSError("[PluginInit] Plugin requires Traffic Server 3.0 or later\n");
    goto error;
  }


  /* default value */
  accept_port = 4666;
  server_port = 4666;

  if (argc < 3) {
    TSDebug("protocol", "Usage: protocol.so accept_port server_port");
    printf("[protocol_plugin] Usage: protocol.so accept_port server_port\n");
    printf("[protocol_plugin] Wrong arguments. Using deafult ports.\n");
  } else {
    if (!isnan(atoi(argv[1]))) {
      accept_port = atoi(argv[1]);
      TSDebug("protocol", "using accept_port %d", accept_port);
      printf("[protocol_plugin] using accept_port %d\n", accept_port);
    } else {
      printf("[protocol_plugin] Wrong argument for accept_port.");
      printf("Using deafult port %d\n", accept_port);
    }

    if (!isnan(atoi(argv[2]))) {
      server_port = atoi(argv[2]);
      TSDebug("protocol", "using server_port %d", server_port);
      printf("[protocol_plugin] using server_port %d\n", server_port);
    } else {
      printf("[protocol_plugin] Wrong argument for server_port.");
      printf("Using deafult port %d\n", server_port);
    }
  }

  protocol_init(accept_port, server_port);

error:
  TSError("[PluginInit] Plugin not initialized");
}
Exemplo n.º 9
0
void protocol_maintainerthread()
{
//struct peer_s *dstpeer;
  protocol_init();
/*-TODO
  while (1)
    {
      protocol_slidekeepalive ();

      protocol_sendpacket (dstpeer, PROTOCOL1_KA);
	  sleep(PROTOCOL_HOLEPUNCHINGTIME);
    }*/
}
Exemplo n.º 10
0
int main(void)
{
  protocol_init();        
  settings_init();  
  plan_init();      
  st_init();        
  spindle_init();   
  gc_init();
  limits_init();  
                    
  for(;;){
    sleep_mode(); // Wait for it ...
    protocol_process(); // ... process the serial protocol
  }
  return 0;   /* never reached */
}
Exemplo n.º 11
0
void
TSPluginInit(int argc, const char *argv[])
{
  TSPluginRegistrationInfo info;
  char *end;
  int tmp;

  info.plugin_name   = PLUGIN_NAME;
  info.vendor_name   = "Apache Software Foundation";
  info.support_email = "*****@*****.**";

  if (TSPluginRegister(&info) != TS_SUCCESS) {
    TSError("[%s] Plugin registration failed", PLUGIN_NAME);

    goto error;
  }

  /* default value */
  accept_port = 4666;
  server_port = 4666;

  if (argc < 3) {
    TSDebug(PLUGIN_NAME, "Usage: protocol.so <accept_port> <server_port>. Using default ports accept=%d server=%d", accept_port,
            server_port);
  } else {
    tmp = strtol(argv[1], &end, 10);
    if (*end == '\0') {
      accept_port = tmp;
      TSDebug(PLUGIN_NAME, "using accept_port %d", accept_port);
    } else {
      TSError("[%s] Wrong argument for accept_port, using default port %d", PLUGIN_NAME, accept_port);
    }

    tmp = strtol(argv[2], &end, 10);
    if (*end == '\0') {
      server_port = tmp;
      TSDebug(PLUGIN_NAME, "using server_port %d", server_port);
    } else {
      TSError("[%s] Wrong argument for server_port, using default port %d", PLUGIN_NAME, server_port);
    }
  }

  protocol_init(accept_port, server_port);

error:
  TSError("[%s] Plugin not initialized", PLUGIN_NAME);
}
Exemplo n.º 12
0
int main(void)
{
  sei(); // Enable interrupts
  
  serial_init(BAUD_RATE);
  protocol_init();        
  settings_init();  
  plan_init();      
  st_init();        
  spindle_init();   
  gc_init();
  limits_init();
                    
  while (1) {
//     sleep_mode(); // Wait for it ...
    protocol_process(); // ... process the serial protocol
  }
  return 0;   /* never reached */
}
Exemplo n.º 13
0
static uperf_shm_t *
master_init(workorder_t *w)
{
	uperf_shm_t *shm;

	if (protocol_init(NULL) == UPERF_FAILURE) {
		return (NULL);
	}
	if (master_setup_signal_handler() != UPERF_SUCCESS) {
		uperf_error("Error setting up signal handlers\n");
		return (NULL);
	}
	if ((shm = shm_init(w)) == NULL) {
		return (NULL);
	}
	if (create_control_connections(w) != UPERF_SUCCESS) {
		shm_fini(shm);
		return (NULL);
	}
	shm->endian = UPERF_ENDIAN_VALUE;
	shm->global_error = 0;
	shm->role = MASTER;
	shm->workorder = w;

	if (strand_init_all(shm, w) != UPERF_SUCCESS) {
		uperf_error("error in strand_init_all");
		shm_fini(shm);
		return (NULL);
	}

	/* Initialize barriers */
	if (shm_init_barriers_master(shm, shm->workorder) != 0) {
		shm_fini(shm);
		return (NULL);
	}

	return (shm);
}
Exemplo n.º 14
0
int main()
{
    FILE *fd;
    FILE *fd_to;
    char buffer[4096];
    Buffer ctx;
    json_val_t *val;
    PtlHeader header;
    char dist[20];
    char *str;

    protocol_init(&header);
    protocol_set_key(&header, "user", "pwd");

    buffer_init(&ctx);
    if ((fd = fopen("test.json", "r")) == NULL) {
        printf("Can't open file\n");
        return 1;
    }

    while (1) {
        int read = fread(buffer, 1, 4096, fd);
        if (read <= 0)
            break;
        buffer_update(&ctx, buffer, read);
    } 

    if ((fd_to = fopen("test.dec", "w")) == NULL) {
        printf("Can't open file\n");
        return 1;
    }

    protocol_encrypt_string(&ctx, &header);
    fwrite(header.dist, 1, 20, fd_to);
    fwrite(ctx.buffer, 1, ctx.pos, fd_to);
    return 0;
}
Exemplo n.º 15
0
int
_protocol_init(const char *prot_name, PROTO_PARA *ppp)
{
	/* check whether the protocol version match the csf core version */
	if (CORE_VER_REQUIRE > ppp->vcbp->lowest_ver)
		return PROTO_VER_ERR;
		
	logger_init(ppp->chp->logp, NULL, 0, 0);
	mp_init(20, 100);   
	monitor_init(ppp->chp->mntp);
	submit_request_init(ppp->chp->sribp);
	
	g_pcp = ppp->pcp;

	set_protocol_name(prot_name);
	
    pthread_once(&init_done, pthr_key_create);
    pthread_setspecific(pthread_key, NULL);
	
	if (protocol_init(get_protocol_name()) < 0)
        return PROTO_INIT_ERR;
	
	return PROTO_INIT_OK;
}
int startGrbl(void)
{
  // Initialize system
  serial_init(); // Setup serial baud rate and interrupts
  settings_init(); // Load grbl settings from EEPROM
  st_init(); // Setup stepper pins and interrupt timers
  sei(); // Enable interrupts
  
  memset(&sys, 0, sizeof(sys));  // Clear all system variables
  sys.abort = true;   // Set abort to complete initialization
  sys.state = STATE_INIT;  // Set alarm state to indicate unknown initial position
    
//  Wire.begin();

    
    
  for(;;) {

    // Execute system reset upon a system abort, where the main program will return to this loop.
    // Once here, it is safe to re-initialize the system. At startup, the system will automatically
    // reset to finish the initialization process.
    if (sys.abort) {
      // Reset system.
      serial_reset_read_buffer(); // Clear serial read buffer
      plan_init(); // Clear block buffer and planner variables
      gc_init(); // Set g-code parser to default state
      protocol_init(); // Clear incoming line data and execute startup lines
      spindle_init();
      coolant_init();
      limits_init();
      st_reset(); // Clear stepper subsystem variables.
      
        syspos(&encdr_x,&encdr_y,&encdr_z);
        ofst_x=encdr_x;
        ofst_y=encdr_y;
        ofst_z=encdr_z;
        
      // Sync cleared gcode and planner positions to current system position, which is only
      // cleared upon startup, not a reset/abort. 
      sys_sync_current_position();
        
      // Reset system variables.
      sys.abort = false;
      sys.execute = 0;
      if (bit_istrue(settings.flags,BITFLAG_AUTO_START)) { sys.auto_start = true; }
      
      // Check for power-up and set system alarm if homing is enabled to force homing cycle
      // by setting Grbl's alarm state. Alarm locks out all g-code commands, including the
      // startup scripts, but allows access to settings and internal commands. Only a homing
      // cycle '$H' or kill alarm locks '$X' will disable the alarm.
      // NOTE: The startup script will run after successful completion of the homing cycle, but
      // not after disabling the alarm locks. Prevents motion startup blocks from crashing into
      // things uncontrollably. Very bad.
      #ifdef HOMING_INIT_LOCK
        if (sys.state == STATE_INIT && bit_istrue(settings.flags,BITFLAG_HOMING_ENABLE)) { sys.state = STATE_ALARM; }
      #endif
      
      // Check for and report alarm state after a reset, error, or an initial power up.
      if (sys.state == STATE_ALARM) {
        report_feedback_message(MESSAGE_ALARM_LOCK); 
      } else {
        // All systems go. Set system to ready and execute startup script.
        sys.state = STATE_IDLE;
        protocol_execute_startup(); 
      }
    }
      
      

    protocol_execute_runtime();

 //   syspos(&encdr_x,&encdr_y);
      
    protocol_process(); // ... process the serial protocol
    
    
      
  }
  return 0;   /* never reached */
}
Exemplo n.º 17
0
void protocol_xbee_init(protocol_state_t * state)
{
    protocol_init(state, PROTOCOL_XBEE_PACKET_START_BYTE, PROTOCOL_XBEE_PACKET_ESCAPE_BYTE);
}
Exemplo n.º 18
0
//there has to be a better way to do this :/
void Run(void)
{
  
    char *ce; 
    SetSig       ();
    Banner       ();

        if ((ce = (char *)get_config_entry("?omega", "version")))
        {
			if (CONFIG_VERSION != atoi(ce))
			{
				fprintf(stderr, "\033[1;31mCRITICAL\033[0m: Invalid configuration file version. [Given: %s][Required: %d]", ce, CONFIG_VERSION); 
				Exit(0);	
			}	
	} else { 
		fprintf(stderr, "\033[1;31mERROR\033[0m: Unable to determine the configuration file version. Please make sure you have all <?omega> intact\n");
		fprintf(stderr, "Assuming configuration version \033[1;31m%d\033[0m\n\n", CONFIG_VERSION);
	} 

#ifdef HAVE_SETPROCTITLE
    setproctitle("%s", CfgSettings.servername);
#endif

    open_log  ();
    init_uid ();
	
    AddEventEx ("House Keeping", 900, EVENT_UNLIMITED, ev_housekeeping);
 
    AddEvent ("BURST", burst_local_users);
    AddEvent ("BURST", burst_local_servers);
    AddEvent ("CONNECT", introduce_users);
	
    if ((Omega->me = new_serv(NULL, CfgSettings.servername)))
    {
        strlcpy (Omega->me->sid, CfgSettings.sid, sizeof(Omega->me->sid));
        Omega->me->eos = 1; //mark us as already EOS'ed
    }
    else
    {
		fprintf (stderr, "Unable to create our server entry\n");
		exit (0);
    }

    /*
     * Initialize our core for running
     */

	database_init (); 
    protocol_init ();
	
    servsock    	 = add_new_socket ((void*) psr_HandleEvent, NULL);
    servsock->flags	|= SOCK_UPLINK;
	strlcpy (servsock->name, "Uplink", sizeof(servsock->name));

#ifdef HAVE_GNUTLS
        servsock->tls_enabled   = get_config_bool("link", "gnutls", 0);
#endif
	
    psr_init      ();
	init_access();

	init_modules();
	introduce_users (0, NULL);

    /*
     * Connect to the IRCd if we don't connect Add an event to connect...
     */

    printf ("\r\n");
    printf ("Connecting to \033[1;32m%s\033[0m port \033[1;32m%d\033[0m\033[0m\n", CfgSettings.uplink, CfgSettings.port);
    if (Connect (servsock, CfgSettings.uplink, CfgSettings.local_ip, CfgSettings.port))
        ircd_connect ();
    else
        AddEventEx ("Connect Uplink", 60, 3, ev_connectuplink);

    /*
     * Okay begin
     */

    OneTimeAround   ();

    return;
}
Exemplo n.º 19
0
int   main(int   argc,   char   *argv[]) 
{



	int sock_serv_fd;
	struct sockaddr_in   cliaddr;
	struct connect_serv   conn_serv;
	unsigned int cid = 1011;
	
	signal(SIGPIPE, sig_handler);

while(1)
{

	if(!protocol_init(cid)){
		printf("协议初始化失败...\n");
		continue;
	}
/*
	protocol_req_ready(&ConnectREQ, &present_info);
	{
		char buff[20] = {0};
		strncpy(buff, ConnectREQ.KEY, 6);
		printf("开始打印协议:\n");
		printf("key:%s\n", buff);
		printf("Length:%d\n", ConnectREQ.Length);
		printf("command:%#x\n", ConnectREQ.Command);
		printf("CID:%d%d%d%d\n",  ConnectREQ.CID[3], ConnectREQ.CID[2], ConnectREQ.CID[1], ConnectREQ.CID[0]);
		printf("IP:%d.%d.%d.%d\n", ConnectREQ.IP[0],ConnectREQ.IP[1],ConnectREQ.IP[2], ConnectREQ.IP[3]);
		printf("MAC:%02x-%02x-%02x-%02x-%02x-%02x\n", ConnectREQ.MAC[0], ConnectREQ.MAC[1], ConnectREQ.MAC[2], ConnectREQ.MAC[3], ConnectREQ.MAC[4],ConnectREQ.MAC[5]);
		printf("presentDate:20%d-days:%d\n",*(unsigned short *)ConnectREQ.PresentDate & 0x7f,  *(unsigned short *)ConnectREQ.PresentDate >> 7);
		printf("presentTime:%d-%d\n", ConnectREQ.PresentTime[0], ConnectREQ.PresentTime[1]);
		printf("model:%s\n", ConnectREQ.Model);
		strncpy(buff, ConnectREQ.Series, 10);
		printf("series:%s\n", buff);
		printf("joinVersion:%d.%d\n", ConnectREQ.JoinConnectVersion[0], ConnectREQ.JoinConnectVersion[1]);
		printf("chargerVersion:%d.%d\n", ConnectREQ.ChargerFWVersion[0], ConnectREQ.ChargerFWVersion[1]);
		printf("CRC:%d\n", *(u16 *)ConnectREQ.CRC16);

	}
*/

	sock_serv_fd = sock_server_init(&cliaddr, JOIN_SERVER1_IP, JOIN_SERVER_PORT);	

	if(  !connect_retry(sock_serv_fd, (const struct sockaddr *)&cliaddr, sizeof(cliaddr)) ){
		// 连接失败,然后连接join_server2_ip
		printf("jion server1 connect fail...\n");
		close(sock_serv_fd);
		if(!(sock_serv_fd = sock_server_init(&cliaddr, JOIN_SERVER2_IP, JOIN_SERVER_PORT))){
			close(sock_serv_fd);
		  	printf("join server2 connect fail...\n");
			continue;
		}
	}
	
	printf("客户端连接成功...\n"); 
	char sock_buff[1024] = {0};

	// 连接join server
	if( !join_conn_serv(sock_serv_fd, &conn_serv)){
		printf("与通信JOIN server 失败, 重新初始化...\n");
		sleep(5);
		continue;
	}

//	if(!join_comfirm_serv(sock_serv_fd, &conn_serv, CHARGER_READY, ONLINE)){
//		printf("发送JOIN SERVER确认连接失败...\n");
//		exit(1);
//	}
//	sleep(2);

//	break;


	printf("\n    #############################################################\n");
	printf("     #############################################################\n");
	printf("关闭JOIN SERVER连接,开始连接CONNECT SERVER...\n");	// JOIN SERVER 连接
	shutdown(sock_serv_fd, SHUT_RDWR);
	close(sock_serv_fd);
	sock_serv_fd = -1;
	memset(&cliaddr, 0, sizeof(cliaddr));
	printf("conn IP:%s port:%d\n",  conn_serv.IP, conn_serv.Port);

int g_CMD = SOCK_CMD_REQ;
while(1){
//	printf("sock_conn_fd=%d\n", sock_serv_fd);
	

	switch(g_CMD)
	{
	
	// 发送新连接
	 case  SOCK_CMD_REQ:
		if((sock_serv_fd = sock_conn_server(&cliaddr, &conn_serv))<0)	
			continue;
		protocol_CSREQ_ready();
		if( !CServer_send(sock_serv_fd, (u8 *)CServer_req, sizeof(CServer_REQ))){
			sock_close(sock_serv_fd);
			memset(&cliaddr, 0, sizeof(cliaddr));
			printf("发送新连接失败...\n");
			sleep(10);
			continue;
		}
		sleep(1);
		g_CMD = SOCK_CMD_FUP;
	continue;
	
	case 	SOCK_CMD_FUP:
	// 发送全更新
		if((sock_serv_fd = sock_conn_server(&cliaddr, &conn_serv))<0)	
			continue;
		protocol_CSFUP_ready();
		if( !CServer_send(sock_serv_fd, (u8 *)CS_FUP, sizeof(CServer_FULL_UPDATE))){
			sock_close(sock_serv_fd);
			memset(&cliaddr, 0, sizeof(cliaddr));
			printf("发送全更新失败...\n");
			sleep(10);
			continue;
		}
		sleep(1);
		g_CMD = SOCK_CMD_HB;
	continue;
	
	case SOCK_CMD_HB:

	// 发送心跳
		if((sock_serv_fd = sock_conn_server(&cliaddr, &conn_serv))<0)	
			continue;
		protocol_CSHB_ready();
		if( !CServer_send(sock_serv_fd, (u8 *)&CS_HB, sizeof(CS_HB))){
			printf("发送心跳失败...\n");
			sock_close(sock_serv_fd);
			memset(&cliaddr, 0, sizeof(cliaddr));
			sleep(2);
		}
		sleep(300);
	break;
	 } // switch
	
      } //  while(1) of conn server
  }		
}
Exemplo n.º 20
0
int main(int argc, char ** argv)
{
    int event, arg;
    struct FRAME r;
    int len = 0; 
    int i;

    protocol_init(argc, argv); 
    lprintf("Designed by JackalDire\n");

    disable_network_layer();

    for (;;) {
        event = wait_for_event(&arg);

        switch (event) {
        case NETWORK_LAYER_READY:
            get_packet(buffer[next_frame_to_send]); // fetch new packet from physical layer
            nbuffered++;
            send_data_frame();
            inc(&next_frame_to_send);
            break;

        case PHYSICAL_LAYER_READY:
            phl_ready = 1;
            break;

        case FRAME_RECEIVED: 
            len = recv_frame((unsigned char *)&r, sizeof r);
            if (len < 5 || crc32((unsigned char *)&r, len) != 0) {
                /* discard the error packet with wrong crc checksum  */
                /* TODO : add NAK to  accelerate resending */
                dbg_event("**** receiver error, bad CRC checksum, packet discarded.\n");
                break;
            }

            if (r.kind == FRAME_DATA) {
                dbg_frame("Recv DATA %d %d, ID %d\n", r.seq, r.ack, *(short *)r.data);
                if (r.seq == frame_expected) {
                    /* transmit the receive packet to network layer */
                    put_packet(r.data, PKT_LEN); // 7 = 3B other fields + 4B crc code
                    inc(&frame_expected);
                    start_ack_timer(ACK_TIMER);
                }
            }
            /* ACK n means packets earlier than n were received correctly,
             * so make packet ack_expeced ~ r.ack acknowledged */ 
            while (between(ack_expected, r.ack, next_frame_to_send)) {
                --nbuffered;
                stop_timer(ack_expected);
                inc(&ack_expected);
            }
            break; 

        case DATA_TIMEOUT:
            dbg_event("---- DATA %d timeout\n", arg); 
            next_frame_to_send = ack_expected;
            /* retransmit all packets in the buffer when timeout */ 
            for (i = 1; i <= nbuffered; ++i) {
                send_data_frame();
                inc(&next_frame_to_send);
            }
            break;
        
        
        case ACK_TIMEOUT:
            /* send a separate ACK frame if there is no outstream for a specific time */
            dbg_event("---- ACK %d timeout\n", arg);
            send_ack_frame();
        }
        
        /* disable networklayer when outstrem buffer if full */
        if (nbuffered < MAX_SEQ && phl_ready)
            enable_network_layer();
        else
            disable_network_layer(); 
   }
}
Exemplo n.º 21
0
int main(int argc, char **argv) {
	// memtrack();

	struct options_t *options = NULL;
	struct ssdp_list_t *ssdp_list = NULL;
	struct devices_t *dev = NULL;
	struct JsonNode *json = NULL;
	struct JsonNode *tmp = NULL;
	char *recvBuff = NULL, *message = NULL, *output = NULL;
	char *device = NULL, *state = NULL, *values = NULL;
	char *server = NULL;
	int has_values = 0, sockfd = 0, hasconfarg = 0;
	unsigned short port = 0, showhelp = 0, showversion = 0;

	log_file_disable();
	log_shell_enable();
	log_level_set(LOG_NOTICE);

	if(!(progname = MALLOC(16))) {
		logprintf(LOG_ERR, "out of memory");
		exit(EXIT_FAILURE);
	}
	strcpy(progname, "pilight-control");

	/* Define all CLI arguments of this program */
	options_add(&options, 'H', "help", OPTION_NO_VALUE, 0, JSON_NULL, NULL, NULL);
	options_add(&options, 'V', "version", OPTION_NO_VALUE, 0, JSON_NULL, NULL, NULL);
	options_add(&options, 'd', "device", OPTION_HAS_VALUE, 0,  JSON_NULL, NULL, NULL);
	options_add(&options, 's', "state", OPTION_HAS_VALUE, 0, JSON_NULL, NULL, NULL);
	options_add(&options, 'v', "values", OPTION_HAS_VALUE, 0, JSON_NULL, NULL, NULL);
	options_add(&options, 'S', "server", OPTION_HAS_VALUE, 0, JSON_NULL, NULL, "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$");
	options_add(&options, 'P', "port", OPTION_HAS_VALUE, 0, JSON_NULL, NULL, "[0-9]{1,4}");
	options_add(&options, 'C', "config", OPTION_HAS_VALUE, 0, JSON_NULL, NULL, NULL);

	/* Store all CLI arguments for later usage
	   and also check if the CLI arguments where
	   used correctly by the user. This will also
	   fill all necessary values in the options struct */
	while(1) {
		int c;
		c = options_parse(&options, argc, argv, 1, &optarg);
		if(c == -1)
			break;
		if(c == -2) {
			showhelp = 1;
			break;
		}
		switch(c) {
			case 'H':
				showhelp = 1;
			break;
			case 'V':
				showversion = 1;
			break;
			case 'd':
				if((device = REALLOC(device, strlen(optarg)+1)) == NULL) {
					logprintf(LOG_ERR, "out of memory");
					exit(EXIT_FAILURE);
				}
				strcpy(device, optarg);
			break;
			case 's':
				if((state = REALLOC(state, strlen(optarg)+1)) == NULL) {
					logprintf(LOG_ERR, "out of memory");
					exit(EXIT_FAILURE);
				}
				strcpy(state, optarg);
			break;
			case 'v':
				if((values = REALLOC(values, strlen(optarg)+1)) == NULL) {
					logprintf(LOG_ERR, "out of memory");
					exit(EXIT_FAILURE);
				}
				strcpy(values, optarg);
			break;
			case 'C':
				if(config_set_file(optarg) == EXIT_FAILURE) {
					return EXIT_FAILURE;
				}
				hasconfarg = 1;
			break;
			case 'S':
				if(!(server = REALLOC(server, strlen(optarg)+1))) {
					logprintf(LOG_ERR, "out of memory");
					exit(EXIT_FAILURE);
				}
				strcpy(server, optarg);
			break;
			case 'P':
				port = (unsigned short)atoi(optarg);
			break;
			default:
				printf("Usage: %s -l location -d device -s state\n", progname);
				goto close;
			break;
		}
	}
	options_delete(options);

	if(showversion == 1) {
		printf("%s %s\n", progname, PILIGHT_VERSION);
		goto close;
	}
	if(showhelp == 1) {
		printf("\t -H --help\t\t\tdisplay this message\n");
		printf("\t -V --version\t\t\tdisplay version\n");
		printf("\t -S --server=x.x.x.x\t\tconnect to server address\n");
		printf("\t -C --config\t\t\tconfig file\n");
		printf("\t -P --port=xxxx\t\t\tconnect to server port\n");
		printf("\t -d --device=device\t\tthe device that you want to control\n");
		printf("\t -s --state=state\t\tthe new state of the device\n");
		printf("\t -v --values=values\t\tspecific comma separated values, e.g.:\n");
		printf("\t\t\t\t\t-v dimlevel=10\n");
		goto close;
	}
	if(device == NULL || state == NULL ||
	   strlen(device) == 0 || strlen(state) == 0) {
		printf("Usage: %s -d device -s state\n", progname);
		goto close;
	}

	if(server && port > 0) {
		if((sockfd = socket_connect(server, port)) == -1) {
			logprintf(LOG_ERR, "could not connect to pilight-daemon");
			goto close;
		}
	} else if(ssdp_seek(&ssdp_list) == -1) {
		logprintf(LOG_ERR, "no pilight ssdp connections found");
		goto close;
	} else {
		if((sockfd = socket_connect(ssdp_list->ip, ssdp_list->port)) == -1) {
			logprintf(LOG_ERR, "could not connect to pilight-daemon");
			goto close;
		}
	}
	if(ssdp_list) {
		ssdp_free(ssdp_list);
	}

	protocol_init();
	config_init();
	if(hasconfarg == 1) {
		if(config_read() != EXIT_SUCCESS) {
			goto close;
		}
	}

	socket_write(sockfd, "{\"action\":\"identify\"}");
	if(socket_read(sockfd, &recvBuff, 0) != 0
	   || strcmp(recvBuff, "{\"status\":\"success\"}") != 0) {
		goto close;
	}

	json = json_mkobject();
	json_append_member(json, "action", json_mkstring("request config"));
	output = json_stringify(json, NULL);
	socket_write(sockfd, output);
	json_free(output);
	json_delete(json);

	if(socket_read(sockfd, &recvBuff, 0) == 0) {
		if(json_validate(recvBuff) == true) {
			json = json_decode(recvBuff);
			if(json_find_string(json, "message", &message) == 0) {
				if(strcmp(message, "config") == 0) {
					struct JsonNode *jconfig = NULL;
					if((jconfig = json_find_member(json, "config")) != NULL) {
						int match = 1;
						while(match) {
							struct JsonNode *jchilds = json_first_child(jconfig);
							match = 0;
							while(jchilds) {
								if(strcmp(jchilds->key, "devices") != 0) {
									json_remove_from_parent(jchilds);
									tmp = jchilds;
									match = 1;
								}
								jchilds = jchilds->next;
								if(tmp != NULL) {
									json_delete(tmp);
								}
								tmp = NULL;
							}
						}
						config_parse(jconfig);
						if(devices_get(device, &dev) == 0) {
							JsonNode *joutput = json_mkobject();
							JsonNode *jcode = json_mkobject();
							JsonNode *jvalues = json_mkobject();
							json_append_member(jcode, "device", json_mkstring(device));

							if(values != NULL) {
								char **array = NULL;
								unsigned int n = explode(values, ",=", &array), q = 0;
								for(q=0;q<n;q+=2) {
									char *name = MALLOC(strlen(array[q])+1);
									if(name == NULL) {
										logprintf(LOG_ERR, "out of memory\n");
										exit(EXIT_FAILURE);
									}
									strcpy(name, array[q]);
									if(q+1 == n) {
										for(q=0;q<n;q++) {
											FREE(array[q]);
										}
										FREE(array);
										logprintf(LOG_ERR, "\"%s\" is missing a value for device \"%s\"", name, device);
										FREE(name);
										break;
									} else {
										char *val = MALLOC(strlen(array[q+1])+1);
										if(val == NULL) {
											logprintf(LOG_ERR, "out of memory\n");
											exit(EXIT_FAILURE);
										}
										strcpy(val, array[q+1]);
										if(devices_valid_value(device, name, val) == 0) {
											if(isNumeric(val) == EXIT_SUCCESS) {
												char *ptr = strstr(array[q+1], ".");
												int decimals = 0;
												if(ptr != NULL) {
													decimals = (int)(strlen(array[q+1])-((size_t)(ptr-array[q+1])+1));
												}
												json_append_member(jvalues, name, json_mknumber(atof(val), decimals));
											} else {
												json_append_member(jvalues, name, json_mkstring(val));
											}
											has_values = 1;
										} else {
											logprintf(LOG_ERR, "\"%s\" is an invalid value for device \"%s\"", name, device);
											for(q=0;q<n;q++) {
												FREE(array[q]);
											}
											FREE(array);
											FREE(name);
											json_delete(json);
											goto close;
										}
									}
									FREE(name);
								}
								unsigned int z = 0;
								for(z=q;z<n;z++) {
									FREE(array[z]);
								}
								if(n > 0) {
									FREE(array);
								}
							}

							if(devices_valid_state(device, state) == 0) {
								json_append_member(jcode, "state", json_mkstring(state));
							} else {
								logprintf(LOG_ERR, "\"%s\" is an invalid state for device \"%s\"", state, device);
								json_delete(json);
								goto close;
							}

							if(has_values == 1) {
								json_append_member(jcode, "values", jvalues);
							} else {
								json_delete(jvalues);
							}
							json_append_member(joutput, "action", json_mkstring("control"));
							json_append_member(joutput, "code", jcode);
							output = json_stringify(joutput, NULL);
							socket_write(sockfd, output);
							json_free(output);
							json_delete(joutput);
							if(socket_read(sockfd, &recvBuff, 0) != 0
							   || strcmp(recvBuff, "{\"status\":\"success\"}") != 0) {
								logprintf(LOG_ERR, "failed to control %s", device);
							}
						} else {
							logprintf(LOG_ERR, "the device \"%s\" does not exist", device);
							json_delete(json);
							goto close;
						}
					}
				}
			}
			json_delete(json);
		}
	}
close:
	if(recvBuff) {
		FREE(recvBuff);
	}
	if(sockfd > 0) {
		socket_close(sockfd);
	}
	if(server != NULL) {
		FREE(server);
	}
	if(device != NULL) {
		FREE(device);
	}
	if(state != NULL) {
		FREE(state);
	}
	if(values != NULL) {
		FREE(values);
	}
	log_shell_disable();
	socket_gc();
	config_gc();
	protocol_gc();
	options_gc();
	event_operator_gc();
	event_action_gc();
	dso_gc();
	log_gc();
	threads_gc();
	gc_clear();
	FREE(progname);
	xfree();

	return EXIT_SUCCESS;
}
Exemplo n.º 22
0
void main1(int argc, char** argv) {
	srand(time(0));
	//init
	protocol_init(argc, argv);
	//arguments
	windowSize = 22;
	retimer = 3300;//retransmit timer
	acktimer = 600;
	bufferSize = windowSize / 2;//buffer size
	//init datalink layer
	senderLeft = 0;//left edge of sender
	senderRight = 0;//right edge of sender, which has data unfilled
	receiverLeft = 0;//left edge of receiver
	//receiverRight = bufferSize - 1;//right edge of receiver
	isPhysicalLayerReady = -1;
	lastAck = windowSize - 1;
	//init buffer
	sender = (buffer*)malloc(sizeof(buffer)* bufferSize);
	receiver = (buffer*)malloc(sizeof(buffer)* bufferSize);
	for (int i = 0; i < bufferSize; i++) {
		sender[i].frameArrived = false;
		receiver[i].frameArrived = false;
		sender[i].hasSent = false;
		receiver[i].hasSent = false;
	}
	//init interfcace
	enable_network_layer();
	bool isNetworkEnabled = true;
	//init event args
	int eventArgs = -1;
	int eventKind = -1;
	//allocate temp space
	unsigned char temp[MAX_PACKET_SIZE + 11];
	//main loop
	while (true) {
		static int frameLength;
		eventKind = wait_for_event(&eventArgs);//get event
		switch (eventKind) {
		case PHYSICAL_LAYER_READY:
			isPhysicalLayerReady = 1;
			break;
		case NETWORK_LAYER_READY:
			//if buffer nearly full
			if (((senderRight > senderLeft) && (senderRight - senderLeft == bufferSize - 1)) || (senderRight < senderLeft) && (windowSize - senderLeft + senderRight == bufferSize - 1)) {
				disable_network_layer();
				isNetworkEnabled = false;
			}

			//store frame in buffer
			sender[senderRight % bufferSize].length = get_packet(sender[senderRight % bufferSize].data);

			//slide window
			senderRight = (senderRight + 1) % windowSize;
			break;
		case FRAME_RECEIVED:
			//init temperory variables
			frameLength = recv_frame(temp, MAX_PACKET_SIZE + 7);

			if (frameLength > MAX_PACKET_SIZE + 7)
				;//frame is too large, discard it
			else {
				//check crc
				if (crc32(temp, frameLength) != 0) {//crc faild
					if (isInBuffer(senderLeft, senderRight, temp[0] == FRAME_DATA ? temp[2] : temp[1], false)) {
						//send nak
						temp[0] = FRAME_NAK;//if the 2nd byte is error, it may sends false nak, but it doesn't matter
						mySendFrame(temp, 2);
					}
				}
				else {
					if (temp[0] == FRAME_ACK) {//if it's an ack frame
						if (isInBuffer(senderLeft, senderRight, temp[1], false)) {
							if (isInBuffer(lastAck, senderRight, temp[1], false))
								lastAck = temp[1];
							//else do noting
							break;
						}
					}
					else if (temp[0] == FRAME_NAK) {//if it's a nak frame
						if (isInBuffer(senderLeft, senderRight, temp[1], false)) {
							//retranmit
							temp[0] = 1;
							memcpy(temp + 3, sender[temp[1] % bufferSize].data, sender[temp[1] % bufferSize].length * sizeof(unsigned char));
							mySendFrame(temp, sender[temp[1] % bufferSize].length + 3);
							break;
						}
					}
					else if (temp[0] == FRAME_DATA) {//if it's a data frame
						if (isInBuffer(lastAck, senderRight, temp[2], false))
							lastAck = temp[2];
						if (isInBuffer(receiverLeft, (receiverLeft + bufferSize) % windowSize, temp[1], true)){
							if (!receiver[temp[1] % bufferSize].frameArrived) {
								receiver[temp[1] % bufferSize].frameArrived = true;
								receiver[temp[1] % bufferSize].length = frameLength - 7;
								for (int i = 0; i < frameLength - 7; i++) {
									receiver[temp[1] % bufferSize].data[i] = temp[3 + i];
								}
							}
						}
					}

				}

			}
			break;
		case DATA_TIMEOUT:
			//just retransmit the frame
			if (isInBuffer(lastAck, senderRight, eventArgs, false) && isInBuffer(senderLeft, senderRight, eventArgs, false)) {
				if (sender[eventArgs % bufferSize].hasSent) {//if it has been sent
					if (eventArgs == senderLeft || rand() % 10 > 10) {
						//build the frame
						temp[0] = FRAME_DATA;
						temp[1] = eventArgs;
						memcpy((void*)(temp + 3), sender[eventArgs % bufferSize].data, sender[eventArgs % bufferSize].length * sizeof(unsigned char));
						//transmit
						mySendFrame(temp, sender[eventArgs % bufferSize].length + 3);
					}
					else
						start_timer(eventArgs, retimer * (rand() % 10 / 10.0 + 1));
				}
			}
			break;
		case ACK_TIMEOUT:
			//just send an ack
			temp[0] = FRAME_ACK;
			mySendFrame(temp, 2);
			break;
		}


		//sliding the sender window
		//send
		{
			int i = senderLeft;
			while (isInBuffer(senderLeft, senderRight, i, false)) {
				if (sender[i % bufferSize].hasSent == false){
					if (isPhysicalLayerReady == 1 || isPhysicalLayerReady == -1 || phl_sq_len() < 1000) {
						//build the frame
						temp[0] = FRAME_DATA;
						temp[1] = i % windowSize;
						memcpy((void*)(temp + 3), sender[i % bufferSize].data, sender[i % bufferSize].length * sizeof(unsigned char));
						//transmit
						mySendFrame(temp, sender[i % bufferSize].length + 3);
						sender[i % bufferSize].hasSent = true;
						isPhysicalLayerReady = 0;
					}
					break;
				}
				i = (i + 1) % windowSize;
			}
		}
		//slide
		while (isInBuffer(senderLeft, senderRight, lastAck, false)) {//·â×°º¯Êý
			sender[senderLeft % bufferSize].hasSent = false;
			stop_timer(senderLeft);
			senderLeft = (senderLeft + 1) % windowSize;
		}
		//enable network layer
		if (!(((senderRight > senderLeft) && (senderRight - senderLeft == bufferSize)) || (senderRight < senderLeft) && (windowSize - senderLeft + senderRight == bufferSize)) && !isNetworkEnabled) {
			enable_network_layer();
			isNetworkEnabled = true;
		}


		//sliding the receiver window
		{
			int i = 0;
			for (i = 0; i < bufferSize; i++) {
				if (receiver[(receiverLeft + i) % bufferSize].frameArrived) {
					put_packet(receiver[(receiverLeft + i) % bufferSize].data, receiver[(receiverLeft + i) % bufferSize].length);
					receiver[(receiverLeft + i) % bufferSize].frameArrived = false;
				}
				else break;
			}
			receiverLeft = (receiverLeft + i) % windowSize;
		}
	}
}
Exemplo n.º 23
0
static int tora_handler( request_rec *r ) {
	mcontext ctx, *c = &ctx;
	if( strcmp(r->handler,"tora-handler") != 0)
		return DECLINED;

	// init context
	c->need_discard = false;
	c->is_multipart = false;
	c->headers_sent = false;
	c->is_form_post = false;
	c->r = r;
	c->post_data = NULL;
	c->xff = NULL;
	c->client_ip = NULL;
	c->p = NULL;
	c->r->content_type = "text/html";
	config.hits++;

	// read post data
	{
		const char *ctype = ap_table_get(r->headers_in,"Content-Type");
		ap_setup_client_block(r,REQUEST_CHUNKED_ERROR);
		if( ctype && strstr(ctype,"multipart/form-data") )
			c->is_multipart = true;
		else if( ap_should_client_block(r) ) {
			int tlen = 0;
			c->post_data = (char*)malloc(config.max_post_size);
			while( true ) {
				int len = ap_get_client_block(r,c->post_data + tlen,config.max_post_size - tlen);
				if( len <= 0 )
					break;
				tlen += len;
			}
			if( tlen >= config.max_post_size ) {
				discard_body(c);
				free(c->post_data);
				log_error(c,"Maximum POST data exceeded. Try using multipart encoding");
				return OK;
			}
			c->post_data[tlen] = 0;
			c->post_data_size = tlen;
			c->is_form_post = ctype == NULL || (strstr(ctype,"urlencoded") != NULL);
		}
	}

	// init protocol
	{
		protocol_infos infos;
		request_rec *first = r;
		while( first->prev != NULL )
			first = first->prev;
		infos.custom = c;
		infos.script = r->filename;
		infos.uri = first->uri;
		infos.hostname = r->hostname ? r->hostname : "";
		if( config.proxy_mode ) {
			const char *xff = ap_table_get(r->headers_in,"X-Forwarded-For");
			if( xff == NULL )
				infos.client_ip = r->connection->remote_ip;
			else {
				char tmp;
				char *xend = (char*)xff + strlen(xff) - 1;
				while( xend > xff && *xend != ' ' && *xend != ',' )
					xend--;
				c->client_ip = strdup(xend);
				infos.client_ip = c->client_ip;
				if( xend > xff && *xend == ' ' && xend[-1] == ',' )
					xend--;
				tmp = *xend;
				*xend = 0;
				c->xff = strdup(xff);
				*xend = tmp;
			}
		} else
			infos.client_ip = inet_ntoa(REMOTE_ADDR(r->connection));
		infos.http_method = r->method;
		infos.get_data = r->args;
		infos.post_data = c->post_data;
		infos.post_data_size = c->post_data_size;
		infos.content_type = ap_table_get(r->headers_in,"Content-Type");
		infos.do_get_headers = do_get_headers;
		infos.do_get_params = do_get_params;
		infos.do_set_header = do_set_header;
		infos.do_set_return_code = do_set_return_code;
		infos.do_print = do_print;
		infos.do_flush = do_flush;
		infos.do_log = do_log;
		infos.do_stream_data = c->is_multipart ? do_stream_data : NULL;
		c->p = protocol_init(&infos);
	}

	// run protocol
	{
		int port = config.port_min + (config.hits % (1 + config.port_max - config.port_min));
		if( !protocol_connect(c->p,config.host,port) ||
			!protocol_send_request(c->p) ||
			!protocol_read_answer(c->p) )
			log_error(c,protocol_get_error(c->p));
	}

	// cleanup
	protocol_free(c->p);
	free(c->xff);
	free(c->client_ip);
	free(c->post_data);
	send_headers(c); // in case...
	if( c->need_discard )
		discard_body(c);
	return OK;
}
Exemplo n.º 24
0
int threads_linux_init(void)
{
    int status = 0;
    int n = 0;
    int return_value = THREADS_LINUX_SUCCESS;

    // Init data
    status = sensors_init(&battery_data, &gps_data, &imu_data, &pitot_data, &pwm_read_data, &pwm_write_data, &scp1000_data, &sonar_data);
    if(status != SENSORS_SUCCESS)
    {
        return_value = THREADS_LINUX_FAILURE;
    }

    if(return_value != THREADS_LINUX_FAILURE)
    {
        status = calibration_init(&calibration_local_coordinate_system_data, &calibration_local_fields_data, &calibration_altimeter_data);
        if(status != CALIBRATION_SUCCESS)
        {
            return_value = THREADS_LINUX_FAILURE;
        }
    }

    if(return_value != THREADS_LINUX_FAILURE)
    {
        status = gps_init(&gps_measure);
        if(status != 1)
        {
            return_value = THREADS_LINUX_FAILURE;
        }
    }

    if(return_value != THREADS_LINUX_FAILURE)
    {
        status = imu_init(&imu_measure);
        if(status != 1)
        {
            return_value = THREADS_LINUX_FAILURE;
        }
    }

    if(return_value != THREADS_LINUX_FAILURE)
    {
        status = magnetometer_init(&magnetometer_measure);
        if(status != 1)
        {
            return_value = THREADS_LINUX_FAILURE;
        }
    }

    if(return_value != THREADS_LINUX_FAILURE)
    {
    	status = sonar_init(&sonar_measure);
    	if(status != 1)
    	{
    		return_value = THREADS_LINUX_FAILURE;
    	}
    }

    if(return_value != THREADS_LINUX_FAILURE)
    {
        status = estimation_init(ESTIMATION_DO_NOT_ESTIMATE_ACCEL_BIAS, &estimation_data);
        if(status != ESTIMATION_SUCCESS)
        {
            return_value = THREADS_LINUX_FAILURE;
        }
    }

    if(return_value != THREADS_LINUX_FAILURE)
    {
        status = control_init(&control_data);
        if(status != CONTROL_SUCCESS)
        {
            return_value = THREADS_LINUX_FAILURE;
        }
    }

    if(return_value != THREADS_LINUX_FAILURE)
    {
        status = protocol_init();
        if(status != PROTOCOL_SUCCESS)
        {
            return_value = THREADS_LINUX_FAILURE;
        }
    }

    if(return_value != THREADS_LINUX_FAILURE)
    {
        status = ui_init();
        if(status != UI_SUCCESS)
        {
            return_value = THREADS_LINUX_FAILURE;
        }
    }

    if(return_value != THREADS_LINUX_FAILURE)
    {
        status = datalogger_init();
        if(status != DATALOGGER_SUCCESS)
        {
            return_value = THREADS_LINUX_FAILURE;
        }
    }

    // Main Loop
    if(return_value != THREADS_LINUX_FAILURE)
    {
        threads_linux_timer_start_task_1();
        usleep(0.5*task_1_period_us);
        threads_linux_timer_start_task_2();
        usleep(5*task_1_period_us);

        while(quittask == 0)
        {
            #if ANU_COMPILE_FOR_OVERO
            #else
            if(datalogger_status() == DATALOGGER_RUNNING) datalogger_update_IPC();
            #endif
            if(++n>100)
            {
                if(datalogger_status() == DATALOGGER_RUNNING) datalogger_write_file();
                n = 0;
            }
            usleep(5*task_1_period_us);
        }

        threads_linux_timer_stop_task_1();
        usleep(TASK1_PERIOD_US);
        threads_linux_timer_stop_task_2();
        usleep(TASK2_PERIOD_US);
    }

    status = datalogger_close();
    if(status != DATALOGGER_SUCCESS)
    {
        return_value = THREADS_LINUX_FAILURE;
    }

    status = ui_close();
    if(status != UI_SUCCESS)
    {
        return_value = THREADS_LINUX_FAILURE;
    }

    status = protocol_close();
    if(status != PROTOCOL_SUCCESS)
    {
        return_value = THREADS_LINUX_FAILURE;
    }

    status = control_close();
    if(status != CONTROL_SUCCESS)
    {
        return_value = THREADS_LINUX_FAILURE;
    }

    status = estimation_close(&estimation_data);
    if(status != ESTIMATION_SUCCESS)
    {
        return_value = THREADS_LINUX_FAILURE;
    }

    status = magnetometer_close(&magnetometer_measure);
    if(status != 1)
    {
        return_value = THREADS_LINUX_FAILURE;
    }

    status = imu_close(&imu_measure);
    if(status != 1)
    {
        return_value = THREADS_LINUX_FAILURE;
    }
    status = gps_close(&gps_measure);
    if(status != 1)
    {
        return_value = THREADS_LINUX_FAILURE;
    }

    status = calibration_close(&calibration_local_coordinate_system_data, &calibration_local_fields_data, &calibration_altimeter_data);
    if(status != CALIBRATION_SUCCESS)
    {
        return_value = THREADS_LINUX_FAILURE;
    }

    status = sensors_close();
    if(status != SENSORS_SUCCESS)
    {
        return_value = THREADS_LINUX_FAILURE;
    }

    return return_value;
}
Exemplo n.º 25
0
int main(void)
{
  // Initialize system
  serial_init(BAUD_RATE); // Setup serial baud rate and interrupts
  st_init(); // Setup stepper pins and interrupt timers
  sei(); // Enable interrupts

  memset(&sys, 0, sizeof(sys));  // Clear all system variables
  sys.abort = true;   // Set abort to complete initialization

  for(;;) {

    // Execute system reset upon a system abort, where the main program will return to this loop.
    // Once here, it is safe to re-initialize the system. At startup, the system will automatically
    // reset to finish the initialization process.
    if (sys.abort) {

      // Retain last known machine position and work coordinate offset(s). If the system abort
      // occurred while in motion, machine position is not guaranteed, since a hard stop can cause
      // the steppers to lose steps. Always perform a feedhold before an abort, if maintaining
      // accurate machine position is required.
      // TODO: Report last position and coordinate offset to users to help relocate origins. Future
      // releases will auto-reset the machine position back to [0,0,0] if an abort is used while
      // grbl is moving the machine.
/// by LETARTARE 3-> 4
      int32_t last_position[4];
      double last_coord_system[N_COORDINATE_SYSTEM][3];
      memcpy(last_position, sys.position, sizeof(sys.position)); // last_position[] = sys.position[]
      memcpy(last_coord_system, sys.coord_system, sizeof(sys.coord_system)); // last_coord_system[] = sys.coord_system[]

      // Reset system.
      memset(&sys, 0, sizeof(sys)); // Clear all system variables
      serial_reset_read_buffer(); // Clear serial read buffer
      settings_init(); // Load grbl settings from EEPROM
      protocol_init(); // Clear incoming line data
      plan_init(); // Clear block buffer and planner variables
      gc_init(); // Set g-code parser to default state
      spindle_init();
      limits_init();
      coolant_init();
      st_reset(); // Clear stepper subsystem variables.

      // Reload last known machine position and work systems. G92 coordinate offsets are reset.
      memcpy(sys.position, last_position, sizeof(last_position)); // sys.position[] = last_position[]
      memcpy(sys.coord_system, last_coord_system, sizeof(last_coord_system)); // sys.coord_system[] = last_coord_system[]
      gc_set_current_position(last_position[X_AXIS],last_position[Y_AXIS],last_position[Z_AXIS],last_position[C_AXIS]);
      plan_set_current_position(last_position[X_AXIS],last_position[Y_AXIS],last_position[Z_AXIS],last_position[C_AXIS]);

      // Set system runtime defaults
      // TODO: Eventual move to EEPROM from config.h when all of the new settings are worked out.
      // Mainly to avoid having to maintain several different versions.
      #ifdef CYCLE_AUTO_START
        sys.auto_start = true;
      #endif
      // TODO: Install G20/G21 unit default into settings and load appropriate settings.
    }

    protocol_execute_runtime();
    protocol_process(); // ... process the serial protocol

  }
  return 0;   /* never reached */
}
Exemplo n.º 26
0
void fc_init()
{
    DEBUG(" *** Flight computer init ***\n");

    //start values
    active_page = config.gui.last_page;
    if (active_page >= config.gui.number_of_pages)
        active_page = 0;

    //reset flight status
    fc_reset();

    //using fake data
#ifdef FAKE_ENABLE
    return;
#endif

    //temperature state machine
    fc.temp.step = 0;

    //init DMA
    DMA_PWR_ON;

    //init calculators
    vario_init();
    audio_init();
    logger_init();
    protocol_init();
    wind_init();

    gps_init();
    if (config.connectivity.use_gps)
        gps_start();

    bt_init();
    if (config.connectivity.use_bt)
        bt_module_init();

    //VCC to baro, acc/mag gyro + i2c pull-ups
    mems_power_on();

    //init and test i2c
    //HW_REW_1504 have two mems enable pins, both have to be enabled!
    //HW_REW_1506 have standalone ldo for mems, hence only one pin is needed
    if (!mems_i2c_init())
    {
        DEBUG("ERROR I2C, Wrong board rev? (%02X)\n", hw_revision);

        hw_revision = HW_REW_1504;
        eeprom_busy_wait();
        eeprom_update_byte(&config_ro.hw_revision, hw_revision);
        eeprom_busy_wait();

        mems_power_init();
        io_init();
        mems_power_on();
        assert(mems_i2c_init());
    }
    else
    {
        if (hw_revision == HW_REW_UNKNOWN)
        {
            hw_revision = HW_REW_1506;
            eeprom_busy_wait();
            eeprom_update_byte(&config_ro.hw_revision, hw_revision);
            eeprom_busy_wait();

            mems_power_init();
            io_init();
            mems_power_on();
            mems_i2c_init();
        }
    }


    if (!mems_i2c_init())
    {
        DEBUG("I2C error!\nUnable to init flight computer!\n");
        return;
    }

    //Barometer
    ms5611.Init(&mems_i2c, MS5611_ADDRESS_CSB_LO);

    //Magnetometer + Accelerometer
    lsm303d_settings lsm_cfg;

    lsm_cfg.enabled = true;
    lsm_cfg.accOdr = lsm_acc_1600Hz;
    lsm_cfg.accScale = lsm_acc_16g;

    lsm_cfg.magOdr = lsm_mag_100Hz;
    lsm_cfg.magScale = lsm_mag_4g;
    lsm_cfg.magHiRes = true;

    lsm_cfg.tempEnable = false;

    //Acceleration calculation init
    accel_calc_init();
    //Magnetic field calculation init
    mag_calc_init();

    //Gyro
    l3gd20_settings l3g_cfg;
    l3g_cfg.enabled = true;
    l3g_cfg.bw = l3g_50Hz;
    l3g_cfg.odr = l3g_760Hz;
    l3g_cfg.scale = l3g_2000dps;

    //SHT21
    sht21_settings sht_cfg;
    sht_cfg.rh_enabled = true;
    sht_cfg.temp_enabled = true;

    //XXX: do self-test?
    lsm303d.Init(&mems_i2c, lsm_cfg);
    lsm303d.Start();

    l3gd20.Init(&mems_i2c, l3g_cfg);
    l3gd20.Start();

    sht21.Init(&mems_i2c, sht_cfg);

    //Measurement timer
    FC_MEAS_TIMER_PWR_ON;

    fc_meas_timer.Init(FC_MEAS_TIMER, timer_div1024);
    fc_meas_timer.SetInterruptPriority(MEDIUM);
    fc_meas_timer.EnableInterrupts(timer_overflow | timer_compareA | timer_compareB | timer_compareC);

    //tight timing!	      1 tick 0.032 ms
    //MS pressure conversion     9.040 ms
    //   temperature conversion  0.600 ms
    //MAG read 					 0.152 ms
    //ACC read					 1.600 ms
    //Gyro read					 1.000 ms
    fc_meas_timer.SetTop(313); // == 10ms
    fc_meas_timer.SetCompare(timer_A, 27); // == 0.78 ms
    fc_meas_timer.SetCompare(timer_B, 70); // == 2 ms
    fc_meas_timer.SetCompare(timer_C, 200); // == 6 ms

    ms5611.StartTemperature();
    lsm303d.StartReadMag(); //it takes 152us to transfer
    _delay_ms(1);

    fc_meas_timer.Start();

    DEBUG(" *** FC init done ***\n");
}
Exemplo n.º 27
0
int
main(
    int		argc,
    char **	argv)
{
    int i;
    time_t timer;
    char *lineread = NULL;
    struct sigaction act, oact;
    extern char *optarg;
    extern int optind;
    char *line = NULL;
    const security_driver_t *secdrv;
    char *req = NULL;
    int response_error;
    struct tm *tm;
    config_overrides_t *cfg_ovr;
    char *starting_hostname = NULL;

    /*
     * Configure program for internationalization:
     *   1) Only set the message locale for now.
     *   2) Set textdomain for all amanda related programs to "amanda"
     *      We don't want to be forced to support dozens of message catalogs.
     */  
    setlocale(LC_MESSAGES, "C");
    textdomain("amanda"); 

    safe_fd(-1, 0);

    set_pname("amrecover");

    /* Don't die when child closes pipe */
    signal(SIGPIPE, SIG_IGN);

    dbopen(DBG_SUBDIR_CLIENT);

    /* treat amrecover-specific command line options as the equivalent
     * -o command-line options to set configuration values */
    cfg_ovr = new_config_overrides(argc/2);

    /* If the first argument is not an option flag, then we assume
     * it is a configuration name to match the syntax of the other
     * Amanda utilities. */
    if (argc > 1 && argv[1][0] != '-') {
	add_config_override(cfg_ovr, "conf", argv[1]);

	/* remove that option from the command line */
	argv[1] = argv[0];
	argv++; argc--;
    }

    /* now parse regular command-line '-' options */
    while ((i = getopt(argc, argv, "o:C:s:t:d:Uh:")) != EOF) {
	switch (i) {
	    case 'C':
		add_config_override(cfg_ovr, "conf", optarg);
		break;

	    case 's':
		add_config_override(cfg_ovr, "index_server", optarg);
		break;

	    case 't':
		add_config_override(cfg_ovr, "tape_server", optarg);
		break;

	    case 'd':
		add_config_override(cfg_ovr, "tapedev", optarg);
		break;

	    case 'o':
		add_config_override_opt(cfg_ovr, optarg);
		break;

	    case 'h':
		starting_hostname = g_strdup(optarg);
		break;

	    case 'U':
	    case '?':
		(void)g_printf(USAGE);
		return 0;
	}
    }
    if (optind != argc) {
	(void)g_fprintf(stderr, USAGE);
	exit(1);
    }

    /* load the base client configuration */
    set_config_overrides(cfg_ovr);
    config_init(CONFIG_INIT_CLIENT, NULL);

    if (config_errors(NULL) >= CFGERR_WARNINGS) {
	config_print_errors();
	if (config_errors(NULL) >= CFGERR_ERRORS) {
	    g_critical(_("errors processing config file"));
	}
    }

    /* and now try to load the configuration named in that file */
    config_init(CONFIG_INIT_CLIENT | CONFIG_INIT_EXPLICIT_NAME | CONFIG_INIT_OVERLAY,
		getconf_str(CNF_CONF));

    check_running_as(RUNNING_AS_ROOT);

    dbrename(get_config_name(), DBG_SUBDIR_CLIENT);

    our_features = am_init_feature_set();
    our_features_string = am_feature_to_string(our_features);

    if (!starting_hostname) {
	starting_hostname = g_malloc(MAX_HOSTNAME_LENGTH+1);
	if (gethostname(starting_hostname, MAX_HOSTNAME_LENGTH) != 0) {
	    error(_("cannot determine local host name\n"));
	    /*NOTREACHED*/
	}
	starting_hostname[MAX_HOSTNAME_LENGTH] = '\0';
    }

    server_name = NULL;
    if (getconf_seen(CNF_INDEX_SERVER) == -2) { /* command line argument */
	server_name = getconf_str(CNF_INDEX_SERVER);
    }
    if (!server_name) {
	server_name = getenv("AMANDA_SERVER");
	if (server_name) {
	    g_printf(_("Using index server from environment AMANDA_SERVER (%s)\n"), server_name);
	}
    }
    if (!server_name) {
	server_name = getconf_str(CNF_INDEX_SERVER);
    }
    if (!server_name) {
	error(_("No index server set"));
	/*NOTREACHED*/
    }
    server_name = g_strdup(server_name);

    tape_server_name = NULL;
    if (getconf_seen(CNF_TAPE_SERVER) == -2) { /* command line argument */
	tape_server_name = getconf_str(CNF_TAPE_SERVER);
    }
    if (!tape_server_name) {
	tape_server_name = getenv("AMANDA_TAPE_SERVER");
	if (!tape_server_name) {
	    tape_server_name = getenv("AMANDA_TAPESERVER");
	    if (tape_server_name) {
		g_printf(_("Using tape server from environment AMANDA_TAPESERVER (%s)\n"), tape_server_name);
	    }
	} else {
	    g_printf(_("Using tape server from environment AMANDA_TAPE_SERVER (%s)\n"), tape_server_name);
	}
    }
    if (!tape_server_name) {
	tape_server_name = getconf_str(CNF_TAPE_SERVER);
    }
    if (!tape_server_name) {
	error(_("No tape server set"));
	/*NOTREACHED*/
    }
    tape_server_name = g_strdup(tape_server_name);

    amfree(tape_device_name);
    tape_device_name = getconf_str(CNF_TAPEDEV);
    if (!tape_device_name ||
	strlen(tape_device_name) == 0 ||
	!getconf_seen(CNF_TAPEDEV)) {
	tape_device_name = NULL;
    } else {
	tape_device_name = g_strdup(tape_device_name);
    }

    authopt = g_strdup(getconf_str(CNF_AUTH));


    amfree(disk_name);
    amfree(mount_point);
    amfree(disk_path);
    dump_date[0] = '\0';

    /* Don't die when child closes pipe */
    signal(SIGPIPE, SIG_IGN);

    /* set up signal handler */
    act.sa_handler = sigint_handler;
    sigemptyset(&act.sa_mask);
    act.sa_flags = 0;
    if (sigaction(SIGINT, &act, &oact) != 0) {
	error(_("error setting signal handler: %s"), strerror(errno));
	/*NOTREACHED*/
    }

    proplist = g_hash_table_new_full(g_str_hash, g_str_equal, &g_free, &free_property_t);

    protocol_init();

    /* We assume that amindexd support fe_amindexd_options_features */
    /*                             and fe_amindexd_options_auth     */
    /* We should send a noop to really know                         */
    req = g_strdup_printf("SERVICE amindexd\n"
		    "OPTIONS features=%s;auth=%s;\n",
		    our_features_string, authopt);

    secdrv = security_getdriver(authopt);
    if (secdrv == NULL) {
	error(_("no '%s' security driver available for host '%s'"),
	    authopt, server_name);
	/*NOTREACHED*/
    }

    protocol_sendreq(server_name, secdrv, generic_client_get_security_conf,
		     req, STARTUP_TIMEOUT, amindexd_response, &response_error);

    amfree(req);
    protocol_run();

    g_printf(_("AMRECOVER Version %s. Contacting server on %s ...\n"),
	   VERSION, server_name);

    if(response_error != 0) {
	g_fprintf(stderr,"%s\n",errstr);
	exit(1);
    }

    /* get server's banner */
    if (grab_reply(1) == -1) {
        aclose(server_socket);
	exit(1);
    }
    if (!server_happy()) {
	dbclose();
	aclose(server_socket);
	exit(1);
    }

    /* try to get the features from the server */
    {
	char *their_feature_string = NULL;

	indexsrv_features = NULL;

	line = g_strdup_printf("FEATURES %s", our_features_string);
	if(exchange(line) == 0) {
	    their_feature_string = g_strdup(server_line+13);
	    indexsrv_features = am_string_to_feature(their_feature_string);
	    if (!indexsrv_features)
		g_printf(_("Bad feature string from server: %s"), their_feature_string);
	}
	if (!indexsrv_features)
	    indexsrv_features = am_set_default_feature_set();

	amfree(their_feature_string);
	amfree(line);
    }

    /* set the date of extraction to be today */
    (void)time(&timer);
    tm = localtime(&timer);
    if (tm) 
	strftime(dump_date, sizeof(dump_date), "%Y-%m-%d", tm);
    else
	error(_("BAD DATE"));

    g_printf(_("Setting restore date to today (%s)\n"), dump_date);
    line = g_strdup_printf("DATE %s", dump_date);
    if (converse(line) == -1) {
        aclose(server_socket);
	exit(1);
    }
    amfree(line);

    line = g_strdup_printf("SCNF %s", get_config_name());
    if (converse(line) == -1) {
        aclose(server_socket);
	exit(1);
    }
    amfree(line);

    if (server_happy()) {
	/* set host we are restoring to this host by default */
	amfree(dump_hostname);
	set_host(starting_hostname);
	if (dump_hostname)
	    g_printf(_("Use the setdisk command to choose dump disk to recover\n"));
	else
	    g_printf(_("Use the sethost command to choose a host to recover\n"));

    }

    quit_prog = 0;
    do {
	if ((lineread = readline("amrecover> ")) == NULL) {
	    clearerr(stdin);
	    putchar('\n');
	    break;
	}
	if (lineread[0] != '\0') 
	{
	    add_history(lineread);
	    dbprintf(_("user command: '%s'\n"), lineread);
	    process_line(lineread);	/* act on line's content */
	}
	amfree(lineread);
    } while (!quit_prog);

    dbclose();

    aclose(server_socket);
    return 0;
}
Exemplo n.º 28
0
/*
 * Use global *tty_tmp and term_parent
 */
int
main( int argc, char **argv )
{
   struct cl_args *cl_args;
   struct term_node *tty_node = NULL;
   pid_t pid;
   pid_t parent_id;
#if defined(HAVE_PTHREAD_SETCONCURRENCY) && !defined(LINUX)
   int concurrent;
#endif

   handle_signals_parent();

   tcgetattr(0, &term_parent);   

   parent_id = getpid();

   if ((pid = fork()) < 0)
   {
      exit(1);
   }
   else
   {
      if (pid != 0)
      {
         wait(NULL);
         tcsetattr(0, TCSANOW, &term_parent);
         exit(0);
      }
   }

   fatal_error = 4;

   /* Disable all signals while initializing data...*/
   handle_signals();

   setvbuf(stdout, NULL, _IONBF, 0);

   tty_tmp = (struct term_tty *)calloc(1,sizeof(struct term_tty));

   if (tty_tmp == NULL)
   {
      printf("Out of memory on calloc tty_tmp\n");
      clean_exit();
   }

   tty_tmp->term = (struct termios *)calloc(1,sizeof(struct termios));      

   if (tty_tmp->term == NULL)
   {
      printf("Out of memory on calloc tty_tmp->term\n");
      clean_exit();
   }

   /* default values */
   tty_tmp->interactive = 0;
   tty_tmp->gtk = 0;
   tty_tmp->attack = -1;
   tty_tmp->mac_spoofing = -1;
   tty_tmp->splash = -1;
   strncpy(tty_tmp->username, VTY_USER, MAX_USERNAME);
   strncpy(tty_tmp->password, VTY_PASS, MAX_PASSWORD);
   strncpy(tty_tmp->e_password, VTY_ENABLE, MAX_PASSWORD);
   tty_tmp->port = VTY_PORT;
   tty_tmp->ip_filter = NULL;
#ifdef HAVE_GTK
   tty_tmp->buffer_log = NULL;
#endif

   cl_args = (struct cl_args *)calloc(1,sizeof(struct cl_args));

   if (cl_args == NULL)
   {
      printf("Out of memory on calloc cl_args\n");
      clean_exit();
   }

   if ( argc == 1 )                                                          
   {
      printf("GNU %s %s %s\n", PACKAGE, VERSION,
            "$Date: 2006/03/23 08:40:14 $");
      printf("Try '%s -h' to display the help.\n",PACKAGE);
      clean_exit();
   }

   if (getuid() != 0) 
   {
      printf("You must be root to run %s %s\n", PACKAGE, VERSION);
      clean_exit();
   }

   if (term_init() < 0)
      g00dbye();

   /* Register all the protocols */
   protocol_init();

   cl_args->proto_index = -1;

   if (parser_initial(tty_tmp, cl_args, argc, argv) < 0) {
      clean_exit();
   } 

   init_log();

#if defined(HAVE_PTHREAD_SETCONCURRENCY) && !defined(LINUX)
/*   concurrent = pthread_getconcurrency();*/

   concurrent = 15;/*(MAX_TERMS*MAX_PROTOCOLS*MAX_THREAD_ATTACK*2)+3;*/

   if (pthread_setconcurrency(concurrent) != 0)
   {
      thread_error("init pthread_setconcurrency()",errno);
      g00dbye();
   }
#endif

   if (interfaces_init(&terms->pcap_listen_th) < 0 )
      g00dbye();

   /* Establish TERM signal handler...*/
   posix_signal(SIGTERM, final);


#ifdef HAVE_REMOTE_ADMIN
   if (tty_tmp->daemonize)
   {
      if (admin_init(tty_tmp) < 0)
         g00dbye();
   }
#endif 

   if (thread_create(&terms->uptime_th.id, &th_uptime, (void *)NULL) < 0)
      g00dbye();

   /* Command line and ncurses cannot be choosed simultaneously...*/
   if ((!tty_tmp->interactive) && (!tty_tmp->gtk) && (cl_args->proto_index != -1)) 
   {
      terms->work_state = INITIAL;
      tty_node = term_type[TERM_TTY].list;
      if (thread_create(&tty_node[0].thread.id, &th_tty_peer, 
               (void *)cl_args) < 0)
         g00dbye();

      while(terms->work_state != STOPPED)
         thread_usleep(100000);
   }

#ifdef HAS_CURSES
   if (tty_tmp->interactive)
   {
      terms->work_state = INITIAL;
      if (thread_create(&terms->gui_th.id, &ncurses_gui, NULL) < 0 )
         g00dbye();
      /* Wait until the ncurses GUI is over */
      while(terms->work_state != STOPPED)
         thread_usleep(100000);
   }
   else
   {
#endif
#ifdef HAVE_GTK
      if (tty_tmp->gtk)
      {
         terms->work_state = INITIAL;
         if (thread_create(&terms->gui_gtk_th.id, &gtk_gui, NULL) < 0 )
            g00dbye();
         /* Wait until the GTK GUI is over */
         while(terms->work_state != STOPPED)
            thread_usleep(100000);
      }
#endif
#ifdef HAS_CURSES
   }
#endif

#ifdef HAVE_REMOTE_ADMIN
   if (tty_tmp->daemonize)
   {
      /* Ok, now that console (ncurses) is finished
       * we can become a true daemon... */
      become_daemon(parent_id);

      /* Wait until some important thread exits due to fatal_error...*/
      while (fatal_error == 4)
         thread_usleep(100000);
   }
#endif

   g00dbye();

   exit(1);
}
Exemplo n.º 29
0
int main(int argc, char **argv) {

	log_file_disable();
	log_shell_enable();
	log_level_set(LOG_NOTICE);

	progname = malloc(16);
	strcpy(progname, "pilight-control");

	struct options_t *options = NULL;
	struct ssdp_list_t *ssdp_list = NULL;

	int sockfd = 0;
    char *recvBuff = NULL;
	char *message = NULL;
	char *pch = NULL;
	steps_t steps = WELCOME;

	char device[50];
	char location[50];
	char state[10] = {'\0'};
	char values[255] = {'\0'};
	struct conf_locations_t *slocation = NULL;
	struct conf_devices_t *sdevice = NULL;
	int has_values = 0;

	char *server = NULL;
	unsigned short port = 0;

	JsonNode *json = NULL;
	JsonNode *jconfig = NULL;
	JsonNode *jcode = NULL;
	JsonNode *jvalues = NULL;

	/* Define all CLI arguments of this program */
	options_add(&options, 'H', "help", no_value, 0, NULL);
	options_add(&options, 'V', "version", no_value, 0, NULL);
	options_add(&options, 'l', "location", has_value, 0, NULL);
	options_add(&options, 'd', "device", has_value, 0,  NULL);
	options_add(&options, 's', "state", has_value, 0,  NULL);
	options_add(&options, 'v', "values", has_value, 0,  NULL);
	options_add(&options, 'S', "server", has_value, 0, "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$");
	options_add(&options, 'P', "port", has_value, 0, "[0-9]{1,4}");

	/* Store all CLI arguments for later usage
	   and also check if the CLI arguments where
	   used correctly by the user. This will also
	   fill all necessary values in the options struct */
	while(1) {
		int c;
		c = options_parse(&options, argc, argv, 1, &optarg);
		if(c == -1)
			break;
		if(c == -2)
			c = 'H';
		switch(c) {
			case 'H':
				printf("\t -H --help\t\t\tdisplay this message\n");
				printf("\t -V --version\t\t\tdisplay version\n");
				printf("\t -S --server=x.x.x.x\t\tconnect to server address\n");
				printf("\t -P --port=xxxx\t\t\tconnect to server port\n");
				printf("\t -l --location=location\t\tthe location in which the device resides\n");
				printf("\t -d --device=device\t\tthe device that you want to control\n");
				printf("\t -s --state=state\t\tthe new state of the device\n");
				printf("\t -v --values=values\t\tspecific comma separated values, e.g.:\n");
				printf("\t\t\t\t\t-v dimlevel=10\n");
				exit(EXIT_SUCCESS);
			break;
			case 'V':
				printf("%s %s\n", progname, VERSION);
				exit(EXIT_SUCCESS);
			break;
			case 'l':
				strcpy(location, optarg);
			break;
			case 'd':
				strcpy(device, optarg);
			break;
			case 's':
				strcpy(state, optarg);
			break;
			case 'v':
				strcpy(values, optarg);
			break;
			case 'S':
				server = realloc(server, strlen(optarg)+1);
				strcpy(server, optarg);
			break;
			case 'P':
				port = (unsigned short)atoi(optarg);
			break;
			default:
				printf("Usage: %s -l location -d device -s state\n", progname);
				exit(EXIT_SUCCESS);
			break;
		}
	}
	options_delete(options);

	if(strlen(location) == 0 || strlen(device) == 0 || strlen(state) == 0) {
		printf("Usage: %s -l location -d device -s state\n", progname);
		exit(EXIT_SUCCESS);
	}

	if(server && port > 0) {
		if((sockfd = socket_connect(server, port)) == -1) {
			logprintf(LOG_ERR, "could not connect to pilight-daemon");
			exit(EXIT_FAILURE);
		}
	} else if(ssdp_seek(&ssdp_list) == -1) {
		logprintf(LOG_ERR, "no pilight ssdp connections found");
		goto close;
	} else {
		if((sockfd = socket_connect(ssdp_list->ip, ssdp_list->port)) == -1) {
			logprintf(LOG_ERR, "could not connect to pilight-daemon");
			goto close;
		}
		sfree((void *)&ssdp_list);
	}

	protocol_init();

	while(1) {
		if(steps > WELCOME) {
			/* Clear the receive buffer again and read the welcome message */
			if(steps == CONFIG) {
				if((recvBuff = socket_read_big(sockfd)) != NULL) {
					json = json_decode(recvBuff);
					json_find_string(json, "message", &message);
				} else {
					goto close;
				}
			} else {
				if((recvBuff = socket_read(sockfd)) != NULL) {
					json = json_decode(recvBuff);
					json_find_string(json, "message", &message);
				} else {
					goto close;
				}
			}
		usleep(100);
		}
		switch(steps) {
			case WELCOME:
				socket_write(sockfd, "{\"message\":\"client controller\"}");
				steps=IDENTIFY;
			break;
			case IDENTIFY:
				if(strcmp(message, "accept client") == 0) {
					steps=REQUEST;
				}
				if(strcmp(message, "reject client") == 0) {
					steps=REJECT;
				}
			case REQUEST:
				socket_write(sockfd, "{\"message\":\"request config\"}");
				steps=CONFIG;
				json_delete(json);
			break;
			case CONFIG:
				if((jconfig = json_find_member(json, "config")) != NULL) {
					config_parse(jconfig);
					if(config_get_location(location, &slocation) == 0) {
						if(config_get_device(location, device, &sdevice) == 0) {
							JsonNode *joutput = json_mkobject();
							jcode = json_mkobject();
							jvalues = json_mkobject();

							json_append_member(jcode, "location", json_mkstring(location));
							json_append_member(jcode, "device", json_mkstring(device));

							pch = strtok(values, ",=");
							while(pch != NULL) {
								char *name = strdup(pch);
								pch = strtok(NULL, ",=");
								if(pch == NULL) {
									break;
								} else {
									char *val = strdup(pch);
									if(pch != NULL) {
										if(config_valid_value(location, device, name, val) == 0) {
											if(isNumeric(val) == EXIT_SUCCESS) {
												json_append_member(jvalues, name, json_mknumber(atoi(val)));
											} else {
												json_append_member(jvalues, name, json_mkstring(val));
											}
											has_values = 1;
										} else {
											logprintf(LOG_ERR, "\"%s\" is an invalid value for device \"%s\"", name, device);
											goto close;
										}
									} else {
										logprintf(LOG_ERR, "\"%s\" is an invalid value for device \"%s\"", name, device);
										goto close;
									}
									pch = strtok(NULL, ",=");
									if(pch == NULL) {
										break;
									}
								}
							}

							if(config_valid_state(location, device, state) == 0) {
								json_append_member(jcode, "state", json_mkstring(state));
							} else {
								logprintf(LOG_ERR, "\"%s\" is an invalid state for device \"%s\"", state, device);
								goto close;
							}

							if(has_values == 1) {
								json_append_member(jcode, "values", jvalues);
							} else {
								json_delete(jvalues);
							}

							json_append_member(joutput, "message", json_mkstring("send"));
							json_append_member(joutput, "code", jcode);
							char *output = json_stringify(joutput, NULL);
							socket_write(sockfd, output);
							sfree((void *)&output);
							json_delete(joutput);
						} else {
							logprintf(LOG_ERR, "the device \"%s\" does not exist", device);
							goto close;
						}
					} else {
						logprintf(LOG_ERR, "the location \"%s\" does not exist", location);
						goto close;
					}
				}
				json_delete(json);
				goto close;
			break;
			case REJECT:
			default:
				json_delete(json);
				goto close;
			break;
		}
	}
close:
	if(sockfd > 0) {
		socket_close(sockfd);
	}
	if(server) {
		sfree((void *)&server);
	}
	log_shell_disable();
	config_gc();
	protocol_gc();
	socket_gc();
	options_gc();
	log_gc();
	sfree((void *)&progname);

return EXIT_SUCCESS;
}
Exemplo n.º 30
0
int main(void)
{
#ifdef PART_LM4F120H5QR // ARM code
  SysCtlClockSet( SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_XTAL_16MHZ | SYSCTL_OSC_MAIN ); //set system clock to 80 MHz
  FPUEnable(); //enable the Floating Point Unit
//  FPULazyStackingEnable(); // Enable stacking for interrupt handlers
#endif

  // Initialize system
  serial_init(); // Setup serial baud rate and interrupts
  settings_init(); // Load grbl settings from EEPROM
  st_init(); // Setup stepper pins and interrupt timers

#ifdef PART_LM4F120H5QR // ARM code
  IntMasterEnable();
#else // AVR code
  sei(); // Enable interrupts
#endif
  
  memset(&sys, 0, sizeof(sys));  // Clear all system variables
  sys.abort = true;   // Set abort to complete initialization
  sys.state = STATE_INIT;  // Set alarm state to indicate unknown initial position
  
  for(;;) {
  
    // Execute system reset upon a system abort, where the main program will return to this loop.
    // Once here, it is safe to re-initialize the system. At startup, the system will automatically
    // reset to finish the initialization process.
    if (sys.abort) {
      // Reset system.
      serial_reset_read_buffer(); // Clear serial read buffer
      plan_init(); // Clear block buffer and planner variables
      gc_init(); // Set g-code parser to default state
      protocol_init(); // Clear incoming line data and execute startup lines
      spindle_init();
      coolant_init();
      limits_init();
      st_reset(); // Clear stepper subsystem variables.

      // Sync cleared gcode and planner positions to current system position, which is only
      // cleared upon startup, not a reset/abort. 
      sys_sync_current_position();

      // Reset system variables.
      sys.abort = false;
      sys.execute = 0;
      if (bit_istrue(settings.flags,BITFLAG_AUTO_START)) { sys.auto_start = true; }
      
      // Check for power-up and set system alarm if homing is enabled to force homing cycle
      // by setting Grbl's alarm state. Alarm locks out all g-code commands, including the
      // startup scripts, but allows access to settings and internal commands. Only a homing
      // cycle '$H' or kill alarm locks '$X' will disable the alarm.
      // NOTE: The startup script will run after successful completion of the homing cycle, but
      // not after disabling the alarm locks. Prevents motion startup blocks from crashing into
      // things uncontrollably. Very bad.
      #ifdef HOMING_INIT_LOCK
        if (sys.state == STATE_INIT && bit_istrue(settings.flags,BITFLAG_HOMING_ENABLE)) { sys.state = STATE_ALARM; }
      #endif
      
      // Check for and report alarm state after a reset, error, or an initial power up.
      if (sys.state == STATE_ALARM) {
        report_feedback_message(MESSAGE_ALARM_LOCK); 
      } else {
        // All systems go. Set system to ready and execute startup script.
        sys.state = STATE_IDLE;
        protocol_execute_startup(); 
      }
    }
    
    protocol_execute_runtime();
    protocol_process(); // ... process the serial protocol
    
    // When the serial protocol returns, there are no more characters in the serial read buffer to
    // be processed and executed. This indicates that individual commands are being issued or 
    // streaming is finished. In either case, auto-cycle start, if enabled, any queued moves.
    if (sys.auto_start) { st_cycle_start(); }
    
  }
  // return 0;   /* never reached */
}