/***************************************************************
 *
 * OpenBeacon.org - dirty OnAir protocol - to textfile decoder
 * accepts a concatenaded set of binary 24C3 sputnik logs. 
 *
 * ---> for internal use only <---
 *
 *
 * See the following website for already decoded Sputnik data:
 * http://people.openpcd.org/meri/openbeacon/sputnik/data/24c3/
 *
 * Copyright 2006 Milosch Meriac <meriac@openbeacon.de>
 *
/***************************************************************

/*
    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; version 2.

    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, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

*/

#include <stdio.h>
#include <unistd.h>
#include <netinet/in.h>

typedef struct
{
  u_int32_t timestamp;
  u_int32_t ip;
  u_int8_t size, proto;
  u_int8_t flags, strength;
  u_int32_t seq;
  u_int32_t oid;
  u_int16_t reserved;
  u_int16_t crc;
} __attribute__((__packed__)) TBeaconTracker;

unsigned short crc16 (const void *buf, int size)
{
    unsigned short crc = 0xFFFF;
    const unsigned char *buffer = (const unsigned char *)buf;

    if(buffer && size)
        while (size--)
        {
            crc = (crc >> 8) | (crc << 8);
            crc ^= *buffer++;
            crc ^= ((unsigned char) crc) >> 4;
            crc ^= crc << 12;
            crc ^= (crc & 0xFF) << 5;
        }

    return crc;
}

int main(void)
{
    int res,f;
    TBeaconTracker item;
    
    f=open("sputnik.bin",0);
    
    res=0;
    while(read(f,&item,sizeof(item))==sizeof(item))
    {
	if(ntohs(item.crc)!=crc16(&item.size,sizeof(item)-sizeof(item.crc)-sizeof(item.timestamp)-sizeof(item.ip)))
	{
	    printf("\nCRC broken.");
	    res=1;
	    break;
	}	
	
	item.ip = ntohl(item.ip);
    	item.seq = ntohl(item.seq);
	item.strength = item.strength/0x55;
	
	printf("%u %u %c%03u %u %010u %c\n",
	    ntohl(item.oid),
	    ntohl(item.timestamp),
	    (char)(((item.ip >> 8)&0x1F)+'A'),
	    (unsigned int)(item.ip & 0xFF),
	    (unsigned int)(item.strength),
	    (unsigned int)item.seq,
	    (item.flags & 0x2)?'1':'0');
    }    
    
    close(f);
    
    return res;
}

