Skip to content
api.c 70.3 KiB
Newer Older
Franz's avatar
Franz committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
/*
  libxbee - a C library to aid the use of Digi's Series 1 XBee modules
            running in API mode (AP=2).

  Copyright (C) 2009  Attie Grande (attie@attie.co.uk)

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
const char *SVN_REV = "$Id: api.c 508 2011-06-12 23:22:34Z attie@attie.co.uk $";
char svn_rev[128] = "\0";

#include "api.h"

const char *xbee_svn_version(void) {
  if (svn_rev[0] == '\0') {
    char *t;
    sprintf(svn_rev,"r%s",&SVN_REV[11]);
    t = strrchr(svn_rev,' ');
    if (t) {
      t[0] = '\0';
    }
  }
  return svn_rev;
}

const char *xbee_build_info(void) {
  return "Built on " __DATE__ " @ " __TIME__ " for " HOST_OS;
}

/* ################################################################# */
/* ### Memory Handling ############################################# */
/* ################################################################# */

/* malloc wrapper function */
static void *Xmalloc2(xbee_hnd xbee, size_t size) {
  void *t;
  t = malloc(size);
  if (!t) {
    /* uhoh... thats pretty bad... */
    xbee_perror("libxbee:malloc()");
    exit(1);
  }
  return t;
}

/* calloc wrapper function */
static void *Xcalloc2(xbee_hnd xbee, size_t size) {
  void *t;
  t = calloc(1, size);
  if (!t) {
    /* uhoh... thats pretty bad... */
    xbee_perror("libxbee:calloc()");
    exit(1);
  }
  return t;
}

/* realloc wrapper function */
static void *Xrealloc2(xbee_hnd xbee, void *ptr, size_t size) {
  void *t;
  t = realloc(ptr,size);
  if (!t) {
    /* uhoh... thats pretty bad... */
    fprintf(stderr,"libxbee:realloc(): Returned NULL\n");
    exit(1);
  }
  return t;
}

/* free wrapper function (uses the Xfree macro and sets the pointer to NULL after freeing it) */
static void Xfree2(void **ptr) {
  if (!*ptr) return;
  free(*ptr);
  *ptr = NULL;
}

/* ################################################################# */
/* ### Helper Functions ############################################ */
/* ################################################################# */

/* #################################################################
   returns 1 if the packet has data for the digital input else 0 */
int xbee_hasdigital(xbee_pkt *pkt, int sample, int input) {
  int mask = 0x0001;
  if (input < 0 || input > 7) return 0;
  if (sample >= pkt->samples) return 0;

  mask <<= input;
  return !!(pkt->IOdata[sample].IOmask & mask);
}

/* #################################################################
   returns 1 if the digital input is high else 0 (or 0 if no digital data present) */
int xbee_getdigital(xbee_pkt *pkt, int sample, int input) {
  int mask = 0x0001;
  if (!xbee_hasdigital(pkt,sample,input)) return 0;

  mask <<= input;
  return !!(pkt->IOdata[sample].IOdigital & mask);
}

/* #################################################################
   returns 1 if the packet has data for the analog input else 0 */
int xbee_hasanalog(xbee_pkt *pkt, int sample, int input) {
  int mask = 0x0200;
  if (input < 0 || input > 5) return 0;
  if (sample >= pkt->samples) return 0;

  mask <<= input;
  return !!(pkt->IOdata[sample].IOmask & mask);
}

/* #################################################################
   returns analog input as a voltage if vRef is non-zero, else raw value (or 0 if no analog data present) */
double xbee_getanalog(xbee_pkt *pkt, int sample, int input, double Vref) {
  if (!xbee_hasanalog(pkt,sample,input)) return 0;

  if (Vref) return (Vref / 1023) * pkt->IOdata[sample].IOanalog[input];
  return pkt->IOdata[sample].IOanalog[input];
}

/* ################################################################# */
/* ### XBee Functions ############################################## */
/* ################################################################# */

static void xbee_logf(xbee_hnd xbee, const char *logformat, const char *file,
                      const int line, const char *function, char *format, ...) {
  char buf[128];
  va_list ap;
  if (!xbee) return;
  if (!xbee->log) return;
  va_start(ap,format);
  vsnprintf(buf,127,format,ap);
  va_end(ap);
  fprintf(xbee->log,logformat,file,line,function,buf);
}
void xbee_logitf(char *format, ...) {
  char buf[128];
  va_list ap;
  va_start(ap,format);
  vsnprintf(buf,127,format,ap);
  va_end(ap);
  xbee_logit(buf);
}
void _xbee_logitf(xbee_hnd xbee, char *format, ...) {
  char buf[128];
  va_list ap;
  va_start(ap,format);
  vsnprintf(buf,127,format,ap);
  va_end(ap);
  _xbee_logit(xbee, buf);
}
void xbee_logit(char *str) {
  _xbee_logit(default_xbee, str);
}
void _xbee_logit(xbee_hnd xbee, char *str) {
  if (!xbee) return;
  if (!xbee->log) return;
  xbee_mutex_lock(xbee->logmutex);
  fprintf(xbee->log,LOG_FORMAT"\n",__FILE__,__LINE__,__FUNCTION__,str);
  xbee_mutex_unlock(xbee->logmutex);
}

/* #################################################################
   xbee_sendAT - INTERNAL
   allows for an at command to be send, and the reply to be captured */
static int xbee_sendAT(xbee_hnd xbee, char *command, char *retBuf, int retBuflen) {
  return xbee_sendATdelay(xbee, 0, command, retBuf, retBuflen);
}
static int xbee_sendATdelay(xbee_hnd xbee, int guardTime, char *command, char *retBuf, int retBuflen) {
  struct timeval to;

  int ret;
  int bufi = 0;

  /* if there is a guardTime given, then use it and a bit more */
  if (guardTime) usleep(guardTime * 1200);

  /* get rid of any pre-command sludge... */
  memset(&to, 0, sizeof(to));
  ret = xbee_select(xbee,&to);
  if (ret > 0) {
    char t[128];
    while (xbee_read(xbee,t,127));
  }

  /* send the requested command */
  xbee_log("sendATdelay: Sending '%s'", command);
  xbee_write(xbee,command, strlen(command));

  /* if there is a guardTime, then use it */
  if (guardTime) {
    usleep(guardTime * 900);

    /* get rid of any post-command sludge... */
    memset(&to, 0, sizeof(to));
    ret = xbee_select(xbee,&to);
    if (ret > 0) {
      char t[128];
      while (xbee_read(xbee,t,127));
    }
  }

  /* retrieve the data */
  memset(retBuf, 0, retBuflen);
  memset(&to, 0, sizeof(to));
  if (guardTime) {
    /* select on the xbee fd... wait at most 0.2 the guardTime for the response */
    to.tv_usec = guardTime * 200;
  } else {
    /* or 250ms */
    to.tv_usec = 250000;
  }
  if ((ret = xbee_select(xbee,&to)) == -1) {
    xbee_perror("libxbee:xbee_sendATdelay()");
    exit(1);
  }

  if (!ret) {
    /* timed out, and there is nothing to be read */
    xbee_log("sendATdelay: No Data to read - Timeout...");
    return 1;
  }

  /* check for any dribble... */
  do {
    /* if there is actually no space in the retBuf then break out */
    if (bufi >= retBuflen - 1) {
      break;
    }

    /* read as much data as is possible into retBuf */
    if ((ret = xbee_read(xbee,&retBuf[bufi], retBuflen - bufi - 1)) == 0) {
      break;
    }

    /* advance the 'end of string' pointer */
    bufi += ret;

    /* wait at most 150ms for any more data */
    memset(&to, 0, sizeof(to));
    to.tv_usec = 150000;
    if ((ret = xbee_select(xbee,&to)) == -1) {
      xbee_perror("libxbee:xbee_sendATdelay()");
      exit(1);
    }

    /* loop while data was read */
  } while (ret);

  if (!bufi) {
    xbee_log("sendATdelay: No response...");
    return 1;
  }

  /* terminate the string */
  retBuf[bufi] = '\0';

  xbee_log("sendATdelay: Recieved '%s'",retBuf);
  return 0;
}


/* #################################################################
   xbee_start
   sets up the correct API mode for the xbee
   cmdSeq  = CC
   cmdTime = GT */
static int xbee_startAPI(xbee_hnd xbee) {
  char buf[256];

  if (xbee->cmdSeq == 0 || xbee->cmdTime == 0) return 1;

  /* setup the command sequence string */
  memset(buf,xbee->cmdSeq,3);
  buf[3] = '\0';

  /* try the command sequence */
  if (xbee_sendATdelay(xbee, xbee->cmdTime, buf, buf, sizeof(buf))) {
    /* if it failed... try just entering 'AT' which should return OK */
    if (xbee_sendAT(xbee, "AT\r", buf, 4) || strncmp(buf,"OK\r",3)) return 1;
  } else if (strncmp(&buf[strlen(buf)-3],"OK\r",3)) {
    /* if data was returned, but it wasn't OK... then something went wrong! */
    return 1;
  }

  /* get the current API mode */
  if (xbee_sendAT(xbee, "ATAP\r", buf, 3)) return 1;
  buf[1] = '\0';
  xbee->oldAPI = atoi(buf);

  if (xbee->oldAPI != 2) {
    /* if it wasnt set to mode 2 already, then set it to mode 2 */
    if (xbee_sendAT(xbee, "ATAP2\r", buf, 4) || strncmp(buf,"OK\r",3)) return 1;
  }

  /* quit from command mode, ready for some packets! :) */
  if (xbee_sendAT(xbee, "ATCN\r", buf, 4) || strncmp(buf,"OK\r",3)) return 1;

  return 0;
}

/* #################################################################
   xbee_end
   resets the API mode to the saved value - you must have called xbee_setup[log]API */
int xbee_end(void) {
  return _xbee_end(default_xbee);
}
int _xbee_end(xbee_hnd xbee) {
  int ret = 1;
  xbee_con *con, *ncon;
  xbee_pkt *pkt, *npkt;
  xbee_hnd xbeet;

  ISREADYR(0);
  xbee_log("Stopping libxbee instance...");

  /* unlink the instance from list... */
  xbee_log("Unlinking instance from list...");
  xbee_mutex_lock(xbee_hnd_mutex);
  if (xbee == default_xbee) {
    default_xbee = default_xbee->next;
    if (!default_xbee) {
      xbee_mutex_destroy(xbee_hnd_mutex);
    }
  } else {
    xbeet = default_xbee;
    while (xbeet) {
      if (xbeet->next == xbee) {
        xbeet->next = xbee->next;
        break;
      }
      xbeet = xbeet->next;
    }
  }
  if (default_xbee) xbee_mutex_unlock(xbee_hnd_mutex);
  
  /* if the api mode was not 2 to begin with then put it back */
  if (xbee->oldAPI == 2) {
    xbee_log("XBee was already in API mode 2, no need to reset");
    ret = 0;
  } else {
    int to = 5;

    con = _xbee_newcon(xbee,'I',xbee_localAT);
    con->callback = NULL;
    con->waitforACK = 1;
    _xbee_senddata(xbee,con,"AP%c",xbee->oldAPI);

    pkt = NULL;

    while (!pkt && to--) {
      pkt = _xbee_getpacketwait(xbee,con);
    }
    if (pkt) {
      ret = pkt->status;
      Xfree(pkt);
    }
    _xbee_endcon(xbee,con);
  }

  /* xbee_* functions may no longer run... */
  xbee->xbee_ready = 0;
  
  /* nullify everything */

  /* stop listening for data... either after timeout or next char read which ever is first */
  xbee->run = 0;
  
  xbee_thread_cancel(xbee->listent,0);
  xbee_thread_join(xbee->listent);
  
  xbee_thread_cancel(xbee->threadt,0);
  xbee_thread_join(xbee->threadt);

  /* free all connections */
  con = xbee->conlist;
  xbee->conlist = NULL;
  while (con) {
    ncon = con->next;
    Xfree(con);
    con = ncon;
  }

  /* free all packets */
  xbee->pktlast = NULL;
  pkt = xbee->pktlist;
  xbee->pktlist = NULL;
  while (pkt) {
    npkt = pkt->next;
    Xfree(pkt);
    pkt = npkt;
  }

  /* destroy mutexes */
  xbee_mutex_destroy(xbee->conmutex);
  xbee_mutex_destroy(xbee->pktmutex);
  xbee_mutex_destroy(xbee->sendmutex);

  /* close the serial port */
  Xfree(xbee->path);
  if (xbee->tty) xbee_close(xbee->tty);

  /* close log and tty */
  if (xbee->log) {
    fflush(xbee->log);
    xbee_close(xbee->log);
  }
  xbee_mutex_destroy(xbee->logmutex);

  Xfree(xbee);

  return ret;
}

/* #################################################################
   xbee_setup
   opens xbee serial port & creates xbee listen thread
   the xbee must be configured for API mode 2
   THIS MUST BE CALLED BEFORE ANY OTHER XBEE FUNCTION */
int xbee_setup(char *path, int baudrate) {
  return xbee_setuplogAPI(path,baudrate,0,0,0);
}
xbee_hnd _xbee_setup(char *path, int baudrate) {
  return _xbee_setuplogAPI(path,baudrate,0,0,0);
}
int xbee_setuplog(char *path, int baudrate, int logfd) {
  return  xbee_setuplogAPI(path,baudrate,logfd,0,0);
}
xbee_hnd _xbee_setuplog(char *path, int baudrate, int logfd) {
  return _xbee_setuplogAPI(path,baudrate,logfd,0,0);
}
int xbee_setupAPI(char *path, int baudrate, char cmdSeq, int cmdTime) {
  return xbee_setuplogAPI(path,baudrate,0,cmdSeq,cmdTime);
}
xbee_hnd _xbee_setupAPI(char *path, int baudrate, char cmdSeq, int cmdTime) {
  return _xbee_setuplogAPI(path,baudrate,0,cmdSeq,cmdTime);
}
int xbee_setuplogAPI(char *path, int baudrate, int logfd, char cmdSeq, int cmdTime) {
  if (default_xbee) return 0;
  default_xbee = _xbee_setuplogAPI(path,baudrate,logfd,cmdSeq,cmdTime);
  return (default_xbee?0:-1);
}
xbee_hnd _xbee_setuplogAPI(char *path, int baudrate, int logfd, char cmdSeq, int cmdTime) {
  int ret;
  xbee_hnd xbee = NULL;

  /* create a new instance */
  xbee = Xcalloc(sizeof(struct xbee_hnd));
  xbee->next = NULL;
  
  xbee_mutex_init(xbee->logmutex);
#ifdef DEBUG
  if (!logfd) logfd = 2;
#endif
  if (logfd) {
    xbee->logfd = dup(logfd);
    xbee->log = fdopen(xbee->logfd,"w");
    if (!xbee->log) {
      /* errno == 9 is bad file descriptor (probrably not provided) */
      if (errno != 9) xbee_perror("xbee_setup(): Failed opening logfile");
      xbee->logfd = 0;
    } else {
#ifdef __GNUC__ /* ---- */
      /* set to line buffer - ensure lines are written to file when complete */
      setvbuf(xbee->log,NULL,_IOLBF,BUFSIZ);
#else /* -------------- */
      /* Win32 is rubbish... so we have to completely disable buffering... */
      setvbuf(xbee->log,NULL,_IONBF,BUFSIZ);
#endif /* ------------- */
    }
  }

  xbee_logS("---------------------------------------------------------------------");
  xbee_logI("libxbee Starting...");
  xbee_logI("SVN Info: %s",xbee_svn_version());
  xbee_logI("Build Info: %s",xbee_build_info());
  xbee_logE("---------------------------------------------------------------------");

  /* setup the connection stuff */
  xbee->conlist = NULL;

  /* setup the packet stuff */
  xbee->pktlist = NULL;
  xbee->pktlast = NULL;
  xbee->pktcount = 0;
  xbee->run = 1;

  /* setup the mutexes */
  if (xbee_mutex_init(xbee->conmutex)) {
    xbee_perror("xbee_setup():xbee_mutex_init(conmutex)");
    if (xbee->log) xbee_close(xbee->log);
    Xfree(xbee);
    return NULL;
  }
  if (xbee_mutex_init(xbee->pktmutex)) {
    xbee_perror("xbee_setup():xbee_mutex_init(pktmutex)");
    if (xbee->log) xbee_close(xbee->log);
    xbee_mutex_destroy(xbee->conmutex);
    Xfree(xbee);
    return NULL;
  }
  if (xbee_mutex_init(xbee->sendmutex)) {
    xbee_perror("xbee_setup():xbee_mutex_init(sendmutex)");
    if (xbee->log) xbee_close(xbee->log);
    xbee_mutex_destroy(xbee->conmutex);
    xbee_mutex_destroy(xbee->pktmutex);
    Xfree(xbee);
    return NULL;
  }

  /* take a copy of the XBee device path */
  if ((xbee->path = Xmalloc(sizeof(char) * (strlen(path) + 1))) == NULL) {
    xbee_perror("xbee_setup():Xmalloc(path)");
    if (xbee->log) xbee_close(xbee->log);
    xbee_mutex_destroy(xbee->conmutex);
    xbee_mutex_destroy(xbee->pktmutex);
    xbee_mutex_destroy(xbee->sendmutex);
    Xfree(xbee);
    return NULL;
  }
  strcpy(xbee->path,path);
  if (xbee->log) xbee_log("Opening serial port '%s'...",xbee->path);

  /* call the relevant init function */
  if ((ret = init_serial(xbee,baudrate)) != 0) {
    xbee_log("Something failed while opening the serial port...");
    if (xbee->log) xbee_close(xbee->log);
    xbee_mutex_destroy(xbee->conmutex);
    xbee_mutex_destroy(xbee->pktmutex);
    xbee_mutex_destroy(xbee->sendmutex);
    Xfree(xbee->path);
    Xfree(xbee);
    return NULL;
  }

  /* when xbee_end() is called, if this is not 2 then ATAP will be set to this value */
  xbee->oldAPI = 2;
  xbee->cmdSeq = cmdSeq;
  xbee->cmdTime = cmdTime;
  if (xbee->cmdSeq && xbee->cmdTime) {
    if (xbee_startAPI(xbee)) {
      if (xbee->log) {
        xbee_log("Couldn't communicate with XBee...");
        xbee_close(xbee->log);
      }
      xbee_mutex_destroy(xbee->conmutex);
      xbee_mutex_destroy(xbee->pktmutex);
      xbee_mutex_destroy(xbee->sendmutex);
      Xfree(xbee->path);
#ifdef __GNUC__ /* ---- */
      close(xbee->ttyfd);
#endif /* ------------- */
      xbee_close(xbee->tty);
      Xfree(xbee);
      return NULL;
    }
  }

  /* allow the listen thread to start */
  xbee->xbee_ready = -1;

  /* can start xbee_listen thread now */
  if (xbee_thread_create(xbee->listent, xbee_listen_wrapper, xbee)) {
    xbee_perror("xbee_setup():xbee_thread_create(listent)");
    if (xbee->log) xbee_close(xbee->log);
    xbee_mutex_destroy(xbee->conmutex);
    xbee_mutex_destroy(xbee->pktmutex);
    xbee_mutex_destroy(xbee->sendmutex);
    Xfree(xbee->path);
#ifdef __GNUC__ /* ---- */
    close(xbee->ttyfd);
#endif /* ------------- */
    xbee_close(xbee->tty);
    Xfree(xbee);
    return NULL;
  }
  
  /* can start xbee_thread_watch thread thread now */
  if (xbee_thread_create(xbee->threadt, xbee_thread_watch, xbee)) {
    xbee_perror("xbee_setup():xbee_thread_create(threadt)");
    if (xbee->log) xbee_close(xbee->log);
    xbee_mutex_destroy(xbee->conmutex);
    xbee_mutex_destroy(xbee->pktmutex);
    xbee_mutex_destroy(xbee->sendmutex);
    Xfree(xbee->path);
#ifdef __GNUC__ /* ---- */
    close(xbee->ttyfd);
#endif /* ------------- */
    xbee_close(xbee->tty);
    Xfree(xbee);
    return NULL;
  }

  usleep(500);
  while (xbee->xbee_ready != -2) {
    usleep(500);
    xbee_log("Waiting for xbee_listen() to be ready...");
  }

  /* allow other functions to be used! */
  xbee->xbee_ready = 1;
  
  xbee_log("Linking xbee instance...");
  if (!default_xbee) {
    xbee_mutex_init(xbee_hnd_mutex);
    xbee_mutex_lock(xbee_hnd_mutex);
    default_xbee = xbee;
    xbee_mutex_unlock(xbee_hnd_mutex);
  } else {
    xbee_hnd xbeet;
    xbee_mutex_lock(xbee_hnd_mutex);
    xbeet = default_xbee;
    while (xbeet->next) {
      xbeet = xbeet->next;
    }
    xbeet->next = xbee;
    xbee_mutex_unlock(xbee_hnd_mutex);
  }
  
  xbee_log("libxbee: Started!");

  return xbee;
}

/* #################################################################
   xbee_con
   produces a connection to the specified device and frameID
   if a connection had already been made, then this connection will be returned */
xbee_con *xbee_newcon(unsigned char frameID, xbee_types type, ...) {
  xbee_con *ret;
  va_list ap;

  /* xbee_vnewcon() wants a va_list... */
  va_start(ap, type);
  /* hand it over :) */
  ret = _xbee_vnewcon(default_xbee, frameID, type, ap);
  va_end(ap);
  return ret;
}
xbee_con *_xbee_newcon(xbee_hnd xbee, unsigned char frameID, xbee_types type, ...) {
  xbee_con *ret;
  va_list ap;

  /* xbee_vnewcon() wants a va_list... */
  va_start(ap, type);
  /* hand it over :) */
  ret = _xbee_vnewcon(xbee, frameID, type, ap);
  va_end(ap);
  return ret;
}
xbee_con *_xbee_vnewcon(xbee_hnd xbee, unsigned char frameID, xbee_types type, va_list ap) {
  xbee_con *con, *ocon;
  unsigned char tAddr[8];
  int t;
  int i;

  ISREADYR(NULL);

  if (!type || type == xbee_unknown) type = xbee_localAT; /* default to local AT */
  else if (type == xbee_remoteAT) type = xbee_64bitRemoteAT; /* if remote AT, default to 64bit */

  /* if: 64 bit address expected (2 ints) */
  if ((type == xbee_64bitRemoteAT) ||
      (type == xbee_64bitData) ||
      (type == xbee_64bitIO) ||
      (type == xbee2_data)) {
    t = va_arg(ap, int);
    tAddr[0] = (t >> 24) & 0xFF;
    tAddr[1] = (t >> 16) & 0xFF;
    tAddr[2] = (t >>  8) & 0xFF;
    tAddr[3] = (t      ) & 0xFF;
    t = va_arg(ap, int);
    tAddr[4] = (t >> 24) & 0xFF;
    tAddr[5] = (t >> 16) & 0xFF;
    tAddr[6] = (t >>  8) & 0xFF;
    tAddr[7] = (t      ) & 0xFF;

    /* if: 16 bit address expected (1 int) */
  } else if ((type == xbee_16bitRemoteAT) ||
             (type == xbee_16bitData) ||
             (type == xbee_16bitIO)) {
    t = va_arg(ap, int);
    tAddr[0] = (t >>  8) & 0xFF;
    tAddr[1] = (t      ) & 0xFF;
    tAddr[2] = 0;
    tAddr[3] = 0;
    tAddr[4] = 0;
    tAddr[5] = 0;
    tAddr[6] = 0;
    tAddr[7] = 0;

    /* otherwise clear the address */
  } else {
    memset(tAddr,0,8);
  }

  /* lock the connection mutex */
  xbee_mutex_lock(xbee->conmutex);

  /* are there any connections? */
  if (xbee->conlist) {
    con = xbee->conlist;
    while (con) {
      /* if: looking for a modemStatus, and the types match! */
      if ((type == xbee_modemStatus) &&
          (con->type == type)) {
        xbee_mutex_unlock(xbee->conmutex);
        return con;

        /* if: looking for a txStatus and frameIDs match! */
      } else if ((type == xbee_txStatus) &&
                 (con->type == type) &&
                 (frameID == con->frameID)) {
        xbee_mutex_unlock(xbee->conmutex);
        return con;

        /* if: looking for a localAT, and the frameIDs match! */
      } else if ((type == xbee_localAT) &&
                 (con->type == type) &&
                 (frameID == con->frameID)) {
        xbee_mutex_unlock(xbee->conmutex);
        return con;

        /* if: connection types match, the frameIDs match, and the addresses match! */
      } else if ((type == con->type) &&
                 (frameID == con->frameID) &&
                 (!memcmp(tAddr,con->tAddr,8))) {
        xbee_mutex_unlock(xbee->conmutex);
        return con;
      }

      /* if there are more, move along, dont want to loose that last item! */
      if (con->next == NULL) break;
      con = con->next;
    }

    /* keep hold of the last connection... we will need to link it up later */
    ocon = con;
  }

  /* unlock the connection mutex */
  xbee_mutex_unlock(xbee->conmutex);
  
  /* create a new connection and set its attributes */
  con = Xcalloc(sizeof(xbee_con));
  con->type = type;
  /* is it a 64bit connection? */
  if ((type == xbee_64bitRemoteAT) ||
      (type == xbee_64bitData) ||
      (type == xbee_64bitIO) ||
      (type == xbee2_data)) {
    con->tAddr64 = TRUE;
  }
  con->atQueue = 0; /* queue AT commands? */
  con->txDisableACK = 0; /* disable ACKs? */
  con->txBroadcastPAN = 0; /* broadcast? */
  con->frameID = frameID;
  con->waitforACK = 0;
  memcpy(con->tAddr,tAddr,8); /* copy in the remote address */
  xbee_mutex_init(con->callbackmutex);
  xbee_mutex_init(con->callbackListmutex);
  xbee_mutex_init(con->Txmutex);
  xbee_sem_init(con->waitforACKsem);

  if (xbee->log) {
    switch(type) {
    case xbee_localAT:
      xbee_log("New local AT connection!");
      break;
    case xbee_16bitRemoteAT:
    case xbee_64bitRemoteAT:
      xbee_logc("New %d-bit remote AT connection! (to: ",(con->tAddr64?64:16));
      for (i=0;i<(con->tAddr64?8:2);i++) {
        fprintf(xbee->log,(i?":%02X":"%02X"),tAddr[i]);
      }
      fprintf(xbee->log,")");
      xbee_logcf();
      break;
    case xbee_16bitData:
    case xbee_64bitData:
      xbee_logc("New %d-bit data connection! (to: ",(con->tAddr64?64:16));
      for (i=0;i<(con->tAddr64?8:2);i++) {
        fprintf(xbee->log,(i?":%02X":"%02X"),tAddr[i]);
      }
      fprintf(xbee->log,")");
      xbee_logcf();
      break;
    case xbee_16bitIO:
    case xbee_64bitIO:
      xbee_logc("New %d-bit IO connection! (to: ",(con->tAddr64?64:16));
      for (i=0;i<(con->tAddr64?8:2);i++) {
        fprintf(xbee->log,(i?":%02X":"%02X"),tAddr[i]);
      }
      fprintf(xbee->log,")");
      xbee_logcf();
      break;
    case xbee2_data:
      xbee_logc("New Series 2 data connection! (to: ");
      for (i=0;i<8;i++) {
        fprintf(xbee->log,(i?":%02X":"%02X"),tAddr[i]);
      }
      fprintf(xbee->log,")");
      xbee_logcf();
      break;
    case xbee_txStatus:
      xbee_log("New Tx status connection!");
      break;
    case xbee_modemStatus:
      xbee_log("New modem status connection!");
      break;
    case xbee_unknown:
    default:
      xbee_log("New unknown connection!");
    }
  }

  /* lock the connection mutex */
  xbee_mutex_lock(xbee->conmutex);
  
  /* make it the last in the list */
  con->next = NULL;
  /* add it to the list */
  if (xbee->conlist) {
    ocon->next = con;
  } else {
    xbee->conlist = con;
  }

  /* unlock the mutex */
  xbee_mutex_unlock(xbee->conmutex);
  return con;
}

/* #################################################################
   xbee_conflush
   removes any packets that have been collected for the specified
   connection */
void xbee_purgecon(xbee_con *con) {
  _xbee_purgecon(default_xbee, con);
}
void _xbee_purgecon(xbee_hnd xbee, xbee_con *con) {
  xbee_pkt *r, *p, *n;

  ISREADYP();
  
  /* lock the packet mutex */
  xbee_mutex_lock(xbee->pktmutex);

  /* if: there are packets */
  if ((p = xbee->pktlist) != NULL) {
    r = NULL;
    /* get all packets for this connection */
    do {
      /* does the packet match the connection? */
      if (xbee_matchpktcon(xbee,p,con)) {
        /* if it was the first packet */
        if (!r) {
          /* move the chain along */
          xbee->pktlist = p->next;
        } else {
          /* otherwise relink the list */
          r->next = p->next;
        }
        xbee->pktcount--;

        /* free this packet! */
        n = p->next;
        Xfree(p);
        /* move on */
        p = n;
      } else {
        /* move on */
        r = p;
        p = p->next;
      }
    } while (p);
    xbee->pktlast = r;
  }

  /* unlock the packet mutex */
  xbee_mutex_unlock(xbee->pktmutex);
}

/* #################################################################
   xbee_endcon
   close the unwanted connection
   free wrapper function (uses the Xfree macro and sets the pointer to NULL after freeing it) */
void xbee_endcon2(xbee_con **con, int alreadyUnlinked) {
  _xbee_endcon2(default_xbee, con, alreadyUnlinked);
}
void _xbee_endcon2(xbee_hnd xbee, xbee_con **con, int alreadyUnlinked) {
  xbee_con *t, *u;

  ISREADYP();
  
  /* lock the connection mutex */
  xbee_mutex_lock(xbee->conmutex);

  u = t = xbee->conlist;
  while (t && t != *con) {
    u = t;
    t = t->next;
  }
  if (!t) {
    /* this could be true if comming from the destroySelf signal... */
    if (!alreadyUnlinked) {
      /* invalid connection given... */
      if (xbee->log) {
        xbee_log("Attempted to close invalid connection...");
      }
      /* unlock the connection mutex */
      xbee_mutex_unlock(xbee->conmutex);
      return;
    }
  } else {
    /* extract this connection from the list */
    if (t == xbee->conlist) {
      xbee->conlist = t->next;
    } else {
      u->next = t->next;
    }
  }
  
  /* unlock the connection mutex */
  xbee_mutex_unlock(xbee->conmutex);

  /* check if a callback thread is running... */
  if (t->callback && xbee_mutex_trylock(t->callbackmutex)) {
    /* if it is running... tell it to destroy the connection on completion */
    xbee_log("Attempted to close a connection with active callbacks... "
             "Connection will be destroyed when callbacks have completeted...");
    t->destroySelf = 1;
    return;
  }

  /* remove all packets for this connection */
  _xbee_purgecon(xbee,t);

  /* destroy the callback mutex */
  xbee_mutex_destroy(t->callbackmutex);
  xbee_mutex_destroy(t->callbackListmutex);
  xbee_mutex_destroy(t->Txmutex);
  xbee_sem_destroy(t->waitforACKsem);

  /* free the connection! */
  Xfree(*con);
}

/* #################################################################
   xbee_senddata
   send the specified data to the provided connection */
int xbee_senddata(xbee_con *con, char *format, ...) {
  int ret;
  va_list ap;

  /* xbee_vsenddata() wants a va_list... */
  va_start(ap, format);
  /* hand it over :) */
  ret = _xbee_vsenddata(default_xbee, con, format, ap);
  va_end(ap);
  return ret;
}
int _xbee_senddata(xbee_hnd xbee, xbee_con *con, char *format, ...) {
  int ret;
  va_list ap;

  /* xbee_vsenddata() wants a va_list... */
  va_start(ap, format);
  /* hand it over :) */
  ret = _xbee_vsenddata(xbee, con, format, ap);
  va_end(ap);
  return ret;
}

int xbee_vsenddata(xbee_con *con, char *format, va_list ap) {
  return _xbee_vsenddata(default_xbee, con, format, ap);
}
int _xbee_vsenddata(xbee_hnd xbee, xbee_con *con, char *format, va_list ap) {
  unsigned char data[128]; /* max payload is 100 bytes... plus a bit of fluff... */
  int length;

  /* make up the data and keep the length, its possible there are nulls in there */
  length = vsnprintf((char *)data, 128, format, ap);

  /* hand it over :) */
  return _xbee_nsenddata(xbee, con, (char *)data, length);
}