while(1){// If we have a socket, try to accept connectionsif((mode&MODE_SOCKET)&&sockfd){structsockaddrclient_addr;size_tclient_addrlen;intnewclientfd=accept(sockfd,&client_addr,&client_addrlen);if(newclientfd>=0){if(current_clients==MAX_CLIENTS){// Bummer, too manyclose(newclientfd);}newclient=true;for(inti=0;i<MAX_CLIENTS;i++){if(clientfds[i]==-1){clientfds[i]=newclientfd;current_clients++;break;}}}}// Read mote pin connectorsintyellow=sggpio.readPin(MOTELED_YELLOW_PIN);intgreen=sggpio.readPin(MOTELED_GREEN_PIN);intred=sggpio.readPin(MOTELED_RED_PIN);// Mote LEDs use negative logic, reverse themif(yellow){yellow=0;}else{yellow=1;}if(green){green=0;}else{green=1;}if(red){red=0;}else{red=1;}// In mirroring mode, set up a patter for the SG LEDs and ioctl() it// into placeif(mode&MODE_MIRROR){intledpattern=0;if(yellow){ledpattern|=LED_RED;}if(green){ledpattern|=LED_GREEN;}if(red){ledpattern|=LED_YELLOW;}if(ioctl(ledfd,CLED_IOSET,ledpattern)<0){fprintf(stderr,"ioctl set error: %s\n",LED_DEV);exit(1);}}// Check to see if what we got this time was different from last timecurrent_status=(red<<2)|(green<<1)|yellow;if(old_status!=current_status){// In printing mode, do just thatif(mode&MODE_PRINT){printf("%i %i %i\n",red,green,yellow);}}

// If we have a socket, print on thatif((mode&MODE_SOCKET)&&(current_clients>0)){charoutbuf[1024];snprintf(outbuf,1024,"%i %i %i\n",red,green,yellow);for(inti=0;i<=MAX_CLIENTS;i++){intclientfd=clientfds[i];if(clientfd==-1){continue;}if(write(clientfd,outbuf,strlen(outbuf))<0){// Detect disconnected clientsif(errno!=EPIPE){perror("write");}close(clientfd);clientfds[i]=-1;current_clients--;}}}newclient=false;