laforge
/
openbts-osmo
Archived
1
0
Fork 0

transceiver: remove old resampling transceiver

This commit is contained in:
Thomas Tsou 2011-10-05 22:11:19 -04:00
parent 1898c37e43
commit 4fcc2bd352
20 changed files with 0 additions and 5726 deletions

View File

@ -31,7 +31,6 @@ SUBDIRS = \
SIP \
GSM \
SMS \
Transceiver \
Transceiver52M \
TRXManager \
Control \

View File

@ -1,277 +0,0 @@
/**@file templates for Complex classes
unlike the built-in complex<> templates, these inline most operations for speed
*/
/*
* Copyright 2008 Free Software Foundation, Inc.
*
* This software is distributed under the terms of the GNU Affero Public License.
* See the COPYING file in the main directory for details.
*
* This use of this software may be subject to additional restrictions.
* See the LEGAL file in the main directory for details.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef COMPLEXCPP_H
#define COMPLEXCPP_H
#include <math.h>
#include <ostream>
template<class Real> class Complex {
public:
Real r, i;
/**@name constructors */
//@{
/**@name from real */
//@{
Complex(Real real, Real imag) {r=real; i=imag;} // x=complex(a,b)
Complex(Real real) {r=real; i=0;} // x=complex(a)
//@}
/**@name from nothing */
//@{
Complex() {r=(Real)0; i=(Real)0;} // x=complex()
//@}
/**@name from other complex */
//@{
Complex(const Complex<float>& z) {r=z.r; i=z.i;} // x=complex(z)
Complex(const Complex<double>& z) {r=z.r; i=z.i;} // x=complex(z)
Complex(const Complex<long double>& z) {r=z.r; i=z.i;} // x=complex(z)
//@}
//@}
/**@name casting up from basic numeric types */
//@{
Complex& operator=(char a) { r=(Real)a; i=(Real)0; return *this; }
Complex& operator=(int a) { r=(Real)a; i=(Real)0; return *this; }
Complex& operator=(long int a) { r=(Real)a; i=(Real)0; return *this; }
Complex& operator=(short a) { r=(Real)a; i=(Real)0; return *this; }
Complex& operator=(float a) { r=(Real)a; i=(Real)0; return *this; }
Complex& operator=(double a) { r=(Real)a; i=(Real)0; return *this; }
Complex& operator=(long double a) { r=(Real)a; i=(Real)0; return *this; }
//@}
/**@name arithmetic */
//@{
/**@ binary operators */
//@{
Complex operator+(const Complex<Real>& a) const { return Complex<Real>(r+a.r, i+a.i); }
Complex operator+(Real a) const { return Complex<Real>(r+a,i); }
Complex operator-(const Complex<Real>& a) const { return Complex<Real>(r-a.r, i-a.i); }
Complex operator-(Real a) const { return Complex<Real>(r-a,i); }
Complex operator*(const Complex<Real>& a) const { return Complex<Real>(r*a.r-i*a.i, r*a.i+i*a.r); }
Complex operator*(Real a) const { return Complex<Real>(r*a, i*a); }
Complex operator/(const Complex<Real>& a) const { return operator*(a.inv()); }
Complex operator/(Real a) const { return Complex<Real>(r/a, i/a); }
//@}
/*@name component-wise product */
//@{
Complex operator&(const Complex<Real>& a) const { return Complex<Real>(r*a.r, i*a.i); }
//@}
/*@name inplace operations */
//@{
Complex& operator+=(const Complex<Real>&);
Complex& operator-=(const Complex<Real>&);
Complex& operator*=(const Complex<Real>&);
Complex& operator/=(const Complex<Real>&);
Complex& operator+=(Real);
Complex& operator-=(Real);
Complex& operator*=(Real);
Complex& operator/=(Real);
//@}
//@}
/**@name comparisons */
//@{
bool operator==(const Complex<Real>& a) const { return ((i==a.i)&&(r==a.r)); }
bool operator!=(const Complex<Real>& a) const { return ((i!=a.i)||(r!=a.r)); }
bool operator<(const Complex<Real>& a) const { return norm2()<a.norm2(); }
bool operator>(const Complex<Real>& a) const { return norm2()>a.norm2(); }
//@}
/// reciprocation
Complex inv() const;
// unary functions -- inlined
/**@name unary functions */
//@{
/**@name inlined */
//@{
Complex conj() const { return Complex<Real>(r,-i); }
Real norm2() const { return i*i+r*r; }
Complex flip() const { return Complex<Real>(i,r); }
Real real() const { return r;}
Real imag() const { return i;}
Complex neg() const { return Complex<Real>(-r, -i); }
bool isZero() const { return ((r==(Real)0) && (i==(Real)0)); }
//@}
/**@name not inlined due to outside calls */
//@{
Real abs() const { return ::sqrt(norm2()); }
Real arg() const { return ::atan2(i,r); }
float dB() const { return 10.0*log10(norm2()); }
Complex exp() const { return expj(i)*(::exp(r)); }
Complex unit() const; ///< unit phasor with same angle
Complex log() const { return Complex(::log(abs()),arg()); }
Complex pow(double n) const { return expj(arg()*n)*(::pow(abs(),n)); }
Complex sqrt() const { return pow(0.5); }
//@}
//@}
};
/**@name standard Complex manifestations */
//@{
typedef Complex<float> complex;
typedef Complex<double> dcomplex;
typedef Complex<short> complex16;
typedef Complex<long> complex32;
//@}
template<class Real> inline Complex<Real> Complex<Real>::inv() const
{
Real nVal;
nVal = norm2();
return Complex<Real>(r/nVal, -i/nVal);
}
template<class Real> Complex<Real>& Complex<Real>::operator+=(const Complex<Real>& a)
{
r += a.r;
i += a.i;
return *this;
}
template<class Real> Complex<Real>& Complex<Real>::operator*=(const Complex<Real>& a)
{
operator*(a);
return *this;
}
template<class Real> Complex<Real>& Complex<Real>::operator-=(const Complex<Real>& a)
{
r -= a.r;
i -= a.i;
return *this;
}
template<class Real> Complex<Real>& Complex<Real>::operator/=(const Complex<Real>& a)
{
operator/(a);
return *this;
}
/* op= style operations with reals */
template<class Real> Complex<Real>& Complex<Real>::operator+=(Real a)
{
r += a;
return *this;
}
template<class Real> Complex<Real>& Complex<Real>::operator*=(Real a)
{
r *=a;
i *=a;
return *this;
}
template<class Real> Complex<Real>& Complex<Real>::operator-=(Real a)
{
r -= a;
return *this;
}
template<class Real> Complex<Real>& Complex<Real>::operator/=(Real a)
{
r /= a;
i /= a;
return *this;
}
template<class Real> Complex<Real> Complex<Real>::unit() const
{
Real absVal = abs();
return (Complex<Real>(r/absVal, i/absVal));
}
/**@name complex functions outside of the Complex<> class. */
//@{
/** this allows type-commutative multiplication */
template<class Real> Complex<Real> operator*(Real a, const Complex<Real>& z)
{
return Complex<Real>(z.r*a, z.i*a);
}
/** this allows type-commutative addition */
template<class Real> Complex<Real> operator+(Real a, const Complex<Real>& z)
{
return Complex<Real>(z.r+a, z.i);
}
/** this allows type-commutative subtraction */
template<class Real> Complex<Real> operator-(Real a, const Complex<Real>& z)
{
return Complex<Real>(z.r-a, z.i);
}
/// e^jphi
template<class Real> Complex<Real> expj(Real phi)
{
return Complex<Real>(cos(phi),sin(phi));
}
/// phasor expression of a complex number
template<class Real> Complex<Real> phasor(Real C, Real phi)
{
return (expj(phi)*C);
}
/// formatted stream output
template<class Real> std::ostream& operator<<(std::ostream& os, const Complex<Real>& z)
{
os << z.r << ' ';
//os << z.r << ", ";
//if (z.i>=0) { os << "+"; }
os << z.i << "j";
os << "\n";
return os;
}
//@}
#endif

View File

@ -1,88 +0,0 @@
#
# Copyright 2008 Free Software Foundation, Inc.
#
# This software is distributed under the terms of the GNU Affero Public License.
# See the COPYING file in the main directory for details.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
include $(top_srcdir)/Makefile.common
if UHD
AM_CPPFLAGS = $(STD_DEFINES_AND_INCLUDES) $(UHD_CFLAGS)
else
AM_CPPFLAGS = $(STD_DEFINES_AND_INCLUDES) $(USRP_CFLAGS)
endif
AM_CXXFLAGS = -Wall -O3 -g -pthread
rev2dir = $(datadir)/usrp/rev2
rev4dir = $(datadir)/usrp/rev4
dist_rev2_DATA = std_inband.rbf
dist_rev4_DATA = std_inband.rbf
EXTRA_DIST = \
README \
README.Talgorithm
noinst_LTLIBRARIES = libtransceiver.la
libtransceiver_la_SOURCES = \
radioInterface.cpp \
sigProcLib.cpp \
Transceiver.cpp
noinst_PROGRAMS = \
USRPping \
transceiver
noinst_HEADERS = \
Complex.h \
radioInterface.h \
rcvLPF_651.h \
sendLPF_961.h \
sigProcLib.h \
Transceiver.h \
USRPDevice.h
USRPping_SOURCES = USRPping.cpp
USRPping_LDADD = \
libtransceiver.la \
$(COMMON_LA)
transceiver_SOURCES = runTransceiver.cpp
transceiver_LDADD = \
libtransceiver.la \
$(GSM_LA) \
$(COMMON_LA)
if UHD
libtransceiver_la_SOURCES += UHDDevice.cpp
transceiver_LDADD += $(UHD_LIBS)
USRPping_LDADD += $(UHD_LIBS)
else
libtransceiver_la_SOURCES += USRPDevice.cpp
transceiver_LDADD += $(USRP_LIBS)
USRPping_LDADD += $(USRP_LIBS)
endif
MOSTLYCLEANFILES +=
#radioInterface.cpp
#ComplexTest.cpp
#sigProcLibTest.cpp
#sweepGenerator.cpp
#testRadio.cpp

View File

@ -1,39 +0,0 @@
The Transceiver
The transceiver consists of three modules:
--- transceiver
--- radioInterface
--- USRPDevice
The USRPDevice module is basically a driver that reads/writes
packets to a USRP with two RFX900 daughterboards, board
A is the Tx chain and board B is the Rx chain.
The radioInterface module is basically an interface b/w the
transceiver and the USRP. It operates the basestation clock
based upon the sample count of received USRP samples. Packets
from the USRP are queued and segmented into GSM bursts that are
passed up to the transceiver; bursts from the transceiver are
passed down to the USRP. Our current implementation includes
a polyphase resampler, since there is no 64e6/N sample rate that
nicely matches a multiple of the GSM symbol rate of 1.625e6/6.
A better implementation would involve running the USRP off of a
13Mhz clock; then the resampler can be discarded altogether.
The transceiver basically operates "layer 0" of the GSM stack,
performing the modulation, detection, and demodulation of GSM
bursts. It communicates with the GSM stack via three UDP sockets,
one socket for data, one for control messages, and one socket to
pass clocking information. The transceiver contains a priority
queue to sort to-be-transmitted bursts, and a filler table to fill
in timeslots that do not have bursts in the priority queue. The
transceiver tries to stay ahead of the basestation clock, adapting
its latency when underruns are reported by the radioInterface/USRP.
Received bursts (from the radioInterface) pass through a simple
energy detector, a RACH or midamble correlator, and a DFE-based demodulator.
NOTE: There's a SWLOOPBACK #define statement, where the USRP is replaced
with a memory buffer. In this mode, data written to the USRP is actually stored
in a buffer, and read commands to the USRP simply pull data from this buffer.
This was very useful in early testing, and still may be useful in testing basic
Transceiver and radioInterface functionality.

View File

@ -1,15 +0,0 @@
Basic model:
Have channel H = {h_0, h_1, ..., h_{K-1}}.
Have received sequence Y = {y_0, ..., y_{K+N}}.
Have transmitted sequence X = {x_0, ..., x_{N-1}}.
Denote state S_n = {x_n, x_{n-1}, ..., x_{n-L}}.
Define a bag as an unordered collection with two operations, add and take.
We have three bags:
S: a bag of survivors.
F: a bag of available data structures.
At time n, start with a non-empty bag S of survivors from time n-1.
Take a member out of S, and create all possible branches and their corresponding metrics. If metric ratio is above T, discard branch. Otherwise, check branch against entry in pruning table P. If branch metric is smaller than the existing entry's metric in P, then replace entry with branch. Otherwise, discard branch.
Once all possible branches of S have been created and pruned, S should be empty.Empty pruning table back into S, thus P is now empty. Repeat.

View File

@ -1,814 +0,0 @@
/*
* Copyright 2008, 2009 Free Software Foundation, Inc.
*
* This software is distributed under the terms of the GNU Affero Public License.
* See the COPYING file in the main directory for details.
*
* This use of this software may be subject to additional restrictions.
* See the LEGAL file in the main directory for details.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
Compilation switches
TRANSMIT_LOGGING write every burst on the given slot to a log
*/
#include "config.h"
#include "Transceiver.h"
#include <Logger.h>
#include <cstdio>
Transceiver::Transceiver(int wBasePort,
const char *TRXAddress,
int wSamplesPerSymbol,
GSM::Time wTransmitLatency,
RadioInterface *wRadioInterface)
:mDataSocket(wBasePort+2,TRXAddress,wBasePort+102),
mControlSocket(wBasePort+1,TRXAddress,wBasePort+101),
mClockSocket(wBasePort,TRXAddress,wBasePort+100)
{
//GSM::Time startTime(0,0);
//GSM::Time startTime(gHyperframe/2 - 4*216*60,0);
GSM::Time startTime(random() % gHyperframe,0);
mSamplesPerSymbol = wSamplesPerSymbol;
mRadioInterface = wRadioInterface;
mTransmitLatency = wTransmitLatency;
mTransmitDeadlineClock = startTime;
mLastClockUpdateTime = startTime;
mLatencyUpdateTime = startTime;
mRadioInterface->getClock()->set(startTime);
// generate pulse and setup up signal processing library
gsmPulse = generateGSMPulse(2,mSamplesPerSymbol);
LOG(DEBUG) << "gsmPulse: " << *gsmPulse;
sigProcLibSetup(mSamplesPerSymbol);
txFullScale = mRadioInterface->fullScaleInputValue();
rxFullScale = mRadioInterface->fullScaleOutputValue();
// initialize filler tables with dummy bursts, initialize other per-timeslot variables
for (int i = 0; i < 8; i++) {
signalVector* modBurst = modulateBurst(gDummyBurst,*gsmPulse,
8 + (i % 4 == 0),
mSamplesPerSymbol);
//if (i!=0) scaleVector(*modBurst,0.0001);
fillerModulus[i]=26;
for (int j = 0; j < 102; j++) {
fillerTable[j][i] = new signalVector(*modBurst);
}
delete modBurst;
mChanType[i] = NONE;
channelResponse[i] = NULL;
DFEForward[i] = NULL;
DFEFeedback[i] = NULL;
channelEstimateTime[i] = startTime;
}
mOn = false;
mTxFreq = 0.0;
mRxFreq = 0.0;
mPower = -10;
mEnergyThreshold = 250.0; // based on empirical data
prevFalseDetectionTime = startTime;
}
Transceiver::~Transceiver()
{
delete gsmPulse;
sigProcLibDestroy();
mTransmitPriorityQueue.clear();
}
void Transceiver::addRadioVector(BitVector &burst,
int RSSI,
GSM::Time &wTime)
{
// modulate and stick into queue
signalVector* modBurst = modulateBurst(burst,*gsmPulse,
8 + (wTime.TN() % 4 == 0),
mSamplesPerSymbol);
scaleVector(*modBurst,pow(10,-RSSI/10));
radioVector *newVec = new radioVector(*modBurst,wTime);
mTransmitPriorityQueue.write(newVec);
delete modBurst;
}
#ifdef TRANSMIT_LOGGING
void Transceiver::unModulateVector(signalVector wVector)
{
SoftVector *burst = demodulateBurst(wVector,
*gsmPulse,
mSamplesPerSymbol,
1.0,0.0);
LOG(DEEPDEBUG) << "LOGGED BURST: " << *burst;
/*
unsigned char burstStr[gSlotLen+1];
SoftVector::iterator burstItr = burst->begin();
for (int i = 0; i < gSlotLen; i++) {
// FIXME: Demod bits are inverted!
burstStr[i] = (unsigned char) ((*burstItr++)*255.0);
}
burstStr[gSlotLen]='\0';
LOG(DEEPDEBUG) << "LOGGED BURST: " << burstStr;
*/
delete burst;
}
#endif
void Transceiver::pushRadioVector(GSM::Time &nowTime)
{
// dump stale bursts, if any
while ((mTransmitPriorityQueue.size() > 0) &&
(mTransmitPriorityQueue.nextTime() < nowTime)) {
// Even if the burst is stale, put it in the fillter table.
// (It might be an idle pattern.)
LOG(NOTICE) << "dumping STALE burst in TRX->USRP interface";
const GSM::Time& nextTime = mTransmitPriorityQueue.nextTime();
int TN = nextTime.TN();
int modFN = nextTime.FN() % fillerModulus[TN];
delete fillerTable[modFN][TN];
fillerTable[modFN][TN] = mTransmitPriorityQueue.readNoBlock();
}
int TN = nowTime.TN();
int modFN = nowTime.FN() % fillerModulus[nowTime.TN()];
// if queue contains data at the desired timestamp, stick it into FIFO
if ((mTransmitPriorityQueue.size() > 0) &&
(mTransmitPriorityQueue.nextTime() == nowTime)) {
radioVector *next = mTransmitPriorityQueue.readNoBlock();
LOG(DEEPDEBUG) << "transmitFIFO: wrote burst " << next << " at time: " << nowTime;
delete fillerTable[modFN][TN];
fillerTable[modFN][TN] = new signalVector(*(next));
mTransmitFIFO->write(next);
#ifdef TRANSMIT_LOGGING
if (nowTime.TN()==TRANSMIT_LOGGING) {
unModulateVector(*(fillerTable[modFN][TN]));
}
#endif
return;
}
// otherwise, pull filler data, and push to radio FIFO
radioVector *tmpVec = new radioVector(*fillerTable[modFN][TN],nowTime);
mTransmitFIFO->write(tmpVec);
#ifdef TRANSMIT_LOGGING
if (nowTime.TN()==TRANSMIT_LOGGING)
unModulateVector(*fillerTable[modFN][TN]);
#endif
}
void Transceiver::setModulus(int timeslot)
{
switch (mChanType[timeslot]) {
case NONE:
case I:
case II:
case III:
fillerModulus[timeslot] = 26;
break;
case IV:
case VI:
case V:
fillerModulus[timeslot] = 51;
break;
//case V:
case VII:
fillerModulus[timeslot] = 102;
break;
default:
break;
}
}
Transceiver::CorrType Transceiver::expectedCorrType(GSM::Time currTime)
{
unsigned burstTN = currTime.TN();
unsigned burstFN = currTime.FN();
switch (mChanType[burstTN]) {
case NONE:
return OFF;
break;
case I:
return TSC;
/*if (burstFN % 26 == 25)
return IDLE;
else
return TSC;*/
break;
case II:
if (burstFN % 2 == 1)
return IDLE;
else
return TSC;
break;
case III:
return TSC;
break;
case IV:
case VI:
if ((burstFN % 51) % 10 < 2)
return RACH;
else
return OFF;
break;
case V: {
int mod51 = burstFN % 51;
if ((mod51 <= 36) && (mod51 >= 14))
return RACH;
else if ((mod51 == 4) || (mod51 == 5))
return RACH;
else if ((mod51 == 45) || (mod51 == 46))
return RACH;
else
return TSC;
break;
}
case VII:
if (burstFN%51 == 12) return IDLE;
if (burstFN%51 == 13) return IDLE;
if (burstFN%51 == 14) return IDLE;
return TSC;
break;
case LOOPBACK:
if ((burstFN % 51 <= 50) && (burstFN % 51 >=48))
return IDLE;
else
return TSC;
break;
default:
return OFF;
break;
}
}
SoftVector *Transceiver::pullRadioVector(GSM::Time &wTime,
int &RSSI,
int &timingOffset)
{
radioVector *rxBurst = NULL;
rxBurst = mReceiveFIFO->read();
if (!rxBurst) return NULL;
LOG(DEEPDEBUG) << "receiveFIFO: read radio vector at time: " << rxBurst->time() << ", new size: " << mReceiveFIFO->size();
// receive chain is offset from transmit chain
rxBurst->time(rxBurst->time());
int timeslot = rxBurst->time().TN();
CorrType corrType = expectedCorrType(rxBurst->time());
if ((corrType==OFF) || (corrType==IDLE)) {
delete rxBurst;
return NULL;
}
// check to see if received burst has sufficient energy
signalVector *vectorBurst = rxBurst;
complex amplitude = 0.0;
float TOA = 0.0;
float avgPwr = 0.0;
if (!energyDetect(*vectorBurst,20*mSamplesPerSymbol,mEnergyThreshold,&avgPwr)) {
LOG(DEEPDEBUG) << "Estimated Energy: " << sqrt(avgPwr) << ", at time " << rxBurst->time();
double framesElapsed = rxBurst->time()-prevFalseDetectionTime;
if (framesElapsed > 50) { // if we haven't had any false detections for a while, lower threshold
mEnergyThreshold -= 10.0;
if (mEnergyThreshold < 0.0)
mEnergyThreshold = 0.0;
prevFalseDetectionTime = rxBurst->time();
}
delete rxBurst;
return NULL;
}
LOG(DEEPDEBUG) << "Estimated Energy: " << sqrt(avgPwr) << ", at time " << rxBurst->time();
// run the proper correlator
bool success = false;
if (corrType==TSC) {
LOG(DEEPDEBUG) << "looking for TSC at time: " << rxBurst->time();
signalVector *channelResp;
double framesElapsed = rxBurst->time()-channelEstimateTime[timeslot];
bool estimateChannel = false;
if ((framesElapsed > 50) || (channelResponse[timeslot]==NULL)) {
if (channelResponse[timeslot]) delete channelResponse[timeslot];
if (DFEForward[timeslot]) delete DFEForward[timeslot];
if (DFEFeedback[timeslot]) delete DFEFeedback[timeslot];
channelResponse[timeslot] = NULL;
DFEForward[timeslot] = NULL;
DFEFeedback[timeslot] = NULL;
estimateChannel = true;
}
float chanOffset;
success = analyzeTrafficBurst(*vectorBurst,
mTSC,
3.0,
mSamplesPerSymbol,
&amplitude,
&TOA, //);
estimateChannel,
&channelResp,
&chanOffset);
if (success) {
LOG(DEBUG) << "FOUND TSC!!!!!! " << amplitude << " " << TOA;
mEnergyThreshold -= 1.0F;
if (mEnergyThreshold < 0.0) mEnergyThreshold = 0.0;
SNRestimate[timeslot] = amplitude.norm2()/(mEnergyThreshold*mEnergyThreshold+1.0); // this is not highly accurate
if (estimateChannel) {
LOG(DEBUG) << "estimating channel...";
channelResponse[timeslot] = channelResp;
chanRespOffset[timeslot] = chanOffset;
chanRespAmplitude[timeslot] = amplitude;
scaleVector(*channelResp, complex(1.0,0.0)/amplitude);
designDFE(*channelResp, SNRestimate[timeslot], 7, &DFEForward[timeslot], &DFEFeedback[timeslot]);
channelEstimateTime[timeslot] = rxBurst->time();
LOG(DEBUG) << "SNR: " << SNRestimate[timeslot] << ", DFE forward: " << *DFEForward[timeslot] << ", DFE backward: " << *DFEFeedback[timeslot];
}
}
else {
double framesElapsed = rxBurst->time()-prevFalseDetectionTime;
LOG(DEEPDEBUG) << "wTime: " << rxBurst->time() << ", pTime: " << prevFalseDetectionTime << ", fElapsed: " << framesElapsed;
mEnergyThreshold += 10.0F*exp(-framesElapsed);
prevFalseDetectionTime = rxBurst->time();
channelResponse[timeslot] = NULL;
}
}
else {
// RACH burst
success = detectRACHBurst(*vectorBurst,
5.0, // detection threshold
mSamplesPerSymbol,
&amplitude,
&TOA);
if (success) {
LOG(DEBUG) << "FOUND RACH!!!!!! " << amplitude << " " << TOA;
mEnergyThreshold -= 1.0F;
if (mEnergyThreshold < 0.0) mEnergyThreshold = 0.0;
channelResponse[timeslot] = NULL;
}
else {
double framesElapsed = rxBurst->time()-prevFalseDetectionTime;
mEnergyThreshold += 10.0F*exp(-framesElapsed);
prevFalseDetectionTime = rxBurst->time();
}
}
LOG(DEBUG) << "energy Threshold = " << mEnergyThreshold;
// demodulate burst
SoftVector *burst = NULL;
if ((rxBurst) && (success)) {
if (corrType==RACH) {
burst = demodulateBurst(*vectorBurst,
*gsmPulse,
mSamplesPerSymbol,
amplitude,TOA);
}
else { // TSC
scaleVector(*vectorBurst,complex(1.0,0.0)/amplitude);
burst = equalizeBurst(*vectorBurst,
TOA-chanRespOffset[timeslot],
mSamplesPerSymbol,
*DFEForward[timeslot],
*DFEFeedback[timeslot]);
}
wTime = rxBurst->time();
RSSI = (int) floor(20.0*log10(rxFullScale/amplitude.abs()));
LOG(DEBUG) << "RSSI: " << RSSI;
timingOffset = (int) round(TOA*256.0/mSamplesPerSymbol);
}
//if (burst) LOG(DEEPDEBUG) << "burst: " << *burst << '\n';
delete rxBurst;
return burst;
}
void Transceiver::start()
{
mReceiveFIFOServiceLoopThread.start((void * (*)(void*))ReceiveFIFOServiceLoopAdapter,(void*) this);
mTransmitFIFOServiceLoopThread.start((void * (*)(void*))TransmitFIFOServiceLoopAdapter,(void*) this);
mControlServiceLoopThread.start((void * (*)(void*))ControlServiceLoopAdapter,(void*) this);
mTransmitPriorityQueueServiceLoopThread.start((void * (*)(void*))TransmitPriorityQueueServiceLoopAdapter,(void*) this);
mLock.unlock();
writeClockInterface();
generateRACHSequence(*gsmPulse,mSamplesPerSymbol);
}
void Transceiver::reset()
{
mLock.lock();
mTransmitPriorityQueue.clear();
mTransmitFIFO->clear();
mReceiveFIFO->clear();
mLock.unlock();
}
void Transceiver::driveControl()
{
mLock.lock();
int MAX_PACKET_LENGTH = 100;
// check control socket
char buffer[MAX_PACKET_LENGTH];
int msgLen = -1;
buffer[0] = '\0';
msgLen = mControlSocket.read(buffer);
if (msgLen < 1) {
mLock.unlock();
return;
}
char cmdcheck[4];
char command[MAX_PACKET_LENGTH];
char response[MAX_PACKET_LENGTH];
sscanf(buffer,"%3s %s",cmdcheck,command);
writeClockInterface();
if (strcmp(cmdcheck,"CMD")!=0) {
LOG(WARN) << "bogus message on control interface";
mLock.unlock();
return;
}
LOG(INFO) << "command is " << buffer;
if (strcmp(command,"POWEROFF")==0) {
// turn off transmitter/demod
sprintf(response,"RSP POWEROFF 0");
}
else if (strcmp(command,"POWERON")==0) {
// turn on transmitter/demod
if (!mTxFreq || !mRxFreq)
sprintf(response,"RSP POWERON 1");
else {
sprintf(response,"RSP POWERON 0");
if (!mOn) {
mPower = -20;
mRadioInterface->start();
mOn = true;
}
}
}
else if (strcmp(command,"SETRXGAIN")==0) {
//set expected maximum time-of-arrival
int newGain;
sscanf(buffer,"%3s %s %d",cmdcheck,command,&newGain);
newGain = mRadioInterface->setRxGain(newGain);
sprintf(response,"RSP SETRXGAIN 0 %d",newGain);
}
else if (strcmp(command,"NOISELEV")==0) {
if (mOn) {
sprintf(response,"RSP NOISELEV 0 %d",
(int) round(20.0*log10(rxFullScale/mEnergyThreshold)));
}
else {
sprintf(response,"RSP NOISELEV 1 0");
}
}
else if (strcmp(command,"SETPOWER")==0) {
// set output power in dB
int dbPwr;
sscanf(buffer,"%3s %s %d",cmdcheck,command,&dbPwr);
if (!mOn)
sprintf(response,"RSP SETPOWER 1 %d",dbPwr);
else {
mPower = dbPwr;
mRadioInterface->setPowerAttenuation(dbPwr);
sprintf(response,"RSP SETPOWER 0 %d",dbPwr);
}
}
else if (strcmp(command,"ADJPOWER")==0) {
// adjust power in dB steps
int dbStep;
sscanf(buffer,"%3s %s %d",cmdcheck,command,&dbStep);
if (!mOn)
sprintf(response,"RSP ADJPOWER 1 %d",mPower);
else {
mPower += dbStep;
sprintf(response,"RSP ADJPOWER 0 %d",mPower);
}
}
#define FREQOFFSET 0//11.2e3
else if (strcmp(command,"RXTUNE")==0) {
// tune receiver
int freqKhz;
sscanf(buffer,"%3s %s %d",cmdcheck,command,&freqKhz);
if (mOn)
sprintf(response,"RSP RXTUNE 1 %d",freqKhz);
else {
mRxFreq = freqKhz*1.0e3+FREQOFFSET;
if (!mRadioInterface->tuneRx(mRxFreq)) {
LOG(ALARM) << "RX failed to tune";
sprintf(response,"RSP RXTUNE 1 %d",freqKhz);
}
else
sprintf(response,"RSP RXTUNE 0 %d",freqKhz);
}
}
else if (strcmp(command,"TXTUNE")==0) {
// tune txmtr
int freqKhz;
sscanf(buffer,"%3s %s %d",cmdcheck,command,&freqKhz);
if (mOn)
sprintf(response,"RSP TXTUNE 1 %d",freqKhz);
else {
//freqKhz = 890e3;
mTxFreq = freqKhz*1.0e3+FREQOFFSET;
if (!mRadioInterface->tuneTx(mTxFreq)) {
LOG(ALARM) << "TX failed to tune";
sprintf(response,"RSP TXTUNE 1 %d",freqKhz);
}
else
sprintf(response,"RSP TXTUNE 0 %d",freqKhz);
}
}
else if (strcmp(command,"SETTSC")==0) {
// set TSC
int TSC;
sscanf(buffer,"%3s %s %d",cmdcheck,command,&TSC);
if (mOn)
sprintf(response,"RSP SETTSC 1 %d",TSC);
else {
mTSC = TSC;
generateMidamble(*gsmPulse,mSamplesPerSymbol,TSC);
sprintf(response,"RSP SETTSC 0 %d",TSC);
}
}
else if (strcmp(command,"SETSLOT")==0) {
// set TSC
int corrCode;
int timeslot;
sscanf(buffer,"%3s %s %d %d",cmdcheck,command,&timeslot,&corrCode);
if ((timeslot < 0) || (timeslot > 7)) {
LOG(WARN) << "bogus message on control interface";
sprintf(response,"RSP SETSLOT 1 %d %d",timeslot,corrCode);
mLock.unlock();
return;
}
mChanType[timeslot] = (ChannelCombination) corrCode;
setModulus(timeslot);
sprintf(response,"RSP SETSLOT 0 %d %d",timeslot,corrCode);
}
else {
LOG(WARN) << "bogus command " << command << " on control interface.";
}
mControlSocket.write(response,strlen(response)+1);
mLock.unlock();
}
bool Transceiver::driveTransmitPriorityQueue()
{
char buffer[gSlotLen+50];
// check data socket
size_t msgLen = mDataSocket.read(buffer);
if (msgLen!=gSlotLen+1+4+1) {
LOG(ERROR) << "badly formatted packet on GSM->TRX interface";
return false;
}
int timeSlot = (int) buffer[0];
uint64_t frameNum = 0;
for (int i = 0; i < 4; i++)
frameNum = (frameNum << 8) | (0x0ff & buffer[i+1]);
/*
if (GSM::Time(frameNum,timeSlot) > mTransmitDeadlineClock + GSM::Time(51,0)) {
// stale burst
//LOG(DEBUG) << "FAST! "<< GSM::Time(frameNum,timeSlot);
//writeClockInterface();
}*/
/*
DAB -- Just let these go through the demod.
if (GSM::Time(frameNum,timeSlot) < mTransmitDeadlineClock) {
// stale burst from GSM core
LOG(NOTICE) << "STALE packet on GSM->TRX interface at time "<< GSM::Time(frameNum,timeSlot);
return false;
}
*/
// periodically update GSM core clock
if (mTransmitDeadlineClock > mLastClockUpdateTime + GSM::Time(216,0))
writeClockInterface();
LOG(DEEPDEBUG) << "rcvd. burst at: " << GSM::Time(frameNum,timeSlot);
int RSSI = (int) buffer[5];
BitVector newBurst(gSlotLen);
BitVector::iterator itr = newBurst.begin();
char *bufferItr = buffer+6;
while (itr < newBurst.end())
*itr++ = *bufferItr++;
GSM::Time currTime = GSM::Time(frameNum,timeSlot);
addRadioVector(newBurst,RSSI,currTime);
LOG(DEEPDEBUG) "added burst - time: " << currTime << ", RSSI: " << RSSI; // << ", data: " << newBurst;
return true;
}
void Transceiver::driveReceiveFIFO()
{
SoftVector *rxBurst = NULL;
int RSSI;
int TOA; // in 1/256 of a symbol
GSM::Time burstTime;
rxBurst = pullRadioVector(burstTime,RSSI,TOA);
if (rxBurst) {
/*LOG(DEEPDEBUG) << ("burst parameters: "
<< " time: " << burstTime
<< " RSSI: " << RSSI
<< " TOA: " << TOA
<< " bits: " << *rxBurst;
*/
char burstString[gSlotLen+10];
burstString[0] = burstTime.TN();
for (int i = 0; i < 4; i++)
burstString[1+i] = (burstTime.FN() >> ((3-i)*8)) & 0x0ff;
burstString[5] = RSSI;
burstString[6] = (TOA >> 8) & 0x0ff;
burstString[7] = TOA & 0x0ff;
SoftVector::iterator burstItr = rxBurst->begin();
for (unsigned int i = 0; i < gSlotLen; i++) {
burstString[8+i] =(char) round((*burstItr++)*255.0);
}
burstString[gSlotLen+9] = '\0';
delete rxBurst;
mDataSocket.write(burstString,gSlotLen+10);
}
}
void Transceiver::driveTransmitFIFO()
{
/**
Features a carefully controlled latency mechanism, to
assure that transmit packets arrive at the radio/USRP
before they need to be transmitted.
Deadline clock indicates the burst that needs to be
pushed into the FIFO right NOW. If transmit queue does
not have a burst, stick in filler data.
*/
RadioClock *radioClock = (mRadioInterface->getClock());
if (mOn) {
radioClock->wait(); // wait until clock updates
while (radioClock->get() + mTransmitLatency >
mTransmitDeadlineClock) {
#ifndef USE_UHD
// if underrun, then we're not providing bursts to radio/USRP fast
// enough. Need to increase latency by one GSM frame.
if (mRadioInterface->isUnderrun()) {
// only do latency update every 10 frames, so we don't over update
if (radioClock->get() > mLatencyUpdateTime + GSM::Time(10,0)) {
mTransmitLatency = mTransmitLatency + GSM::Time(1,0);
LOG(INFO) << "new latency: " << mTransmitLatency;
mLatencyUpdateTime = radioClock->get();
}
}
else {
// if underrun hasn't occurred in the last sec (216 frames) drop
// transmit latency by a timeslot
if (mTransmitLatency > GSM::Time(1,1)) {
if (radioClock->get() > mLatencyUpdateTime + GSM::Time(216,0)) {
mTransmitLatency.decTN();
LOG(INFO) << "reduced latency: " << mTransmitLatency;
mLatencyUpdateTime = radioClock->get();
}
}
}
#endif
// time to push burst to transmit FIFO
pushRadioVector(mTransmitDeadlineClock);
mTransmitDeadlineClock.incTN();
}
}
// FIXME -- This should not be a hard spin.
// But any delay here causes us to throw omni_thread_fatal.
//else radioClock->wait();
}
void Transceiver::writeClockInterface()
{
char command[50];
// FIXME -- This should be adaptive.
sprintf(command,"IND CLOCK %llu",(unsigned long long) (mTransmitDeadlineClock.FN())+2);
LOG(INFO) << "ClockInterface: sending " << command;
mClockSocket.write(command,strlen(command)+1);
mLastClockUpdateTime = mTransmitDeadlineClock;
}
void *TransmitFIFOServiceLoopAdapter(Transceiver *transceiver)
{
while (1) {
transceiver->driveTransmitFIFO();
pthread_testcancel();
}
return NULL;
}
void *ReceiveFIFOServiceLoopAdapter(Transceiver *transceiver)
{
while (1) {
transceiver->driveReceiveFIFO();
pthread_testcancel();
}
return NULL;
}
void *ControlServiceLoopAdapter(Transceiver *transceiver)
{
while (1) {
transceiver->driveControl();
pthread_testcancel();
}
return NULL;
}
void *TransmitPriorityQueueServiceLoopAdapter(Transceiver *transceiver)
{
while (1) {
bool stale = false;
// Flush the UDP packets until a successful transfer.
while (!transceiver->driveTransmitPriorityQueue()) {
stale = true;
}
if (stale) {
// If a packet was stale, remind the GSM stack of the clock.
transceiver->writeClockInterface();
}
pthread_testcancel();
}
return NULL;
}

View File

@ -1,214 +0,0 @@
/*
* Copyright 2008 Free Software Foundation, Inc.
*
* This software is distributed under the terms of the GNU Affero Public License.
* See the COPYING file in the main directory for details.
*
* This use of this software may be subject to additional restrictions.
* See the LEGAL file in the main directory for details.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
Compilation switches
TRANSMIT_LOGGING write every burst on the given slot to a log
*/
#include "radioInterface.h"
#include "Interthread.h"
#include "GSMCommon.h"
#include "Sockets.h"
#include <sys/types.h>
#include <sys/socket.h>
/** Define this to be the slot number to be logged. */
//#define TRANSMIT_LOGGING 1
/** The Transceiver class, responsible for physical layer of basestation */
class Transceiver {
private:
GSM::Time mTransmitLatency; ///< latency between basestation clock and transmit deadline clock
GSM::Time mLatencyUpdateTime; ///< last time latency was updated
UDPSocket mDataSocket; ///< socket for writing to/reading from GSM core
UDPSocket mControlSocket; ///< socket for writing/reading control commands from GSM core
UDPSocket mClockSocket; ///< socket for writing clock updates to GSM core
VectorQueue mTransmitPriorityQueue; ///< priority queue of transmit bursts received from GSM core
VectorFIFO* mTransmitFIFO; ///< radioInterface FIFO of transmit bursts
VectorFIFO* mReceiveFIFO; ///< radioInterface FIFO of receive bursts
mutable Mutex mLock; ///< internal lock used for timeslicing threads
mutable Mutex mDataSocketLock; ///< lock for handling the data socket
Thread mTransmitFIFOServiceLoopThread; ///< thread to push bursts into transmit FIFO
Thread mReceiveFIFOServiceLoopThread; ///< thread for pulling bursts from receive FIFO
Thread mControlServiceLoopThread; ///< thread to process control messages from GSM core
Thread mTransmitPriorityQueueServiceLoopThread;///< thread to process transmit bursts from GSM core
GSM::Time mTransmitDeadlineClock; ///< deadline for pushing bursts into transmit FIFO
GSM::Time mLastClockUpdateTime; ///< last time clock update was sent up to core
RadioInterface *mRadioInterface; ///< associated radioInterface object
double txFullScale; ///< full scale input to radio
double rxFullScale; ///< full scale output to radio
/** Codes for burst types of received bursts*/
typedef enum {
OFF, ///< timeslot is off
TSC, ///< timeslot should contain a normal burst
RACH, ///< timeslot should contain an access burst
IDLE ///< timeslot is an idle (or dummy) burst
} CorrType;
/** Codes for channel combinations */
typedef enum {
NONE, ///< Channel is inactive
I, ///< TCH/FS
II, ///< TCH/HS, idle every other slot
III, ///< TCH/HS
IV, ///< FCCH+SCH+CCCH+BCCH, uplink RACH
V, ///< FCCH+SCH+CCCH+BCCH+SDCCH/4+SACCH/4, uplink RACH+SDCCH/4
VI, ///< CCCH+BCCH, uplink RACH
VII, ///< SDCCH/8 + SACCH/8
LOOPBACK ///< similar go VII, used in loopback testing
} ChannelCombination;
/** unmodulate a modulated burst */
#ifdef TRANSMIT_LOGGING
void unModulateVector(signalVector wVector);
#endif
/** modulate and add a burst to the transmit queue */
void addRadioVector(BitVector &burst,
int RSSI,
GSM::Time &wTime);
/** Push modulated burst into transmit FIFO corresponding to a particular timestamp */
void pushRadioVector(GSM::Time &nowTime);
/** Pull and demodulate a burst from the receive FIFO */
SoftVector *pullRadioVector(GSM::Time &wTime,
int &RSSI,
int &timingOffset);
/** Set modulus for specific timeslot */
void setModulus(int timeslot);
/** return the expected burst type for the specified timestamp */
CorrType expectedCorrType(GSM::Time currTime);
/** send messages over the clock socket */
void writeClockInterface(void);
signalVector *gsmPulse; ///< the GSM shaping pulse for modulation
int mSamplesPerSymbol; ///< number of samples per GSM symbol
bool mOn; ///< flag to indicate that transceiver is powered on
ChannelCombination mChanType[8]; ///< channel types for all timeslots
double mTxFreq; ///< the transmit frequency
double mRxFreq; ///< the receive frequency
int mPower; ///< the transmit power in dB
unsigned mTSC; ///< the midamble sequence code
double mEnergyThreshold; ///< threshold to determine if received data is potentially a GSM burst
GSM::Time prevFalseDetectionTime; ///< last timestamp of a false energy detection
int fillerModulus[8]; ///< modulus values of all timeslots, in frames
signalVector *fillerTable[102][8]; ///< table of modulated filler waveforms for all timeslots
GSM::Time channelEstimateTime[8]; ///< last timestamp of each timeslot's channel estimate
signalVector *channelResponse[8]; ///< most recent channel estimate of all timeslots
float SNRestimate[8]; ///< most recent SNR estimate of all timeslots
signalVector *DFEForward[8]; ///< most recent DFE feedforward filter of all timeslots
signalVector *DFEFeedback[8]; ///< most recent DFE feedback filter of all timeslots
float chanRespOffset[8]; ///< most recent timing offset, e.g. TOA, of all timeslots
complex chanRespAmplitude[8]; ///< most recent channel amplitude of all timeslots
public:
/** Transceiver constructor
@param wBasePort base port number of UDP sockets
@param TRXAddress IP address of the TRX manager, as a string
@param wSamplesPerSymbol number of samples per GSM symbol
@param wTransmitLatency initial setting of transmit latency
@param radioInterface associated radioInterface object
*/
Transceiver(int wBasePort,
const char *TRXAddress,
int wSamplesPerSymbol,
GSM::Time wTransmitLatency,
RadioInterface *wRadioInterface);
/** Destructor */
~Transceiver();
/** start the Transceiver */
void start();
/** attach the radioInterface receive FIFO */
void receiveFIFO(VectorFIFO *wFIFO) { mReceiveFIFO = wFIFO;}
/** attach the radioInterface transmit FIFO */
void transmitFIFO(VectorFIFO *wFIFO) { mTransmitFIFO = wFIFO;}
protected:
/** drive reception and demodulation of GSM bursts */
void driveReceiveFIFO();
/** drive transmission of GSM bursts */
void driveTransmitFIFO();
/** drive handling of control messages from GSM core */
void driveControl();
/**
drive modulation and sorting of GSM bursts from GSM core
@return true if a burst was transferred successfully
*/
bool driveTransmitPriorityQueue();
friend void *TransmitFIFOServiceLoopAdapter(Transceiver *);
friend void *ReceiveFIFOServiceLoopAdapter(Transceiver *);
friend void *ControlServiceLoopAdapter(Transceiver *);
friend void *TransmitPriorityQueueServiceLoopAdapter(Transceiver *);
void reset();
};
/** transmit FIFO thread loop */
void *TransmitFIFOServiceLoopAdapter(Transceiver *);
/** receive FIFO thread loop */
void *ReceiveFIFOServiceLoopAdapter(Transceiver *);
/** control message handler thread loop */
void *ControlServiceLoopAdapter(Transceiver *);
/** transmit queueing thread loop */
void *TransmitPriorityQueueServiceLoopAdapter(Transceiver *);

View File

@ -1,882 +0,0 @@
/*
* Copyright 2008, 2009, 2010 Free Software Foundation, Inc.
*
* This software is distributed under the terms of the GNU Affero Public License.
* See the COPYING file in the main directory for details.
*
* This use of this software may be subject to additional restrictions.
* See the LEGAL file in the main directory for details.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "../Transceiver52M/radioDevice.h"
#include "Threads.h"
#include "Logger.h"
#include <uhd/usrp/single_usrp.hpp>
#include <uhd/utils/thread_priority.hpp>
/*
use_ext_ref - Enable external 10MHz clock reference
master_clk_rt - Master clock frequency
rx_smpl_offset - Timing correction in seconds between receive and
transmit timestamps. This value corrects for delays on
on the RF side of the timestamping point of the device.
This value is generally empirically measured.
smpl_buf_sz - The receive sample buffer size in bytes.
tx_ampl - Transmit amplitude must be between 0 and 1.0
*/
const bool use_ext_ref = false;
const double master_clk_rt = 100e6;
const double rx_smpl_offset = .00005;
const size_t smpl_buf_sz = (1 << 20);
const float tx_ampl = .3;
/** Timestamp conversion
@param timestamp a UHD or OpenBTS timestamp
@param rate sample rate
@return the converted timestamp
*/
uhd::time_spec_t convert_time(TIMESTAMP ticks, double rate)
{
double secs = (double) ticks / rate;
return uhd::time_spec_t(secs);
}
TIMESTAMP convert_time(uhd::time_spec_t ts, double rate)
{
TIMESTAMP ticks = ts.get_full_secs() * rate;
return ts.get_tick_count(rate) + ticks;
}
/*
Sample Buffer - Allows reading and writing of timed samples using OpenBTS
or UHD style timestamps. Time conversions are handled
internally or accessable through the static convert calls.
*/
class smpl_buf {
public:
/** Sample buffer constructor
@param len number of 32-bit samples the buffer should hold
@param rate sample clockrate
@param timestamp
*/
smpl_buf(size_t len, double rate);
~smpl_buf();
/** Query number of samples available for reading
@param timestamp time of first sample
@return number of available samples or error
*/
ssize_t avail_smpls(TIMESTAMP timestamp) const;
ssize_t avail_smpls(uhd::time_spec_t timestamp) const;
/** Read and write
@param buf pointer to buffer
@param len number of samples desired to read or write
@param timestamp time of first stample
@return number of actual samples read or written or error
*/
ssize_t read(void *buf, size_t len, TIMESTAMP timestamp);
ssize_t read(void *buf, size_t len, uhd::time_spec_t timestamp);
ssize_t write(void *buf, size_t len, TIMESTAMP timestamp);
ssize_t write(void *buf, size_t len, uhd::time_spec_t timestamp);
/** Buffer status string
@return a formatted string describing internal buffer state
*/
std::string str_status() const;
/** Formatted error string
@param code an error code
@return a formatted error string
*/
static std::string str_code(ssize_t code);
enum err_code {
ERROR_TIMESTAMP = -1,
ERROR_READ = -2,
ERROR_WRITE = -3,
ERROR_OVERFLOW = -4
};
private:
uint32_t *data;
size_t buf_len;
double clk_rt;
TIMESTAMP time_start;
TIMESTAMP time_end;
size_t data_start;
size_t data_end;
};
/*
uhd_device - UHD implementation of the Device interface. Timestamped samples
are sent to and received from the device. An intermediate buffer
on the receive side collects and aligns packets of samples.
Events and errors such as underruns are reported asynchronously
by the device and received in a separate thread.
*/
class uhd_device : public RadioDevice {
public:
uhd_device(double rate, bool skip_rx);
~uhd_device();
bool open();
bool start();
bool stop();
void restart(uhd::time_spec_t ts);
void setPriority();
int readSamples(short *buf, int len, bool *overrun,
TIMESTAMP timestamp, bool *underrun, unsigned *RSSI);
int writeSamples(short *buf, int len, bool *underrun,
TIMESTAMP timestamp, bool isControl);
bool updateAlignment(TIMESTAMP timestamp);
bool setTxFreq(double wFreq);
bool setRxFreq(double wFreq);
inline TIMESTAMP initialWriteTimestamp() { return 0; }
inline TIMESTAMP initialReadTimestamp() { return 0; }
inline double fullScaleInputValue() { return 32000 * tx_ampl; }
inline double fullScaleOutputValue() { return 32000; }
double setRxGain(double db);
double getRxGain(void) { return rx_gain; }
double maxRxGain(void) { return rx_gain_max; }
double minRxGain(void) { return rx_gain_min; }
double setTxGain(double db);
double maxTxGain(void) { return tx_gain_max; }
double minTxGain(void) { return tx_gain_min; }
double getTxFreq() { return tx_freq; }
double getRxFreq() { return rx_freq; }
inline double getSampleRate() { return actual_smpl_rt; }
inline double numberRead() { return rx_pkt_cnt; }
inline double numberWritten() { return 0; }
/** Receive and process asynchronous message
@return true if message received or false on timeout or error
*/
bool recv_async_msg();
enum err_code {
ERROR_TIMING = -1,
ERROR_UNRECOVERABLE = -2,
ERROR_UNHANDLED = -3,
};
private:
uhd::usrp::single_usrp::sptr usrp_dev;
double desired_smpl_rt, actual_smpl_rt;
double tx_gain, tx_gain_min, tx_gain_max;
double rx_gain, rx_gain_min, rx_gain_max;
double tx_freq, rx_freq;
size_t tx_spp, rx_spp;
bool started;
bool aligned;
bool skip_rx;
size_t rx_pkt_cnt;
size_t drop_cnt;
uhd::time_spec_t prev_ts;
TIMESTAMP ts_offset;
smpl_buf *rx_smpl_buf;
void init_gains();
void set_ref_clk(bool ext_clk);
double set_rates(double rate);
bool flush_recv(size_t num_pkts);
int check_rx_md_err(uhd::rx_metadata_t &md, ssize_t num_smpls);
std::string str_code(uhd::rx_metadata_t metadata);
std::string str_code(uhd::async_metadata_t metadata);
Thread async_event_thrd;
};
void *async_event_loop(uhd_device *dev)
{
while (1) {
dev->recv_async_msg();
pthread_testcancel();
}
}
uhd_device::uhd_device(double rate, bool skip_rx)
: desired_smpl_rt(rate), actual_smpl_rt(0),
tx_gain(0.0), tx_gain_min(0.0), tx_gain_max(0.0),
rx_gain(0.0), rx_gain_min(0.0), rx_gain_max(0.0),
tx_freq(0.0), rx_freq(0.0), tx_spp(0), rx_spp(0),
started(false), aligned(false), rx_pkt_cnt(0), drop_cnt(0),
prev_ts(0,0), ts_offset(0), rx_smpl_buf(NULL)
{
this->skip_rx = skip_rx;
}
uhd_device::~uhd_device()
{
stop();
if (rx_smpl_buf)
delete rx_smpl_buf;
}
void uhd_device::init_gains()
{
uhd::gain_range_t range;
range = usrp_dev->get_tx_gain_range();
tx_gain_min = range.start();
tx_gain_max = range.stop();
range = usrp_dev->get_rx_gain_range();
rx_gain_min = range.start();
rx_gain_max = range.stop();
usrp_dev->set_tx_gain((tx_gain_min + tx_gain_max) / 2);
usrp_dev->set_rx_gain((rx_gain_min + rx_gain_max) / 2);
tx_gain = usrp_dev->get_tx_gain();
rx_gain = usrp_dev->get_rx_gain();
return;
}
void uhd_device::set_ref_clk(bool ext_clk)
{
uhd::clock_config_t clk_cfg;
clk_cfg.pps_source = uhd::clock_config_t::PPS_SMA;
if (ext_clk)
clk_cfg.ref_source = uhd::clock_config_t::REF_SMA;
else
clk_cfg.ref_source = uhd::clock_config_t::REF_INT;
usrp_dev->set_clock_config(clk_cfg);
return;
}
double uhd_device::set_rates(double rate)
{
double actual_rt, actual_clk_rt;
// Set master clock rate
usrp_dev->set_master_clock_rate(master_clk_rt);
actual_clk_rt = usrp_dev->get_master_clock_rate();
if (actual_clk_rt != master_clk_rt) {
LOG(ERROR) << "Failed to set master clock rate";
return -1.0;
}
// Set sample rates
usrp_dev->set_tx_rate(rate);
usrp_dev->set_rx_rate(rate);
actual_rt = usrp_dev->get_tx_rate();
if (actual_rt != rate) {
LOG(ERROR) << "Actual sample rate differs from desired rate";
return -1.0;
}
if (usrp_dev->get_rx_rate() != actual_rt) {
LOG(ERROR) << "Transmit and receive sample rates do not match";
return -1.0;
}
return actual_rt;
}
double uhd_device::setTxGain(double db)
{
usrp_dev->set_tx_gain(db);
tx_gain = usrp_dev->get_tx_gain();
LOG(INFO) << "Set TX gain to " << tx_gain << "dB";
return tx_gain;
}
double uhd_device::setRxGain(double db)
{
usrp_dev->set_rx_gain(db);
rx_gain = usrp_dev->get_rx_gain();
LOG(INFO) << "Set RX gain to " << rx_gain << "dB";
return rx_gain;
}
bool uhd_device::open()
{
LOG(INFO) << "creating USRP device...";
// Use the first available USRP2 / N2xx
uhd::device_addr_t dev_addr("type=usrp2");
try {
usrp_dev = uhd::usrp::single_usrp::make(dev_addr);
}
catch(...) {
LOG(ERROR) << "Failed to find USRP2 / N2xx device";
return false;
}
// Number of samples per over-the-wire packet
tx_spp = usrp_dev->get_device()->get_max_send_samps_per_packet();
rx_spp = usrp_dev->get_device()->get_max_recv_samps_per_packet();
// Set rates
actual_smpl_rt = set_rates(desired_smpl_rt);
if (actual_smpl_rt < 0)
return false;
// Create receive buffer
size_t buf_len = smpl_buf_sz / sizeof(uint32_t);
rx_smpl_buf = new smpl_buf(buf_len, actual_smpl_rt);
// Set receive chain sample offset
ts_offset = (TIMESTAMP)(rx_smpl_offset * actual_smpl_rt);
// Initialize and shadow gain values
init_gains();
// Set reference clock
set_ref_clk(use_ext_ref);
// Print configuration
LOG(INFO) << usrp_dev->get_pp_string();
return true;
}
bool uhd_device::flush_recv(size_t num_pkts)
{
uhd::rx_metadata_t md;
size_t num_smpls;
uint32_t buff[rx_spp];
float timeout;
// Use .01 sec instead of the default .1 sec
timeout = .01;
for (size_t i = 0; i < num_pkts; i++) {
num_smpls = usrp_dev->get_device()->recv(
buff,
rx_spp,
md,
uhd::io_type_t::COMPLEX_INT16,
uhd::device::RECV_MODE_ONE_PACKET,
timeout);
if (!num_smpls) {
switch (md.error_code) {
case uhd::rx_metadata_t::ERROR_CODE_TIMEOUT:
return true;
default:
continue;
}
}
}
return true;
}
void uhd_device::restart(uhd::time_spec_t ts)
{
uhd::stream_cmd_t cmd = uhd::stream_cmd_t::STREAM_MODE_STOP_CONTINUOUS;
usrp_dev->issue_stream_cmd(cmd);
flush_recv(50);
usrp_dev->set_time_now(ts);
aligned = false;
cmd = uhd::stream_cmd_t::STREAM_MODE_START_CONTINUOUS;
cmd.stream_now = true;
usrp_dev->issue_stream_cmd(cmd);
}
bool uhd_device::start()
{
LOG(INFO) << "Starting USRP...";
if (started) {
LOG(ERROR) << "Device already started";
return false;
}
setPriority();
// Start asynchronous event (underrun check) loop
async_event_thrd.start((void * (*)(void*))async_event_loop, (void*)this);
// Start streaming
restart(uhd::time_spec_t(0.0));
// Display usrp time
double time_now = usrp_dev->get_time_now().get_real_secs();
LOG(INFO) << "The current time is " << time_now << " seconds";
started = true;
return true;
}
bool uhd_device::stop()
{
uhd::stream_cmd_t stream_cmd =
uhd::stream_cmd_t::STREAM_MODE_STOP_CONTINUOUS;
usrp_dev->issue_stream_cmd(stream_cmd);
started = false;
return true;
}
void uhd_device::setPriority()
{
uhd::set_thread_priority_safe();
return;
}
int uhd_device::check_rx_md_err(uhd::rx_metadata_t &md, ssize_t num_smpls)
{
uhd::time_spec_t ts;
if (!num_smpls) {
LOG(ERROR) << str_code(md);
switch (md.error_code) {
case uhd::rx_metadata_t::ERROR_CODE_TIMEOUT:
return ERROR_UNRECOVERABLE;
case uhd::rx_metadata_t::ERROR_CODE_OVERFLOW:
case uhd::rx_metadata_t::ERROR_CODE_LATE_COMMAND:
case uhd::rx_metadata_t::ERROR_CODE_BROKEN_CHAIN:
case uhd::rx_metadata_t::ERROR_CODE_BAD_PACKET:
default:
return ERROR_UNHANDLED;
}
}
// Missing timestamp
if (!md.has_time_spec) {
LOG(ERROR) << "UHD: Received packet missing timestamp";
return ERROR_UNRECOVERABLE;
}
ts = md.time_spec;
// Monotonicity check
if (ts < prev_ts) {
LOG(ERROR) << "UHD: Loss of monotonic: " << ts.get_real_secs();
LOG(ERROR) << "UHD: Previous time: " << prev_ts.get_real_secs();
return ERROR_TIMING;
} else {
prev_ts = ts;
}
return 0;
}
int uhd_device::readSamples(short *buf, int len, bool *overrun,
TIMESTAMP timestamp, bool *underrun, unsigned *RSSI)
{
ssize_t rc;
uhd::time_spec_t ts;
uhd::rx_metadata_t metadata;
uint32_t pkt_buf[rx_spp];
if (skip_rx)
return 0;
// Shift read time with respect to transmit clock
timestamp += ts_offset;
ts = convert_time(timestamp, actual_smpl_rt);
LOG(DEEPDEBUG) << "Requested timestamp = " << ts.get_real_secs();
// Check that timestamp is valid
rc = rx_smpl_buf->avail_smpls(timestamp);
if (rc < 0) {
LOG(ERROR) << rx_smpl_buf->str_code(rc);
LOG(ERROR) << rx_smpl_buf->str_status();
return 0;
}
// Receive samples from the usrp until we have enough
while (rx_smpl_buf->avail_smpls(timestamp) < len) {
size_t num_smpls = usrp_dev->get_device()->recv(
(void*)pkt_buf,
rx_spp,
metadata,
uhd::io_type_t::COMPLEX_INT16,
uhd::device::RECV_MODE_ONE_PACKET);
rx_pkt_cnt++;
// Check for errors
rc = check_rx_md_err(metadata, num_smpls);
switch (rc) {
case ERROR_UNRECOVERABLE:
LOG(ERROR) << "UHD: Unrecoverable error, exiting.";
exit(-1);
case ERROR_TIMING:
restart(prev_ts);
case ERROR_UNHANDLED:
return 0;
}
ts = metadata.time_spec;
LOG(DEEPDEBUG) << "Received timestamp = " << ts.get_real_secs();
rc = rx_smpl_buf->write(pkt_buf,
num_smpls,
metadata.time_spec);
// Continue on local overrun, exit on other errors
if ((rc < 0)) {
LOG(ERROR) << rx_smpl_buf->str_code(rc);
LOG(ERROR) << rx_smpl_buf->str_status();
if (rc != smpl_buf::ERROR_OVERFLOW)
return 0;
}
}
// We have enough samples
rc = rx_smpl_buf->read(buf, len, timestamp);
if ((rc < 0) || (rc != len)) {
LOG(ERROR) << rx_smpl_buf->str_code(rc);
LOG(ERROR) << rx_smpl_buf->str_status();
return 0;
}
return len;
}
int uhd_device::writeSamples(short *buf, int len, bool *underrun,
unsigned long long timestamp,bool isControl)
{
uhd::tx_metadata_t metadata;
metadata.has_time_spec = true;
metadata.start_of_burst = false;
metadata.end_of_burst = false;
metadata.time_spec = convert_time(timestamp, actual_smpl_rt);
// No control packets
if (isControl) {
LOG(ERROR) << "Control packets not supported";
return 0;
}
// Drop a fixed number of packets (magic value)
if (!aligned) {
drop_cnt++;
if (drop_cnt == 1) {
LOG(DEBUG) << "Aligning transmitter: stop burst";
metadata.end_of_burst = true;
} else if (drop_cnt < 30) {
LOG(DEEPDEBUG) << "Aligning transmitter: packet advance";
*underrun = true;
return len;
} else {
LOG(DEBUG) << "Aligning transmitter: start burst";
metadata.start_of_burst = true;
aligned = true;
drop_cnt = 0;
}
}
size_t num_smpls = usrp_dev->get_device()->send(buf,
len,
metadata,
uhd::io_type_t::COMPLEX_INT16,
uhd::device::SEND_MODE_FULL_BUFF);
if (num_smpls != (unsigned)len)
LOG(ERROR) << "UHD: Sent fewer samples than requested";
return num_smpls;
}
bool uhd_device::updateAlignment(TIMESTAMP timestamp)
{
aligned = false;
return true;
}
bool uhd_device::setTxFreq(double wFreq)
{
uhd::tune_result_t tr = usrp_dev->set_tx_freq(wFreq);
LOG(INFO) << tr.to_pp_string();
tx_freq = usrp_dev->get_tx_freq();
return true;
}
bool uhd_device::setRxFreq(double wFreq)
{
uhd::tune_result_t tr = usrp_dev->set_rx_freq(wFreq);
LOG(INFO) << tr.to_pp_string();
rx_freq = usrp_dev->get_rx_freq();
return true;
}
bool uhd_device::recv_async_msg()
{
uhd::async_metadata_t metadata;
if (!usrp_dev->get_device()->recv_async_msg(metadata))
return false;
// Assume that any error requires resynchronization
if (metadata.event_code != uhd::async_metadata_t::EVENT_CODE_BURST_ACK) {
aligned = false;
LOG(ERROR) << str_code(metadata);
}
return true;
}
std::string uhd_device::str_code(uhd::rx_metadata_t metadata)
{
std::ostringstream ost("UHD: ");
switch (metadata.error_code) {
case uhd::rx_metadata_t::ERROR_CODE_NONE:
ost << "No error";
break;
case uhd::rx_metadata_t::ERROR_CODE_TIMEOUT:
ost << "No packet received, implementation timed-out";
break;
case uhd::rx_metadata_t::ERROR_CODE_LATE_COMMAND:
ost << "A stream command was issued in the past";
break;
case uhd::rx_metadata_t::ERROR_CODE_BROKEN_CHAIN:
ost << "Expected another stream command";
break;
case uhd::rx_metadata_t::ERROR_CODE_OVERFLOW:
ost << "An internal receive buffer has filled";
break;
case uhd::rx_metadata_t::ERROR_CODE_BAD_PACKET:
ost << "The packet could not be parsed";
break;
default:
ost << "Unknown error " << metadata.error_code;
}
if (metadata.has_time_spec)
ost << " at " << metadata.time_spec.get_real_secs() << " sec.";
return ost.str();
}
std::string uhd_device::str_code(uhd::async_metadata_t metadata)
{
std::ostringstream ost("UHD: ");
switch (metadata.event_code) {
case uhd::async_metadata_t::EVENT_CODE_BURST_ACK:
ost << "A packet was successfully transmitted";
break;
case uhd::async_metadata_t::EVENT_CODE_UNDERFLOW:
ost << "An internal send buffer has emptied";
break;
case uhd::async_metadata_t::EVENT_CODE_SEQ_ERROR:
ost << "Packet loss between host and device";
break;
case uhd::async_metadata_t::EVENT_CODE_TIME_ERROR:
ost << "Packet time was too late or too early";
break;
case uhd::async_metadata_t::EVENT_CODE_UNDERFLOW_IN_PACKET:
ost << "Underflow occurred inside a packet";
break;
case uhd::async_metadata_t::EVENT_CODE_SEQ_ERROR_IN_BURST:
ost << "Packet loss within a burst";
break;
default:
ost << "Unknown error " << metadata.event_code;
}
if (metadata.has_time_spec)
ost << " at " << metadata.time_spec.get_real_secs() << " sec.";
return ost.str();
}
smpl_buf::smpl_buf(size_t len, double rate)
: buf_len(len), clk_rt(rate),
time_start(0), time_end(0), data_start(0), data_end(0)
{
data = new uint32_t[len];
}
smpl_buf::~smpl_buf()
{
delete[] data;
}
ssize_t smpl_buf::avail_smpls(TIMESTAMP timestamp) const
{
if (timestamp < time_start)
return ERROR_TIMESTAMP;
else if (timestamp >= time_end)
return 0;
else
return time_end - timestamp;
}
ssize_t smpl_buf::avail_smpls(uhd::time_spec_t timespec) const
{
return avail_smpls(convert_time(timespec, clk_rt));
}
ssize_t smpl_buf::read(void *buf, size_t len, TIMESTAMP timestamp)
{
// Check for valid read
if (timestamp < time_start)
return ERROR_TIMESTAMP;
if (timestamp >= time_end)
return 0;
if (len >= buf_len)
return ERROR_READ;
// How many samples should be copied
size_t num_smpls = time_end - timestamp;
if (num_smpls > len);
num_smpls = len;
// Starting index
size_t read_start = data_start + (timestamp - time_start);
// Read it
if (read_start + num_smpls < buf_len) {
size_t numBytes = len * 2 * sizeof(short);
memcpy(buf, data + read_start, numBytes);
} else {
size_t first_cp = (buf_len - read_start) * 2 * sizeof(short);
size_t second_cp = len * 2 * sizeof(short) - first_cp;
memcpy(buf, data + read_start, first_cp);
memcpy((char*) buf + first_cp, data, second_cp);
}
data_start = (read_start + len) % buf_len;
time_start = timestamp + len;
if (time_start > time_end)
return ERROR_READ;
else
return num_smpls;
}
ssize_t smpl_buf::read(void *buf, size_t len, uhd::time_spec_t ts)
{
return read(buf, len, convert_time(ts, clk_rt));
}
ssize_t smpl_buf::write(void *buf, size_t len, TIMESTAMP timestamp)
{
// Check for valid write
if ((len == 0) || (len >= buf_len))
return ERROR_WRITE;
if ((timestamp + len) <= time_end)
return ERROR_TIMESTAMP;
// Starting index
size_t write_start = (data_start + (timestamp - time_start)) % buf_len;
// Write it
if ((write_start + len) < buf_len) {
size_t numBytes = len * 2 * sizeof(short);
memcpy(data + write_start, buf, numBytes);
} else {
size_t first_cp = (buf_len - write_start) * 2 * sizeof(short);
size_t second_cp = len * 2 * sizeof(short) - first_cp;
memcpy(data + write_start, buf, first_cp);
memcpy(data, (char*) buf + first_cp, second_cp);
}
data_end = (write_start + len) % buf_len;
time_end = timestamp + len;
if (((write_start + len) > buf_len) && (data_end > data_start))
return ERROR_OVERFLOW;
else if (time_end <= time_start)
return ERROR_WRITE;
else
return len;
}
ssize_t smpl_buf::write(void *buf, size_t len, uhd::time_spec_t ts)
{
return write(buf, len, convert_time(ts, clk_rt));
}
std::string smpl_buf::str_status() const
{
std::ostringstream ost("Sample buffer: ");
ost << "length = " << buf_len;
ost << ", time_start = " << time_start;
ost << ", time_end = " << time_end;
ost << ", data_start = " << data_start;
ost << ", data_end = " << data_end;
return ost.str();
}
std::string smpl_buf::str_code(ssize_t code)
{
switch (code) {
case ERROR_TIMESTAMP:
return "Sample buffer: Requested timestamp is not valid";
case ERROR_READ:
return "Sample buffer: Read error";
case ERROR_WRITE:
return "Sample buffer: Write error";
case ERROR_OVERFLOW:
return "Sample buffer: Overrun";
default:
return "Sample buffer: Unknown error";
}
}
RadioDevice *RadioDevice::make(double smpl_rt, bool skip_rx)
{
return new uhd_device(smpl_rt, skip_rx);
}

View File

@ -1,537 +0,0 @@
/*
* Copyright 2008, 2009 Free Software Foundation, Inc.
*
* This software is distributed under the terms of the GNU Affero Public License.
* See the COPYING file in the main directory for details.
*
* This use of this software may be subject to additional restrictions.
* See the LEGAL file in the main directory for details.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
Compilation Flags
SWLOOPBACK compile for software loopback testing
*/
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include "Threads.h"
#include "USRPDevice.h"
#include <Logger.h>
using namespace std;
enum dboardConfigType {
TXA_RXB,
TXB_RXA,
TXA_RXA,
TXB_RXB
};
const dboardConfigType dboardConfig = TXA_RXB;
const double USRPDevice::masterClockRate = 64.0e6;
USRPDevice::USRPDevice (double _desiredSampleRate, bool wSkipRx)
: skipRx(wSkipRx)
{
LOG(INFO) << "creating USRP device...";
decimRate = (unsigned int) round(masterClockRate/_desiredSampleRate);
actualSampleRate = masterClockRate/decimRate;
#ifdef SWLOOPBACK
samplePeriod = 1.0e6/actualSampleRate;
loopbackBufferSize = 0;
gettimeofday(&lastReadTime,NULL);
firstRead = false;
#endif
}
bool USRPDevice::open()
{
LOG(INFO) << "opening USRP device...";
#ifndef SWLOOPBACK
string rbf = "std_inband.rbf";
//string rbf = "inband_1rxhb_1tx.rbf";
m_uRx.reset();
if (!skipRx) {
try {
m_uRx = usrp_standard_rx_sptr(usrp_standard_rx::make(0,decimRate,1,-1,
usrp_standard_rx::FPGA_MODE_NORMAL,
1024,16*8,rbf));
#ifdef HAVE_LIBUSRP_3_2
m_uRx->set_fpga_master_clock_freq(masterClockRate);
#endif
}
catch(...) {
LOG(ERROR) << "make failed on Rx";
m_uRx.reset();
return false;
}
if (m_uRx->fpga_master_clock_freq() != masterClockRate)
{
LOG(ERROR) << "WRONG FPGA clock freq = " << m_uRx->fpga_master_clock_freq()
<< ", desired clock freq = " << masterClockRate;
m_uRx.reset();
return false;
}
}
try {
m_uTx = usrp_standard_tx_sptr(usrp_standard_tx::make(0,decimRate*2,1,-1,
1024,16*8,rbf));
#ifdef HAVE_LIBUSRP_3_2
m_uTx->set_fpga_master_clock_freq(masterClockRate);
#endif
}
catch(...) {
LOG(ERROR) << "make failed on Tx";
m_uTx.reset();
return false;
}
if (m_uTx->fpga_master_clock_freq() != masterClockRate)
{
LOG(ERROR) << "WRONG FPGA clock freq = " << m_uTx->fpga_master_clock_freq()
<< ", desired clock freq = " << masterClockRate;
m_uTx.reset();
return false;
}
if (!skipRx) m_uRx->stop();
m_uTx->stop();
#endif
switch (dboardConfig) {
case TXA_RXB:
txSubdevSpec = usrp_subdev_spec(0,0);
rxSubdevSpec = usrp_subdev_spec(1,0);
break;
case TXB_RXA:
txSubdevSpec = usrp_subdev_spec(1,0);
rxSubdevSpec = usrp_subdev_spec(0,0);
break;
case TXA_RXA:
txSubdevSpec = usrp_subdev_spec(0,0);
rxSubdevSpec = usrp_subdev_spec(0,0);
break;
case TXB_RXB:
txSubdevSpec = usrp_subdev_spec(1,0);
rxSubdevSpec = usrp_subdev_spec(1,0);
break;
default:
txSubdevSpec = usrp_subdev_spec(0,0);
rxSubdevSpec = usrp_subdev_spec(1,0);
}
m_dbTx = m_uTx->selected_subdev(txSubdevSpec);
m_dbRx = m_uRx->selected_subdev(rxSubdevSpec);
samplesRead = 0;
samplesWritten = 0;
started = false;
return true;
}
bool USRPDevice::start()
{
LOG(INFO) << "starting USRP...";
#ifndef SWLOOPBACK
if (!m_uRx && !skipRx) return false;
if (!m_uTx) return false;
if (!skipRx) m_uRx->stop();
m_uTx->stop();
// Transmit settings - gain at midpoint
m_dbTx->set_gain((m_dbRx->gain_min() + m_dbRx->gain_max()) / 2);
m_dbTx->set_enable(true);
m_uTx->set_mux(m_uTx->determine_tx_mux_value(txSubdevSpec));
// Receive settings - gain at max, antenna RX2 (if available)
m_dbRx->set_gain(m_dbRx->gain_max());
m_uRx->set_mux(m_uRx->determine_rx_mux_value(rxSubdevSpec));
if (!m_dbRx->select_rx_antenna(1))
m_dbRx->select_rx_antenna(0);
data = new short[currDataSize];
dataStart = 0;
dataEnd = 0;
timeStart = 0;
timeEnd = 0;
timestampOffset = 0;
latestWriteTimestamp = 0;
lastPktTimestamp = 0;
hi32Timestamp = 0;
isAligned = false;
if (!skipRx)
started = (m_uRx->start() && m_uTx->start());
else
started = m_uTx->start();
return started;
#else
gettimeofday(&lastReadTime,NULL);
return true;
#endif
}
bool USRPDevice::stop()
{
#ifndef SWLOOPBACK
if (!m_uRx) return false;
if (!m_uTx) return false;
delete[] currData;
started = !(m_uRx->stop() && m_uTx->stop());
return !started;
#else
return true;
#endif
}
double USRPDevice::maxTxGain()
{
return m_dbTx->gain_max();
}
double USRPDevice::minTxGain()
{
return m_dbTx->gain_min();
}
double USRPDevice::maxRxGain()
{
return m_dbRx->gain_max();
}
double USRPDevice::minRxGain()
{
return m_dbRx->gain_min();
}
double USRPDevice::setTxGain(double dB)
{
if (dB > maxTxGain()) dB = maxTxGain();
if (dB < minTxGain()) dB = minTxGain();
LOG(NOTICE) << "Setting TX gain to " << dB << " dB.";
if (!m_dbRx->set_gain(dB))
LOG(ERROR) << "Error setting TX gain";
return dB;
}
double USRPDevice::setRxGain(double dB)
{
if (dB > maxRxGain()) dB = maxRxGain();
if (dB < minRxGain()) dB = minRxGain();
LOG(NOTICE) << "Setting RX gain to " << dB << " dB.";
if (!m_dbRx->set_gain(dB)) {
LOG(ERROR) << "Error setting RX gain";
} else {
rxGain = dB;
}
return rxGain;
}
// NOTE: Assumes sequential reads
int USRPDevice::readSamples(short *buf, int len, bool *overrun,
TIMESTAMP timestamp,
bool *underrun,
unsigned *RSSI)
{
#ifndef SWLOOPBACK
if (!m_uRx) return 0;
timestamp += timestampOffset;
if (timestamp + len < timeStart) {
memset(buf,0,len*2*sizeof(short));
return len;
}
if (underrun) *underrun = false;
uint32_t *readBuf = NULL;
while (1) {
//guestimate USB read size
int readLen=0;
{
int numSamplesNeeded = timestamp + len - timeEnd;
if (numSamplesNeeded <=0) break;
readLen = 512 * ((int) ceil((float) numSamplesNeeded/126.0));
}
// read USRP packets, parse and save A/D data as needed
if (readBuf!=NULL) delete[] readBuf;
readBuf = new uint32_t[readLen/4];
readLen = m_uRx->read((void *)readBuf,readLen,overrun);
for(int pktNum = 0; pktNum < (readLen/512); pktNum++) {
// tmpBuf points to start of a USB packet
uint32_t* tmpBuf = (uint32_t *) (readBuf+pktNum*512/4);
TIMESTAMP pktTimestamp = usrp_to_host_u32(tmpBuf[1]);
uint32_t word0 = usrp_to_host_u32(tmpBuf[0]);
uint32_t chan = (word0 >> 16) & 0x1f;
unsigned payloadSz = word0 & 0x1ff;
LOG(DEBUG) << "first two bytes: " << hex << word0 << " " << dec << pktTimestamp;
bool incrementHi32 = ((lastPktTimestamp & 0x0ffffffffll) > pktTimestamp);
if (incrementHi32 && (timeStart!=0)) {
LOG(DEBUG) << "high 32 increment!!!";
hi32Timestamp++;
}
pktTimestamp = (((TIMESTAMP) hi32Timestamp) << 32) | pktTimestamp;
lastPktTimestamp = pktTimestamp;
if (chan == 0x01f) {
// control reply, check to see if its ping reply
uint32_t word2 = usrp_to_host_u32(tmpBuf[2]);
if ((word2 >> 16) == ((0x01 << 8) | 0x02)) {
timestamp -= timestampOffset;
timestampOffset = pktTimestamp - pingTimestamp + PINGOFFSET;
LOG(DEBUG) << "updating timestamp offset to: " << timestampOffset;
timestamp += timestampOffset;
isAligned = true;
}
continue;
}
if (chan != 0) {
LOG(DEBUG) << "chan: " << chan << ", timestamp: " << pktTimestamp << ", sz:" << payloadSz;
continue;
}
if ((word0 >> 28) & 0x04) {
if (underrun) *underrun = true;
LOG(DEBUG) << "UNDERRUN in TRX->USRP interface";
}
if (RSSI) *RSSI = (word0 >> 21) & 0x3f;
if (!isAligned) continue;
unsigned cursorStart = pktTimestamp - timeStart + dataStart;
while (cursorStart*2 > currDataSize) {
cursorStart -= currDataSize/2;
}
if (cursorStart*2 + payloadSz/2 > currDataSize) {
// need to circle around buffer
memcpy(data+cursorStart*2,tmpBuf+2,(currDataSize-cursorStart*2)*sizeof(short));
memcpy(data,tmpBuf+2+(currDataSize/2-cursorStart),payloadSz-(currDataSize-cursorStart*2)*sizeof(short));
}
else {
memcpy(data+cursorStart*2,tmpBuf+2,payloadSz);
}
if (pktTimestamp + payloadSz/2/sizeof(short) > timeEnd)
timeEnd = pktTimestamp+payloadSz/2/sizeof(short);
LOG(DEBUG) << "timeStart: " << timeStart << ", timeEnd: " << timeEnd << ", pktTimestamp: " << pktTimestamp;
}
}
// copy desired data to buf
unsigned bufStart = dataStart+(timestamp-timeStart);
if (bufStart + len < currDataSize/2) {
LOG(DEBUG) << "bufStart: " << bufStart;
memcpy(buf,data+bufStart*2,len*2*sizeof(short));
memset(data+bufStart*2,0,len*2*sizeof(short));
}
else {
LOG(DEBUG) << "len: " << len << ", currDataSize/2: " << currDataSize/2 << ", bufStart: " << bufStart;
unsigned firstLength = (currDataSize/2-bufStart);
LOG(DEBUG) << "firstLength: " << firstLength;
memcpy(buf,data+bufStart*2,firstLength*2*sizeof(short));
memset(data+bufStart*2,0,firstLength*2*sizeof(short));
memcpy(buf+firstLength*2,data,(len-firstLength)*2*sizeof(short));
memset(data,0,(len-firstLength)*2*sizeof(short));
}
dataStart = (bufStart + len) % (currDataSize/2);
timeStart = timestamp + len;
if (readBuf!=NULL) delete[] readBuf;
return len;
#else
if (loopbackBufferSize < 2) return 0;
int numSamples = 0;
struct timeval currTime;
gettimeofday(&currTime,NULL);
double timeElapsed = (currTime.tv_sec - lastReadTime.tv_sec)*1.0e6 +
(currTime.tv_usec - lastReadTime.tv_usec);
if (timeElapsed < samplePeriod) {return 0;}
int numSamplesToRead = (int) floor(timeElapsed/samplePeriod);
if (numSamplesToRead < len) return 0;
if (numSamplesToRead > len) numSamplesToRead = len;
if (numSamplesToRead > loopbackBufferSize/2) {
firstRead =false;
numSamplesToRead = loopbackBufferSize/2;
}
memcpy(buf,loopbackBuffer,sizeof(short)*2*numSamplesToRead);
loopbackBufferSize -= 2*numSamplesToRead;
memcpy(loopbackBuffer,loopbackBuffer+2*numSamplesToRead,
sizeof(short)*loopbackBufferSize);
numSamples = numSamplesToRead;
if (firstRead) {
int new_usec = lastReadTime.tv_usec + (int) round((double) numSamplesToRead * samplePeriod);
lastReadTime.tv_sec = lastReadTime.tv_sec + new_usec/1000000;
lastReadTime.tv_usec = new_usec % 1000000;
}
else {
gettimeofday(&lastReadTime,NULL);
firstRead = true;
}
samplesRead += numSamples;
return numSamples;
#endif
}
int USRPDevice::writeSamples(short *buf, int len, bool *underrun,
unsigned long long timestamp,
bool isControl)
{
#ifndef SWLOOPBACK
if (!m_uTx) return 0;
for (int i = 0; i < len*2; i++) {
buf[i] = host_to_usrp_short(buf[i]);
}
int numWritten = 0;
unsigned isStart = 1;
unsigned RSSI = 0;
unsigned CHAN = (isControl) ? 0x01f : 0x00;
len = len*2*sizeof(short);
int numPkts = (int) ceil((float)len/(float)504);
unsigned isEnd = (numPkts < 2);
uint32_t *outPkt = new uint32_t[128*numPkts];
int pktNum = 0;
while (numWritten < len) {
// pkt is pointer to start of a USB packet
uint32_t *pkt = outPkt + pktNum*128;
isEnd = (len - numWritten <= 504);
unsigned payloadLen = ((len - numWritten) < 504) ? (len-numWritten) : 504;
pkt[0] = (isStart << 12 | isEnd << 11 | (RSSI & 0x3f) << 5 | CHAN) << 16 | payloadLen;
pkt[1] = timestamp & 0x0ffffffffll;
memcpy(pkt+2,buf+(numWritten/sizeof(short)),payloadLen);
numWritten += payloadLen;
timestamp += payloadLen/2/sizeof(short);
isStart = 0;
pkt[0] = host_to_usrp_u32(pkt[0]);
pkt[1] = host_to_usrp_u32(pkt[1]);
pktNum++;
}
m_uTx->write((const void*) outPkt,sizeof(uint32_t)*128*numPkts,NULL);
delete[] outPkt;
samplesWritten += len/2/sizeof(short);
return len/2/sizeof(short);
#else
int retVal = len;
memcpy(loopbackBuffer+loopbackBufferSize,buf,sizeof(short)*2*len);
samplesWritten += retVal;
loopbackBufferSize += retVal*2;
return retVal;
#endif
}
bool USRPDevice::updateAlignment(TIMESTAMP timestamp)
{
#ifndef SWLOOPBACK
short data[] = {0x00,0x02,0x00,0x00};
uint32_t *wordPtr = (uint32_t *) data;
*wordPtr = host_to_usrp_u32(*wordPtr);
bool tmpUnderrun;
if (writeSamples((short *) data,1,&tmpUnderrun,timestamp & 0x0ffffffffll,true)) {
pingTimestamp = timestamp;
return true;
}
return false;
#else
return true;
#endif
}
#ifndef SWLOOPBACK
bool USRPDevice::setTxFreq(double wFreq)
{
usrp_tune_result result;
if (m_uTx->tune(txSubdevSpec.side, m_dbTx, wFreq, &result)) {
LOG(INFO) << "set TX: " << wFreq << std::endl
<< " baseband freq: " << result.baseband_freq << std::endl
<< " DDC freq: " << result.dxc_freq << std::endl
<< " residual freq: " << result.residual_freq;
return true;
}
else {
LOG(ERROR) << "set TX: " << wFreq << "failed" << std::endl
<< " baseband freq: " << result.baseband_freq << std::endl
<< " DDC freq: " << result.dxc_freq << std::endl
<< " residual freq: " << result.residual_freq;
return false;
}
}
bool USRPDevice::setRxFreq(double wFreq)
{
usrp_tune_result result;
if (m_uRx->tune(0, m_dbRx, wFreq, &result)) {
LOG(INFO) << "set RX: " << wFreq << std::endl
<< " baseband freq: " << result.baseband_freq << std::endl
<< " DDC freq: " << result.dxc_freq << std::endl
<< " residual freq: " << result.residual_freq;
return true;
}
else {
LOG(ERROR) << "set RX: " << wFreq << "failed" << std::endl
<< " baseband freq: " << result.baseband_freq << std::endl
<< " DDC freq: " << result.dxc_freq << std::endl
<< " residual freq: " << result.residual_freq;
return false;
}
}
#else
bool USRPDevice::setTxFreq(double wFreq) { return true;};
bool USRPDevice::setRxFreq(double wFreq) { return true;};
#endif
RadioDevice *RadioDevice::make(double desiredSampleRate, bool skipRx)
{
return new USRPDevice(desiredSampleRate, skipRx);
}

View File

@ -1,192 +0,0 @@
/*
* Copyright 2008 Free Software Foundation, Inc.
*
* This software is distributed under the terms of the GNU Affero Public License.
* See the COPYING file in the main directory for details.
*
* This use of this software may be subject to additional restrictions.
* See the LEGAL file in the main directory for details.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _USRP_DEVICE_H_
#define _USRP_DEVICE_H_
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#ifdef HAVE_LIBUSRP_3_3 // [
# include <usrp/usrp_standard.h>
# include <usrp/usrp_bytesex.h>
# include <usrp/usrp_prims.h>
#else // HAVE_LIBUSRP_3_3 ][
# include "usrp_standard.h"
# include "usrp_bytesex.h"
# include "usrp_prims.h"
#endif // !HAVE_LIBUSRP_3_3 ]
#include <sys/time.h>
#include <math.h>
#include <string>
#include <iostream>
#include "../Transceiver52M/radioDevice.h"
/** Define types which are not defined in libusrp-3.1 */
#ifndef HAVE_LIBUSRP_3_2
#include <boost/shared_ptr.hpp>
typedef boost::shared_ptr<usrp_standard_tx> usrp_standard_tx_sptr;
typedef boost::shared_ptr<usrp_standard_rx> usrp_standard_rx_sptr;
#endif // HAVE_LIBUSRP_3_2
/** A class to handle a USRP rev 4, with a two RFX900 daughterboards */
class USRPDevice : public RadioDevice {
private:
static const double masterClockRate;///< the USRP clock rate
double desiredSampleRate; ///< the desired sampling rate
usrp_standard_rx_sptr m_uRx; ///< the USRP receiver
usrp_standard_tx_sptr m_uTx; ///< the USRP transmitter
db_base_sptr m_dbRx; ///< rx daughterboard
db_base_sptr m_dbTx; ///< tx daughterboard
usrp_subdev_spec rxSubdevSpec;
usrp_subdev_spec txSubdevSpec;
double actualSampleRate; ///< the actual USRP sampling rate
unsigned int decimRate; ///< the USRP decimation rate
unsigned long long samplesRead; ///< number of samples read from USRP
unsigned long long samplesWritten; ///< number of samples sent to USRP
bool started; ///< flag indicates USRP has started
bool skipRx; ///< set if USRP is transmit-only.
static const unsigned int currDataSize_log2 = 18;
static const unsigned long currDataSize = (1 << currDataSize_log2);
short *data;
unsigned long dataStart;
unsigned long dataEnd;
TIMESTAMP timeStart;
TIMESTAMP timeEnd;
bool isAligned;
short *currData; ///< internal data buffer when reading from USRP
TIMESTAMP currTimestamp; ///< timestamp of internal data buffer
unsigned currLen; ///< size of internal data buffer
TIMESTAMP timestampOffset; ///< timestamp offset b/w Tx and Rx blocks
TIMESTAMP latestWriteTimestamp; ///< timestamp of most recent ping command
TIMESTAMP pingTimestamp; ///< timestamp of most recent ping response
static const TIMESTAMP PINGOFFSET = 272; ///< undetermined delay b/w ping response timestamp and true receive timestamp
unsigned long hi32Timestamp;
unsigned long lastPktTimestamp;
double rxGain;
#ifdef SWLOOPBACK
short loopbackBuffer[1000000];
int loopbackBufferSize;
double samplePeriod;
struct timeval startTime;
struct timeval lastReadTime;
bool firstRead;
#endif
public:
/** Object constructor */
USRPDevice (double _desiredSampleRate, bool skipRx);
/** Instantiate the USRP */
bool open();
/** Start the USRP */
bool start();
/** Stop the USRP */
bool stop();
/** Set priority not supported */
void setPriority() { return; }
/**
Read samples from the USRP.
@param buf preallocated buf to contain read result
@param len number of samples desired
@param overrun Set if read buffer has been overrun, e.g. data not being read fast enough
@param timestamp The timestamp of the first samples to be read
@param underrun Set if USRP does not have data to transmit, e.g. data not being sent fast enough
@param RSSI The received signal strength of the read result
@return The number of samples actually read
*/
int readSamples(short *buf, int len, bool *overrun,
TIMESTAMP timestamp = 0xffffffff,
bool *underrun = NULL,
unsigned *RSSI = NULL);
/**
Write samples to the USRP.
@param buf Contains the data to be written.
@param len number of samples to write.
@param underrun Set if USRP does not have data to transmit, e.g. data not being sent fast enough
@param timestamp The timestamp of the first sample of the data buffer.
@param isControl Set if data is a control packet, e.g. a ping command
@return The number of samples actually written
*/
int writeSamples(short *buf, int len, bool *underrun,
TIMESTAMP timestamp = 0xffffffff,
bool isControl = false);
/** Update the alignment between the read and write timestamps */
bool updateAlignment(TIMESTAMP timestamp);
/** Set the transmitter frequency */
bool setTxFreq(double wFreq);
/** Set the receiver frequency */
bool setRxFreq(double wFreq);
inline TIMESTAMP initialWriteTimestamp() { return 0; }
inline TIMESTAMP initialReadTimestamp() { return 0; }
inline double fullScaleInputValue() { return 13500.0; }
inline double fullScaleOutputValue() { return 9450.0; }
inline double setRxGain(double dB);
inline double getRxGain(void) { return rxGain; }
inline double maxRxGain(void);
inline double minRxGain(void);
inline double setTxGain(double dB);
inline double maxTxGain(void);
inline double minTxGain(void);
/** Return internal status values */
inline double getTxFreq() { return 0;}
inline double getRxFreq() { return 0;}
inline double getSampleRate() {return actualSampleRate;}
inline double numberRead() { return samplesRead; }
inline double numberWritten() { return samplesWritten;}
};
#endif // _USRP_DEVICE_H_

View File

@ -1,90 +0,0 @@
/*
* Copyright 2008, 2009 Free Software Foundation, Inc.
*
* This software is distributed under the terms of the GNU Affero Public License.
* See the COPYING file in the main directory for details.
*
* This use of this software may be subject to additional restrictions.
* See the LEGAL file in the main directory for details.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdint.h>
#include <stdio.h>
#include "Transceiver.h"
#include <Logger.h>
#include <Configuration.h>
using namespace std;
ConfigurationTable gConfig;
int main(int argc, char *argv[]) {
// Configure logger.
if (argc>1) gLogInit(argv[1]);
else gLogInit("INFO");
if (argc>2) gSetLogFile(argv[2]);
RadioDevice *usrp = RadioDevice::make(400e3);
if (!usrp->open()) {
cerr << "Device open failed. Exiting..." << endl;
exit(1);
}
TIMESTAMP timestamp;
usrp->setTxFreq(890.0e6);
usrp->setRxFreq(890.0e6);
usrp->start();
LOG(INFO) << "Looping...";
bool underrun;
//short data[]={0x00,0x02};
usrp->updateAlignment(20000);
usrp->updateAlignment(21000);
int numpkts = 2;
short data2[156*2*numpkts];
for (int i = 0; i < 156*numpkts; i++) {
data2[i<<1] = 10000;//4096*cos(2*3.14159*(i % 126)/126);
data2[(i<<1) + 1] = 10000;//4096*sin(2*3.14159*(i % 126)/126);
}
for (int i = 0; i < 1; i++)
usrp->writeSamples((short*) data2,156*numpkts,&underrun,102000+i*1000);
timestamp = 19000;
while (1) {
short readBuf[512*2];
int rd = usrp->readSamples(readBuf,512,&underrun,timestamp);
if (rd) {
LOG(INFO) << "rcvd. data@:" << timestamp;
/*for (int i = 0; i < 512; i++) {
uint32_t *wordPtr = (uint32_t *) &readBuf[2*i];
*wordPtr = usrp_to_host_u32(*wordPtr);
printf ("%d: %d %d\n", timestamp+i,readBuf[2*i],readBuf[2*i+1]);
} */
timestamp += rd;
}
}
}

View File

@ -1,431 +0,0 @@
/*
* Copyright 2008, 2009 Free Software Foundation, Inc.
*
* This software is distributed under the terms of the GNU Affero Public License.
* See the COPYING file in the main directory for details.
*
* This use of this software may be subject to additional restrictions.
* See the LEGAL file in the main directory for details.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//#define NDEBUG
#include "config.h"
#include "radioInterface.h"
#include <Logger.h>
GSM::Time VectorQueue::nextTime() const
{
GSM::Time retVal;
mLock.lock();
while (mQ.size()==0) mWriteSignal.wait(mLock);
retVal = mQ.top()->time();
mLock.unlock();
return retVal;
}
RadioInterface::RadioInterface(RadioDevice *wUsrp,
int wReceiveOffset,
int wSamplesPerSymbol,
GSM::Time wStartTime)
{
underrun = false;
sendHistory = new signalVector(INHISTORY);
rcvHistory = NULL;
sendBuffer = NULL;
rcvBuffer = NULL;
sendLPF = NULL;
rcvLPF = NULL;
mOn = false;
usrp = wUsrp;
receiveOffset = wReceiveOffset;
samplesPerSymbol = wSamplesPerSymbol;
mClock.set(wStartTime);
powerScaling = 1.0;
}
RadioInterface::~RadioInterface(void) {
if (sendBuffer!=NULL) delete sendBuffer;
if (rcvBuffer!=NULL) delete rcvBuffer;
if (sendHistory!=NULL) delete sendHistory;
if (rcvHistory!=NULL) delete rcvHistory;
if (sendLPF!=NULL) delete sendLPF;
if (rcvLPF!=NULL) delete rcvLPF;
mTransmitFIFO.clear();
mReceiveFIFO.clear();
}
double RadioInterface::fullScaleInputValue(void) {
return usrp->fullScaleInputValue();
}
double RadioInterface::fullScaleOutputValue(void) {
return usrp->fullScaleOutputValue();
}
void RadioInterface::setPowerAttenuation(double atten)
{
double rfGain, digAtten;
rfGain = usrp->setTxGain(usrp->maxTxGain() - atten);
digAtten = atten - usrp->maxTxGain() + rfGain;
if (digAtten < 1.0)
powerScaling = 1.0;
else
powerScaling = 1.0/sqrt(pow(10, (digAtten/10.0)));
}
short *RadioInterface::USRPifyVector(signalVector &wVector)
{
short *retVector = new short[2*wVector.size()];
signalVector::iterator itr = wVector.begin();
short *shortItr = retVector;
while (itr < wVector.end()) {
*shortItr++ = itr->real();
*shortItr++ = itr->imag();
itr++;
}
return retVector;
}
signalVector *RadioInterface::unUSRPifyVector(short *shortVector, int numSamples)
{
signalVector *newVector = new signalVector(numSamples);
signalVector::iterator itr = newVector->begin();
short *shortItr = shortVector;
while (itr < newVector->end()) {
*itr++ = Complex<float>(*shortItr, *(shortItr+1));
shortItr += 2;
}
return newVector;
}
bool started = false;
#define POLYPHASESPAN 10
void RadioInterface::pushBuffer(void) {
if (sendBuffer->size() < INCHUNK) {
return;
}
int numChunks = sendBuffer->size()/INCHUNK;
signalVector* truncatedBuffer = new signalVector(numChunks*INCHUNK);
sendBuffer->segmentCopyTo(*truncatedBuffer,0,numChunks*INCHUNK);
if (!sendLPF) {
int P = OUTRATE; int Q = INRATE;
float cutoffFreq = (P < Q) ? (1.0/(float) Q) : (1.0/(float) P);
sendLPF = createLPF(cutoffFreq,651,P);
}
// resample data to USRP sample rate
signalVector *inputVector = new signalVector(*sendHistory,*truncatedBuffer);
signalVector *resampledVector = polyphaseResampleVector(*inputVector,
OUTRATE,
INRATE,sendLPF);
delete inputVector;
// Set transmit gain and power here.
scaleVector(*resampledVector, powerScaling * usrp->fullScaleInputValue());
short *resampledVectorShort = USRPifyVector(*resampledVector);
// start the USRP when we actually have data to send to the USRP.
if (!started) {
started = true;
LOG(INFO) << "Starting USRP";
usrp->start();
LOG(DEBUG) << "USRP started";
usrp->updateAlignment(10000);
usrp->updateAlignment(10000);
}
// send resampleVector
writingRadioLock.lock();
int samplesWritten = usrp->writeSamples(resampledVectorShort+OUTHISTORY*2,
(resampledVector->size()-OUTHISTORY),
&underrun,
writeTimestamp);
//LOG(DEEPDEBUG) << "writeTimestamp: " << writeTimestamp << ", samplesWritten: " << samplesWritten;
writeTimestamp += (TIMESTAMP) samplesWritten;
wroteRadioSignal.signal();
writingRadioLock.unlock();
LOG(DEEPDEBUG) << "converted " << truncatedBuffer->size()
<< " transceiver samples into " << samplesWritten
<< " radio samples ";
delete resampledVector;
delete []resampledVectorShort;
// update the history of sent data
truncatedBuffer->segmentCopyTo(*sendHistory,truncatedBuffer->size()-INHISTORY,
INHISTORY);
// update the buffer, i.e. keep the samples we didn't send
signalVector *tmp = sendBuffer;
sendBuffer = new signalVector(sendBuffer->size()-truncatedBuffer->size());
tmp->segmentCopyTo(*sendBuffer,truncatedBuffer->size(),
sendBuffer->size());
delete tmp;
delete truncatedBuffer;
}
void RadioInterface::pullBuffer(void)
{
writingRadioLock.lock();
// These timestamps are in samples @ 400 kHz.
while (readTimestamp > writeTimestamp - (TIMESTAMP) 2*OUTCHUNK) {
LOG(DEEPDEBUG) << "waiting..." << readTimestamp << " " << writeTimestamp;
wroteRadioSignal.wait(writingRadioLock);
//wroteRadioSignal.wait(writingRadioLock,1);
}
writingRadioLock.unlock();
bool localUnderrun;
// receive receiveVector
short* shortVector = new short[OUTCHUNK*2];
int samplesRead = usrp->readSamples(shortVector,OUTCHUNK,&overrun,readTimestamp,&localUnderrun);
underrun |= localUnderrun;
readTimestamp += (TIMESTAMP) samplesRead;
while (samplesRead < OUTCHUNK) {
int oldSamplesRead = samplesRead;
samplesRead += usrp->readSamples(shortVector+2*samplesRead,
OUTCHUNK-samplesRead,
&overrun,
readTimestamp,
&localUnderrun);
underrun |= localUnderrun;
readTimestamp += (TIMESTAMP) (samplesRead - oldSamplesRead);
}
signalVector *receiveVector = unUSRPifyVector(shortVector,samplesRead);
delete []shortVector;
if (!rcvLPF) {
int P = INRATE; int Q = OUTRATE;
float cutoffFreq = (P < Q) ? (1.0/(float) Q) : (1.0/(float) P);
rcvLPF = createLPF(cutoffFreq,961,P);
}
signalVector *retVector = NULL;
if (!rcvHistory) {
rcvHistory = new signalVector(OUTHISTORY);
rcvHistory->fill(0);
}
// resample received data to multiple of GSM symbol rate
signalVector inputVector(*rcvHistory,*receiveVector);
retVector = polyphaseResampleVector(inputVector,
INRATE,OUTRATE,rcvLPF);
// push sampled data to back of receive buffer
signalVector *tmp = retVector;
retVector = new signalVector(retVector->size()-INHISTORY);
tmp->segmentCopyTo(*retVector,INHISTORY,tmp->size()-INHISTORY);
delete tmp;
LOG(DEEPDEBUG) << "converted " << receiveVector->size()
<< " radio samples into " << retVector->size()
<< " transceiver samples ";
// update history of received data
receiveVector->segmentCopyTo(*rcvHistory,receiveVector->size()-OUTHISTORY,OUTHISTORY);
delete receiveVector;
if (rcvBuffer) {
signalVector *tmp = rcvBuffer;
rcvBuffer = new signalVector(*tmp,*retVector);
delete tmp;
delete retVector;
}
else
rcvBuffer = retVector;
}
bool RadioInterface::tuneTx(double freq)
{
if (mOn) return false;
return usrp->setTxFreq(freq);
}
bool RadioInterface::tuneRx(double freq)
{
if (mOn) return false;
return usrp->setRxFreq(freq);
}
double RadioInterface::setRxGain(double dB)
{
if (usrp)
return usrp->setRxGain(dB);
else
return -1;
}
double RadioInterface::getRxGain(void)
{
if (usrp)
return usrp->getRxGain();
else
return -1;
}
void RadioInterface::start()
{
LOG(INFO) << "starting radio interface...";
writeTimestamp = 20000;
readTimestamp = 20000;
mTransmitRadioServiceLoopThread.start((void* (*)(void*))TransmitRadioServiceLoopAdapter,
(void*)this);
mReceiveRadioServiceLoopThread.start((void* (*)(void*))ReceiveRadioServiceLoopAdapter,
(void*)this);
mAlignRadioServiceLoopThread.start((void * (*)(void*))AlignRadioServiceLoopAdapter,
(void*)this);
mOn = true;
LOG(DEBUG) << "radio interface started!";
}
void *TransmitRadioServiceLoopAdapter(RadioInterface *radioInterface)
{
while (1) {
radioInterface->driveTransmitRadio();
pthread_testcancel();
}
return NULL;
}
void *ReceiveRadioServiceLoopAdapter(RadioInterface *radioInterface)
{
radioInterface->setPriority();
while (1) {
radioInterface->driveReceiveRadio();
pthread_testcancel();
}
return NULL;
}
void *AlignRadioServiceLoopAdapter(RadioInterface *radioInterface)
{
while (1) {
radioInterface->alignRadio();
pthread_testcancel();
}
return NULL;
}
void RadioInterface::alignRadio() {
sleep(60);
usrp->updateAlignment(writeTimestamp+ (TIMESTAMP) 10000);
}
void RadioInterface::driveTransmitRadio() {
radioVector *radioBurst = NULL;
radioBurst = mTransmitFIFO.read();
LOG(DEEPDEBUG) << "transmitFIFO: read radio vector at time: " << radioBurst->time();
signalVector *newBurst = radioBurst;
if (sendBuffer) {
signalVector *tmp = sendBuffer;
sendBuffer = new signalVector(*sendBuffer,*newBurst);
delete tmp;
}
else
sendBuffer = new signalVector(*newBurst);
delete radioBurst;
pushBuffer();
}
void RadioInterface::driveReceiveRadio() {
pullBuffer();
if (!rcvBuffer) {
return;}
GSM::Time rcvClock = mClock.get();
rcvClock.decTN(receiveOffset);
unsigned tN = rcvClock.TN();
int rcvSz = rcvBuffer->size();
int readSz = 0;
const int symbolsPerSlot = gSlotLen + 8;
// while there's enough data in receive buffer, form received
// GSM bursts and pass up to Transceiver
// Using the 157-156-156-156 symbols per timeslot format.
while (rcvSz > (symbolsPerSlot + (tN % 4 == 0))*samplesPerSymbol) {
signalVector rxVector(rcvBuffer->begin(),
readSz,
(symbolsPerSlot + (tN % 4 == 0))*samplesPerSymbol);
GSM::Time tmpTime = rcvClock;
if (rcvClock.FN() >= 0) {
LOG(DEEPDEBUG) << "FN: " << rcvClock.FN();
radioVector* rxBurst = new radioVector(rxVector,tmpTime);
mReceiveFIFO.write(rxBurst);
}
mClock.incTN();
rcvClock.incTN();
if (mReceiveFIFO.size() >= 16) mReceiveFIFO.wait(8);
LOG(DEEPDEBUG) << "receiveFIFO: wrote radio vector at time: " << mClock.get() << ", new size: " << mReceiveFIFO.size() ;
readSz += (symbolsPerSlot+(tN % 4 == 0))*samplesPerSymbol;
rcvSz -= (symbolsPerSlot+(tN % 4 == 0))*samplesPerSymbol;
tN = rcvClock.TN();
}
signalVector *tmp = new signalVector(rcvBuffer->size()-readSz);
rcvBuffer->segmentCopyTo(*tmp,readSz,tmp->size());
delete rcvBuffer;
rcvBuffer = tmp;
}

View File

@ -1,240 +0,0 @@
/*
* Copyright 2008 Free Software Foundation, Inc.
*
* This software is distributed under the terms of the GNU Affero Public License.
* See the COPYING file in the main directory for details.
*
* This use of this software may be subject to additional restrictions.
* See the LEGAL file in the main directory for details.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "sigProcLib.h"
#include "../Transceiver52M/radioDevice.h"
#include "GSMCommon.h"
#include "Interthread.h"
/** samples per GSM symbol */
#define SAMPSPERSYM 1
/** parameters for polyphase resampling */
#define INRATE (65*SAMPSPERSYM)
#define OUTRATE (96)
#define INHISTORY (INRATE*2)
#define OUTHISTORY (OUTRATE*2)
#define INCHUNK (INRATE*9)
#define OUTCHUNK (OUTRATE*9)
/** class used to organize GSM bursts by GSM timestamps */
class radioVector : public signalVector {
private:
GSM::Time mTime; ///< the burst's GSM timestamp
public:
/** constructor */
radioVector(const signalVector& wVector,
GSM::Time& wTime): signalVector(wVector),mTime(wTime) {};
/** timestamp read and write operators */
GSM::Time time() const { return mTime;}
void time(const GSM::Time& wTime) { mTime = wTime;}
/** comparison operator, used for sorting */
bool operator>(const radioVector& other) const {return mTime > other.mTime;}
};
/** a priority queue of radioVectors, i.e. GSM bursts, sorted so that earliest element is at top */
class VectorQueue : public InterthreadPriorityQueue<radioVector> {
public:
/** the top element of the queue */
GSM::Time nextTime() const;
};
/** a FIFO of radioVectors */
class VectorFIFO : public InterthreadQueueWithWait<radioVector> {};
/** the basestation clock class */
class RadioClock {
private:
GSM::Time mClock;
Mutex mLock;
Signal updateSignal;
public:
/** Set clock */
void set(const GSM::Time& wTime) { mLock.lock(); mClock = wTime; updateSignal.signal(); mLock.unlock();}
//void set(const GSM::Time& wTime) { mLock.lock(); mClock = wTime; updateSignal.broadcast(); mLock.unlock();}
/** Increment clock */
void incTN() { mLock.lock(); mClock.incTN(); updateSignal.signal(); mLock.unlock();}
//void incTN() { mLock.lock(); mClock.incTN(); updateSignal.broadcast(); mLock.unlock();}
/** Get clock value */
GSM::Time get() { mLock.lock(); GSM::Time retVal = mClock; mLock.unlock(); return retVal;}
/** Wait until clock has changed */
void wait() {mLock.lock(); updateSignal.wait(mLock,1); mLock.unlock();}
// FIXME -- If we take away the timeout, a lot of threads don't start. Why?
//void wait() {mLock.lock(); updateSignal.wait(mLock); mLock.unlock();}
};
/** class to interface the transceiver with the USRP */
class RadioInterface {
private:
Thread mTransmitRadioServiceLoopThread; ///< thread that handles transmission of GSM bursts
Thread mReceiveRadioServiceLoopThread; ///< thread that handles reception of GSM bursts
Thread mAlignRadioServiceLoopThread; ///< thread that synchronizes transmit and receive sections
VectorFIFO mTransmitFIFO; ///< FIFO that holds transmit bursts
VectorFIFO mReceiveFIFO; ///< FIFO that holds receive bursts
signalVector* sendHistory; ///< block of previous transmitted samples
signalVector* rcvHistory; ///< block of previous received samples
RadioDevice *usrp; ///< the USRP object
signalVector* sendBuffer; ///< block of samples to be transmitted
signalVector* rcvBuffer; ///< block of received samples to be processed
signalVector* sendLPF; ///< polyphase filter for resampling transmit bursts
signalVector* rcvLPF; ///< polyphase filter for resampling receive bursts
mutable Signal wroteRadioSignal; ///< signal that indicates samples sent to USRP
mutable Mutex writingRadioLock; ///< mutex to lock receive thread when transmit thread is writing
bool underrun; ///< indicates writes to USRP are too slow
bool overrun; ///< indicates reads from USRP are too slow
TIMESTAMP writeTimestamp; ///< sample timestamp of next packet written to USRP
TIMESTAMP readTimestamp; ///< sample timestamp of next packet read from USRP
RadioClock mClock; ///< the basestation clock!
int samplesPerSymbol; ///< samples per GSM symbol
int receiveOffset; ///< offset b/w transmit and receive GSM timestamps, in timeslots
bool mOn; ///< indicates radio is on
float powerScaling;
/** format samples to USRP */
short *USRPifyVector(signalVector &wVector);
/** format samples from USRP */
signalVector *unUSRPifyVector(short *shortVector, int numSamples);
/** push GSM bursts into the transmit buffer */
void pushBuffer(void);
/** pull GSM bursts from the receive buffer */
void pullBuffer(void);
public:
/** start the interface */
void start();
/** constructor */
RadioInterface(RadioDevice* wUsrp = NULL,
int receiveOffset = 3,
int wSamplesPerSymbol = SAMPSPERSYM,
GSM::Time wStartTime = GSM::Time(0));
/** destructor */
~RadioInterface();
/** check for underrun, resets underrun value */
bool isUnderrun() { bool retVal = underrun; underrun = false; return retVal;}
/** attach an existing USRP to this interface */
void attach(RadioDevice *wUsrp) {if (!mOn) usrp = wUsrp;}
/** return the transmit FIFO */
VectorFIFO* transmitFIFO() { return &mTransmitFIFO;}
/** return the receive FIFO */
VectorFIFO* receiveFIFO() { return &mReceiveFIFO;}
/** return the basestation clock */
RadioClock* getClock(void) { return &mClock;};
/** set transmit frequency */
bool tuneTx(double freq);
/** set receive frequency */
bool tuneRx(double freq);
/** set receive gain */
double setRxGain(double dB);
/** get receive gain */
double getRxGain(void);
/** drive transmission of GSM bursts */
void driveTransmitRadio();
/** drive reception of GSM bursts */
void driveReceiveRadio();
void setPowerAttenuation(double atten);
/** returns the full-scale transmit amplitude **/
double fullScaleInputValue();
/** returns the full-scale receive amplitude **/
double fullScaleOutputValue();
/** set thread priority */
void setPriority() { usrp->setPriority(); }
protected:
/** drive synchronization of Tx/Rx of USRP */
void alignRadio();
/** reset the interface */
void reset();
friend void *TransmitRadioServiceLoopAdapter(RadioInterface*);
friend void *ReceiveRadioServiceLoopAdapter(RadioInterface*);
friend void *AlignRadioServiceLoopAdapter(RadioInterface*);
};
/** transmit thread loop */
void *TransmitRadioServiceLoopAdapter(RadioInterface*);
/** receive thread loop */
void *ReceiveRadioServiceLoopAdapter(RadioInterface*);
/** synchronization thread loop */
void *AlignRadioServiceLoopAdapter(RadioInterface*);

File diff suppressed because one or more lines are too long

View File

@ -1,66 +0,0 @@
/*
* Copyright 2008, 2009 Free Software Foundation, Inc.
*
* This software is distributed under the terms of the GNU Affero Public License.
* See the COPYING file in the main directory for details.
*
* This use of this software may be subject to additional restrictions.
* See the LEGAL file in the main directory for details.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Transceiver.h"
#include "GSMCommon.h"
#include <time.h>
#include <Logger.h>
#include <Configuration.h>
ConfigurationTable gConfig;
using namespace std;
int main(int argc, char *argv[]) {
// Configure logger.
if (argc<2) {
cerr << argv[0] << " <logLevel> [logFilePath]" << endl;
cerr << "Log levels are ERROR, ALARM, WARN, NOTICE, INFO, DEBUG, DEEPDEBUG" << endl;
exit(0);
}
gLogInit(argv[1]);
if (argc>2) gSetLogFile(argv[2]);
srandom(time(NULL));
RadioDevice *usrp = RadioDevice::make(400.0e3);
if (!usrp->open()) {
cerr << "Device open failed. Exiting..." << endl;
exit(1);
}
RadioInterface* radio = new RadioInterface(usrp,3);
Transceiver *trx = new Transceiver(5700,"127.0.0.1",SAMPSPERSYM,GSM::Time(3,0),radio);
trx->transmitFIFO(radio->transmitFIFO());
trx->receiveFIFO(radio->receiveFIFO());
trx->start();
//int i = 0;
while(1) { sleep(1); }//i++; if (i==60) break;}
}

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

View File

@ -1,384 +0,0 @@
/*
* Copyright 2008 Free Software Foundation, Inc.
*
* This software is distributed under the terms of the GNU Affero Public License.
* See the COPYING file in the main directory for details.
*
* This use of this software may be subject to additional restrictions.
* See the LEGAL file in the main directory for details.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Vector.h"
#include "Complex.h"
#include "GSMTransfer.h"
using namespace GSM;
/** Indicated signalVector symmetry */
enum Symmetry {
NONE = 0,
ABSSYM = 1
};
/** Convolution type indicator */
enum ConvType {
FULL_SPAN = 0,
OVERLAP_ONLY = 1,
START_ONLY = 2,
WITH_TAIL = 3,
NO_DELAY = 4,
UNDEFINED = 255
};
/** the core data structure of the Transceiver */
class signalVector: public Vector<complex>
{
private:
Symmetry symmetry; ///< the symmetry of the vector
bool realOnly; ///< true if vector is real-valued, not complex-valued
public:
/** Constructors */
signalVector(int dSize=0, Symmetry wSymmetry = NONE):
Vector<complex>(dSize),
realOnly(false)
{
symmetry = wSymmetry;
};
signalVector(complex* wData, size_t start,
size_t span, Symmetry wSymmetry = NONE):
Vector<complex>(NULL,wData+start,wData+start+span),
realOnly(false)
{
symmetry = wSymmetry;
};
signalVector(const signalVector &vec1, const signalVector &vec2):
Vector<complex>(vec1,vec2),
realOnly(false)
{
symmetry = vec1.symmetry;
};
signalVector(const signalVector &wVector):
Vector<complex>(wVector.size()),
realOnly(false)
{
wVector.copyTo(*this);
symmetry = wVector.getSymmetry();
};
/** symmetry operators */
Symmetry getSymmetry() const { return symmetry;};
void setSymmetry(Symmetry wSymmetry) { symmetry = wSymmetry;};
/** real-valued operators */
bool isRealOnly() const { return realOnly;};
void isRealOnly(bool wOnly) { realOnly = wOnly;};
};
/** Convert a linear number to a dB value */
float dB(float x);
/** Convert a dB value into a linear value */
float dBinv(float x);
/** Compute the energy of a vector */
float vectorNorm2(const signalVector &x);
/** Compute the average power of a vector */
float vectorPower(const signalVector &x);
/** Setup the signal processing library */
void sigProcLibSetup(int samplesPerSymbol);
/** Destroy the signal processing library */
void sigProcLibDestroy(void);
/**
Convolve two vectors.
@param a,b The vectors to be convolved.
@param c, A preallocated vector to hold the convolution result.
@param spanType The type/span of the convolution.
@return The convolution result.
*/
signalVector* convolve(const signalVector *a,
const signalVector *b,
signalVector *c,
ConvType spanType);
/**
Generate the GSM pulse.
@param samplesPerSymbol The number of samples per GSM symbol.
@param symbolLength The size of the pulse.
@return The GSM pulse.
*/
signalVector* generateGSMPulse(int samplesPerSymbol,
int symbolLength);
/**
Frequency shift a vector.
@param y The frequency shifted vector.
@param x The vector to-be-shifted.
@param freq The digital frequency shift
@param startPhase The starting phase of the oscillator
@param finalPhase The final phase of the oscillator
@return The frequency shifted vector.
*/
signalVector* frequencyShift(signalVector *y,
signalVector *x,
float freq = 0.0,
float startPhase = 0.0,
float *finalPhase=NULL);
/**
Correlate two vectors.
@param a,b The vectors to be correlated.
@param c, A preallocated vector to hold the correlation result.
@param spanType The type/span of the correlation.
@return The correlation result.
*/
signalVector* correlate(signalVector *a,
signalVector *b,
signalVector *c,
ConvType spanType);
/** Operate soft slicer on real-valued portion of vector */
bool vectorSlicer(signalVector *x);
/** GMSK modulate a GSM burst of bits */
signalVector *modulateBurst(const BitVector &wBurst,
const signalVector &gsmPulse,
int guardPeriodLength,
int samplesPerSymbol);
/** Sinc function */
float sinc(float x);
/** Delay a vector */
void delayVector(signalVector &wBurst,
float delay);
/** Add two vectors in-place */
bool addVector(signalVector &x,
signalVector &y);
/** Generate a vector of gaussian noise */
signalVector *gaussianNoise(int length,
float variance = 1.0,
complex mean = complex(0.0));
/**
Given a non-integer index, interpolate a sample.
@param inSig The signal from which to interpolate.
@param ix The index.
@return The interpolated signal value.
*/
complex interpolatePoint(const signalVector &inSig,
float ix);
/**
Given a correlator output, locate the correlation peak.
@param rxBurst The correlator result.
@param peakIndex Pointer to value to receive interpolated peak index.
@param avgPower Power to value to receive mean power.
@return Peak value.
*/
complex peakDetect(const signalVector &rxBurst,
float *peakIndex,
float *avgPwr);
/**
Apply a scalar to a vector.
@param x The vector of interest.
@param scale The scalar.
*/
void scaleVector(signalVector &x,
complex scale);
/**
Add a constant offset to a vecotr.
@param x The vector of interest.
@param offset The offset.
*/
void offsetVector(signalVector &x,
complex offset);
/**
Generate a modulated GSM midamble, stored within the library.
@param gsmPulse The GSM pulse used for modulation.
@param samplesPerSymbol The number of samples per GSM symbol.
@param TSC The training sequence [0..7]
@return Success.
*/
bool generateMidamble(signalVector &gsmPulse,
int samplesPerSymbol,
int TSC);
/**
Generate a modulated RACH sequence, stored within the library.
@param gsmPulse The GSM pulse used for modulation.
@param samplesPerSymbol The number of samples per GSM symbol.
@return Success.
*/
bool generateRACHSequence(signalVector &gsmPulse,
int samplesPerSymbol);
/**
Energy detector, checks to see if received burst energy is above a threshold.
@param rxBurst The received GSM burst of interest.
@param windowLength The number of burst samples used to compute burst energy
@param detectThreshold The detection threshold, a linear value.
@param avgPwr The average power of the received burst.
@return True if burst energy is above threshold.
*/
bool energyDetect(signalVector &rxBurst,
unsigned windowLength,
float detectThreshold,
float *avgPwr = NULL);
/**
RACH correlator/detector.
@param rxBurst The received GSM burst of interest.
@param detectThreshold The threshold that the received burst's post-correlator SNR is compared against to determine validity.
@param samplesPerSymbol The number of samples per GSM symbol.
@param amplitude The estimated amplitude of received RACH burst.
@param TOA The estimate time-of-arrival of received RACH burst.
@return True if burst SNR is larger that the detectThreshold value.
*/
bool detectRACHBurst(signalVector &rxBurst,
float detectThreshold,
int samplesPerSymbol,
complex *amplitude,
float* TOA);
/**
Normal burst correlator, detector, channel estimator.
@param rxBurst The received GSM burst of interest.
@param detectThreshold The threshold that the received burst's post-correlator SNR is compared against to determine validity.
@param samplesPerSymbol The number of samples per GSM symbol.
@param amplitude The estimated amplitude of received RACH burst.
@param TOA The estimate time-of-arrival of received RACH burst.
@param requestChannel Set to true if channel estimation is desired.
@param channelResponse The estimated channel.
@param channelResponseOffset The time offset b/w the first sample of the channel response and the reported TOA.
@return True if burst SNR is larger that the detectThreshold value.
*/
bool analyzeTrafficBurst(signalVector &rxBurst,
unsigned TSC,
float detectThreshold,
int samplesPerSymbol,
complex *amplitude,
float *TOA,
bool requestChannel = false,
signalVector** channelResponse = NULL,
float *channelResponseOffset = NULL);
/**
Decimate a vector.
@param wVector The vector of interest.
@param decimationFactor The amount of decimation, i.e. the decimation factor.
@return The decimated signal vector.
*/
signalVector *decimateVector(signalVector &wVector,
int decimationFactor);
/**
Demodulates a received burst using a soft-slicer.
@param rxBurst The burst to be demodulated.
@param gsmPulse The GSM pulse.
@param samplesPerSymbol The number of samples per GSM symbol.
@param channel The amplitude estimate of the received burst.
@param TOA The time-of-arrival of the received burst.
@return The demodulated bit sequence.
*/
SoftVector *demodulateBurst(const signalVector &rxBurst,
const signalVector &gsmPulse,
int samplesPerSymbol,
complex channel,
float TOA);
/**
Creates a simple Kaiser-windowed low-pass FIR filter.
@param cutoffFreq The digital 3dB bandwidth of the filter.
@param filterLen The number of taps in the filter.
@param gainDC The DC gain of the filter.
@return The desired LPF
*/
signalVector *createLPF(float cutoffFreq,
int filterLen,
float gainDC = 1.0);
/**
Change sampling rate of a vector via polyphase resampling.
@param wVector The vector to be resampled.
@param P The numerator, i.e. the amount of upsampling.
@param Q The denominator, i.e. the amount of downsampling.
@param LPF An optional low-pass filter used in the resampling process.
@return A vector resampled at P/Q of the original sampling rate.
*/
signalVector *polyphaseResampleVector(signalVector &wVector,
int P, int Q,
signalVector *LPF);
/**
Change the sampling rate of a vector via linear interpolation.
@param wVector The vector to be resampled.
@param expFactor Ratio of new sampling rate/original sampling rate.
@param endPoint ???
@return A vector resampled a expFactor*original sampling rate.
*/
signalVector *resampleVector(signalVector &wVector,
float expFactor,
complex endPoint);
/**
Design the necessary filters for a decision-feedback equalizer.
@param channelResponse The multipath channel that we're mitigating.
@param SNRestimate The signal-to-noise estimate of the channel, a linear value
@param Nf The number of taps in the feedforward filter.
@param feedForwardFilter The designed feed forward filter.
@param feedbackFilter The designed feedback filter.
@return True if DFE can be designed.
*/
bool designDFE(signalVector &channelResponse,
float SNRestimate,
int Nf,
signalVector **feedForwardFilter,
signalVector **feedbackFilter);
/**
Equalize/demodulate a received burst via a decision-feedback equalizer.
@param rxBurst The received burst to be demodulated.
@param TOA The time-of-arrival of the received burst.
@param samplesPerSymbol The number of samples per GSM symbol.
@param w The feed forward filter of the DFE.
@param b The feedback filter of the DFE.
@return The demodulated bit sequence.
*/
SoftVector *equalizeBurst(signalVector &rxBurst,
float TOA,
int samplesPerSymbol,
signalVector &w,
signalVector &b);

View File

@ -108,7 +108,6 @@ AC_CONFIG_FILES([\
GSM/Makefile \
SIP/Makefile \
SMS/Makefile \
Transceiver/Makefile \
Transceiver52M/Makefile \
TRXManager/Makefile \
CLI/Makefile \