create repo

master
王路远 2018-01-29 22:11:44 -08:00
commit 9173a31acc
40 changed files with 6982 additions and 0 deletions

7
README.md Normal file
View File

@ -0,0 +1,7 @@
# Pluto-Network
本项目使用 Pluto SDR 设备实现了简化版的停止等待和滑动窗口两个可靠传输协议。可在两台设备之间任意的传输文字或文件。
需要使用两台 Pluto 设备,一台作为接收机,另外一台作为发射机,并分别运行相应的代码。具体的实验报告发布在了我的 Blog 上。
如果有疑问或发现了什么问题,欢迎发邮件联系我。我的邮箱是 e@wangluyuan.cc

View File

@ -0,0 +1,119 @@
function [rStr, crcResult] = bpsk_rx_func(rxdata)
global cyc;
seq_sync = tx_gen_m_seq([1 0 0 0 0 0 1]);
local_sync = tx_modulate(seq_sync, 'BPSK');
rx_signal=rxdata;
%% matched filtering
fir = rcosdesign(1,128,4);
rx_sig_filter = upfirdn(rx_signal,fir,1);
%% normalization
c1=max([abs(real(rx_sig_filter.')),abs(imag(rx_sig_filter.'))]);
rx_sig_norm=rx_sig_filter ./c1;
%% sampling synchronization
[time_error,rx_sig_down]=rx_timing_recovery(rx_sig_norm.');
% rx_sig_down=rx_sig_norm(1:4:end).';
%% package search
[rx_frame,cor_abs,th_max,index_s]=rx_package_search(rx_sig_down,local_sync,703);
%% coarse freq synchronization
coarse_sync_seq=rx_frame(1:8);
[deltaf1,out_signal1] = rx_freq_sync(coarse_sync_seq,4,rx_frame);
%% first fine freq synchronization
fine_sync_seq_1=out_signal1(1:120);
[deltaf2,out_signal2] = rx_freq_sync(fine_sync_seq_1,2,out_signal1);
%% second fine freq synchronization
fine_sync_seq_2=out_signal2(1:120);
[deltaf3,out_signal3]=rx_freq_sync(fine_sync_seq_2,2,out_signal2);
deltaf=deltaf1+deltaf2+deltaf3;
%% initial phase estimate
[out_signal4,ang]=rx_phase_sync(out_signal3,local_sync);
%% phase track
rx_no_syn_seq=out_signal4(127+1:end);
[out_signal6,phase_curve]=rx_phase_track(rx_no_syn_seq);
%% delete pilot
out_signal7=rx_delete_pilot(out_signal6);
%% time domain equalize
out_signal8=rx_time_equalize(out_signal7);
%% signal demod
[soft_bits_out,evm] = rx_bpsk_demod(out_signal8);
Si=[1 1 0 1 1 0 0];
m=0;
for i=1:length(soft_bits_out)
[c,Si]=descramble(soft_bits_out(i),Si);
m=m+1;
y(m)=c;
end
soft_bits_out=y;
%% crc32 check
ret=crc32(soft_bits_out(1:length(soft_bits_out)-32)).';
crc_bits_32=soft_bits_out(length(soft_bits_out)-31:length(soft_bits_out));
crc_outputs=sum(xor(ret,crc_bits_32),2);
if crc_outputs==0
crc_32='YES';
crcResult = 1;
% disp(char(b.'));
% disp(char(y));
% disp(char(soft_bits_out(1:end-32)));
else
crc_32='NO';
crcResult = 0;
end
cyc=cyc+1;
msg=soft_bits_out(1:end-32).';
w = [128 64 32 16 8 4 2 1];
Nbits = numel(msg);
Ny = Nbits/8;
y = zeros(1,Ny);
for i = 0:Ny-1
y(i+1) = w*msg(8*i+(1:8));
end
a=[y zeros(1,4)];
b=reshape(a,64,1);
%b=reshape(a,16,4);
%% display
%{
%figure(2);clf;
%subplot(231);
plot(real(rx_signal),'r');
hold on;
%plot(imag(rx_signal),'b');
grid on;
title('rx original signal');
%subplot(232);
pwelch(rx_signal,[],[],[],40e6,'centered','psd');
%}
% text(0.15,1.0,['帧同步序号:',b.']);
receivedStr = deblank(char(b.'));
rStr = receivedStr;
%{
%disp(receivedStr);
%disp(char(b.'));
% plot(phase_curve);
axis square;
subplot(233);
plot(real(out_signal8),imag(out_signal8),'b*');
title('constellation');
axis([-1.5 1.5 -1.5 1.5]);
axis square;
subplot(234);
plot(phase_curve+pi*2);
title('phae track');
%subplot(235);
text(0.15,1.0,['帧同步序号:',num2str(index_s,5)]);%,'FontSize',12
text(0.15,0.8,['频偏估计值:',num2str(deltaf/1e3,3),'KHz']);
text(0.15,0.6,['调制模式:', 'BPSK']);
text(0.15,0.4,['数据长度:', '500','bytes']);
text(0.15,0.2,['evm', num2str(evm.*100,3),'%']);
text(0.15,0.0,['crc\_32', crc_32]);
axis off;
% figure(2)
% plot(cor_abs);
%}
end

View File

@ -0,0 +1,23 @@
function ret = crc32(bits)
poly = [1 de2bi(hex2dec('EDB88320'), 32)]';
bits = bits(:);
% Flip first 32 bits
bits(1:32) = 1 - bits(1:32);
% Add 32 zeros at the back
bits = [bits; zeros(32,1)];
% Initialize remainder to 0
rem = zeros(32,1);
% Main compution loop for the CRC32
for i = 1:length(bits)
rem = [rem; bits(i)]; %#ok<AGROW>
if rem(1) == 1
rem = xor(rem,poly);%mod(rem + poly, 2);
end
rem = rem(2:33);
end
% Flip the remainder before returning it
ret = 1 - rem;
end

View File

@ -0,0 +1,22 @@
subplot(241);
plot(real(rx_signal),'r');
hold on;
plot(imag(rx_signal),'b');
grid on;
title('接收端时域信号');
subplot(242);
plot(time_error,'b')
grid on;
title('定时同步误差曲线');
subplot(243);
plot((th_max-127:th_max+1),cor_abs(th_max-127:th_max+1),'b');
grid on;
title('帧同步曲线');
subplot(244);
plot(phase_curve,'b');
grid on;
title('相位校正曲线');
subplot(245);
plot(real(out_signal6),imag(out_signal6),'b.');
grid on;
axis square;

View File

@ -0,0 +1,11 @@
function [ a,Si ] = descramble( a,Si )
for i=1:length(a)
b(i)=xor(Si(4),Si(7));
b(i)=xor(b(i),a(i));
c(i)=a(i);
a(i)=b(i);
Si(2:7)=Si(1:6);
Si(1)=c(i);
end
end

View File

@ -0,0 +1,19 @@
function [soft_bits,evm] = rx_bpsk_demod(rx_symbols)
evm_real=zeros(1,length(rx_symbols));
evm_image=imag(rx_symbols);
soft_bits = real(rx_symbols);
for i=1:length(rx_symbols)
if(soft_bits(i)>0)
evm_real(i)=soft_bits(i)-1;
soft_bits(i)=1;
else
evm_real(i)=soft_bits(i)-(-1);
soft_bits(i)=0;
end
end
evm=(evm_real.^2+evm_image.^2).^0.5;
evm=sum(evm)/length(evm);

View File

@ -0,0 +1,20 @@
function out_signal = rx_channel_est(signal,uw)
% MMSE频域均衡函数
% 输入序列x为去掉CP后的接受序列设其长度为L;
% uw为系统中使用的独特字序列,长度为uw_num;
% 输出序列y为经过FDE后的输出序列,长度为L-uw_num。
%
L = size(signal,2); %求输入序列的长度;
uw_num = size(uw,2); %求独特字的长度;
sigstmp(1,:) = signal(1,(uw_num+1):end); %提取数据信息流;
uwstmp(1,:) = signal(1,1:uw_num); %提取独特字序列;
H = fft(uwstmp)./fft(uw);
h = ifft(H);
u = [h,zeros(1,L-2*uw_num)];
U = fft(u);
W = conj(U)./(U.*conj(U));
Sig = fft(sigstmp);
Y = W.*Sig;
out_signal = ifft(Y);
end

View File

@ -0,0 +1,20 @@
function out_signal = rx_delete_pilot(signal)
Nr=64+8;
Ns=length(signal)/Nr;
signal=reshape(signal,Nr,Ns);
signal=signal.';
% N=size(signal,2);
% out_signal=[];
% for i=9:N
% out_signal1=signal(:,i);
% out_signal=[out_signal out_signal1];
% end
% out_signal=out_signal(:)';
out_signal=signal(:,(9:end));
out_signal=reshape(out_signal,1,128*4);
c=max([abs(real(out_signal)),abs(imag(out_signal))]);
out_signal=out_signal ./c;
end

View File

@ -0,0 +1,20 @@
function [deltaf,out_signal] = rx_freq_sync(sync_samples,Num,samples_package)
Tchip=1/10000000;
len=length(samples_package);
N=length(sync_samples)/Num;
L0=length(sync_samples);
zr=sync_samples.^2;
for m=1:N
r0(m)=mean(zr(1+m:L0).*conj(zr(1:L0-m)));
end
deltaf=angle(sum(r0))/(pi*(N+1)*Tchip)/2;
freq_offset=deltaf;
out_signal=samples_package(1:end).*exp(-1i*2*pi*freq_offset*(1:len)*Tchip);
end

View File

@ -0,0 +1,19 @@
function [out_signal,cor_abs,bo,index_s] = rx_package_search(signal,local_sync,len_frame)
signali=(real(signal)>0)*2-1;
signalq=(imag(signal)>0)*2-1;
signalo=signali+1i*signalq;
L=length(signal);
N=length(local_sync);
for i=N:L
cor_abs(i)=abs(signalo(i-N+1:i)*local_sync');
end
[~,bo]=max(cor_abs(1:length(cor_abs)/2));
index_s=bo-N+1;
index_e=index_s+len_frame-1;
out_signal=signal(index_s:index_e);
end

View File

@ -0,0 +1,15 @@
function [out_signal,cor_abs,bo,index_s] = rx_package_search(signal,local_sync,len_frame)
L=length(signal);
N=length(local_sync);
for i=N:L
cor_abs(i)=abs(signal(i-N+1:i)*local_sync');
end
[~,bo]=max(cor_abs(1:length(cor_abs)/2));
index_s=bo-N+1;
index_e=index_s+len_frame-1;
out_signal=signal(index_s:index_e);
end

View File

@ -0,0 +1,14 @@
function [out_signal,ang] = rx_phase_sync(signal_freq_sync,local_seq)
len=length(local_seq);
L=len;
for i=1:L-1
cor(i)=signal_freq_sync(i).*conj(local_seq(L-i));
end
ang=angle(mean(cor))-pi;
out_signal=signal_freq_sync.*exp(-1i*ang);
end

View File

@ -0,0 +1,17 @@
function [signal,phase_curve] = rx_phase_track(signal)
% local_pilot=ones(1,4)-2;
local_pilot=[1 -1 1 -1 -1 1 -1 1];
% local_pilot=[1 -1 1 -1 -1 1 -1 1];
idx=0;
N=64+8;
phase_curve=0;
for i=1:N:length(signal)-N
temp=signal(i:(i+N-1));
% rx_pilot=temp(N-7:end);
rx_pilot = temp(1:8);
[~,ang]=rx_phase_sync(rx_pilot,local_pilot);
idx=idx+1;
phase_curve(idx)=ang;
signal(i:end)=signal(i:end).*exp(-1i*ang);
end

View File

@ -0,0 +1,35 @@
function [soft_bits_out,evm] = rx_qpsk_demod(rx_symbols)
rx_symbols=rx_symbols./sqrt(2);
soft_bits = zeros(2,length(rx_symbols));
evm_real=zeros(1,length(rx_symbols));
evm_image=zeros(1,length(rx_symbols));
bit0 = real(rx_symbols);
for i=1:length(rx_symbols)
if(bit0(i)>0)
evm_real(i)=bit0(i)-1/sqrt(2);
bit0(i)=1;
else
evm_real(i)=bit0(i)-(-1/sqrt(2));
bit0(i)=0;
end
end
bit1 = imag(rx_symbols);
for j=1:length(rx_symbols)
if(bit1(j)>0)
evm_image(j)=bit1(j)-1/sqrt(2);
bit1(j)=1;
else
evm_image(j)=bit1(j)-(-1/sqrt(2));
bit1(j)=0;
end
end
evm=(evm_real.^2+evm_image.^2).^0.5;
evm=sum(evm)/length(evm);
soft_bits(1,:) = bit0;
soft_bits(2,:) = bit1;
soft_bits_out = soft_bits(:)';

View File

@ -0,0 +1,25 @@
function out_signal = rx_time_equalize(signal)
signal=[zeros(1,13) signal zeros(1,5)];
N=length(signal);
M=10; %均衡器的阶数
W=zeros(M+1,1); %初始化抽头系数
W(ceil(((M+1)/2)))=1; %初始化
U=1e-3; %设置收敛步长
Y1=zeros(M+1,1);
e=zeros(1,(N-M)); %初始化误差
R1=1;
R2=1;
for mmm=1:4
for n=1:(N-M)
Y1=signal(n+M:-1:n).';
YK(n)=W.'*Y1; %均衡器的输出
YI=real(YK(n));
YQ=imag(YK(n));
EI=YI*(YI^2-R1);
EQ=YQ*(YQ^2-R2);
e(n)=EI+EQ*sqrt(-1);
W=W-U*e(n)*conj(Y1);%调节抽头系数
end
end
out_signal=YK(9:end);
end

View File

@ -0,0 +1,94 @@
function [time_error,iq] = rx_timing_recovery(signal)
N=ceil((length(signal))/4);
Ns=4*N; %总的采样点数
bt=2e-2/1.3;
c1=8/3*bt;
c2=32/9*bt*bt;
w=[0.5,zeros(1,N-1)]; %环路滤波器输出寄存器初值设为0.5
n=[0.9,zeros(1,Ns-1)]; %NCO寄存器初值设为0.9
n_temp=[n(1),zeros(1,Ns-1)];
u=[0.6,zeros(1,2*N-1)]; %NCO输出的定时分数间隔寄存器初值设为0.6
out_signal_I=zeros(1,2*N); %I路内插后的输出数据
out_signal_Q=zeros(1,2*N); %Q路内插后的输出数据
time_error=zeros(1,N); %Gardner提取的时钟误差寄存器
ik=time_error;
qk=time_error;
k=1; %用来表示Ti时间序号,指示u,yI,yQ
ms=1; %用来指示T的时间序号,用来指示a,b以及w
strobe=zeros(1,Ns);
aI=real(signal);
bQ=imag(signal);
ns=length(aI)-1;
i=1;
while(i<ns)
n_temp(i+1)=n(i)-w(ms);
if(n_temp(i+1)>0)
n(i+1)=n_temp(i+1);
else
n(i+1)=mod(n_temp(i+1),1);
%内插滤波器模块
FI1=0.5*aI(i+2)-0.5*aI(i+1)-0.5*aI(i)+0.5*aI(i-1);
FI2=1.5*aI(i+1)-0.5*aI(i+2)-0.5*aI(i)-0.5*aI(i-1);
FI3=aI(i);
out_signal_I(k)=(FI1*u(k)+FI2)*u(k)+FI3;
FQ1=0.5*bQ(i+2)-0.5*bQ(i+1)-0.5*bQ(i)+0.5*bQ(i-1);
FQ2=1.5*bQ(i+1)-0.5*bQ(i+2)-0.5*bQ(i)-0.5*bQ(i-1);
FQ3=bQ(i);
out_signal_Q(k)=(FQ1*u(k)+FQ2)*u(k)+FQ3;
strobe(k)=mod(k,2);
%时钟误差提取模块采用的是Gardner算法
if(strobe(k)==0)
%取出插值数据
ik(ms)=out_signal_I(k);
qk(ms)=out_signal_Q(k);
%每个数据符号计算一次时钟误差
if(k>2)
Ia=(out_signal_I(k)+out_signal_I(k-2))/2;
Qa=(out_signal_Q(k)+out_signal_Q(k-2))/2;
time_error(ms)=[out_signal_I(k-1)-Ia]*(out_signal_I(k)-out_signal_I(k-2))+[out_signal_Q(k-1)-Qa]*(out_signal_Q(k)-out_signal_Q(k-2));
else
time_error(ms)=(out_signal_I(k-1)*out_signal_I(k)+out_signal_Q(k-1)*out_signal_Q(k));
end
%环路滤波器,每个数据符号计算一次环路滤波器输出
if(ms>1)
w(ms+1)=w(ms)+c1*(time_error(ms)-time_error(ms-1))+c2*time_error(ms-1);
else
w(ms+1)=w(ms)+c1*time_error(ms)+c2*time_error(ms);
end
ms=ms+1;
end
k=k+1;
u(k)=n(i)/w(ms);
end
i=i+1;
end
iq=ik+1i*qk;
c1=max([abs(real(iq)),abs(imag(iq))]);
iq=iq ./c1;
% figure(1);
% subplot(311);
% plot(u);
% xlabel('运算点数');
% ylabel('分数间隔');
% grid on;
% subplot(312);
% plot(time_error);
% xlabel('运算点数');
% ylabel('定时误差');
% grid on;
% subplot(313);
% plot(w);
% xlabel('运算点数');
% ylabel('环路滤波器输出');
% grid on;
end

View File

@ -0,0 +1,17 @@
function seq = tx_gen_m_seq(m_init)
%MSRG模件抽头型结构
connections =m_init;
m=length(connections);%移位寄存器的级数
L=2^m-1;%m序列长度
registers=[zeros(1,m-1) 1];%寄存器初始化
seq(1)=registers(m);%m序列的第一位取移位寄存器移位输出的值
for i=2:L,
new_reg_cont(1)=connections(1)*seq(i-1);%新寄存器的第一位等于连接值乘寄存器最后一位
for j=2:m,
new_reg_cont(j)=rem(registers(j-1)+connections(j)*seq(i-1),2);%其他位等于前边的寄存器值加上连接值乘寄存器最后一位
end
registers=new_reg_cont;
seq(i)=registers(m);%经过一次循环寄存器输出一位得到m序列的其他位
end
end

View File

@ -0,0 +1,65 @@
function mod_symbols = tx_modulate(bits_in, modulation)
full_len = length(bits_in);
% BPSK modulation
if ~isempty(findstr(modulation, 'BPSK'))
% Angle [pi/4 -3*pi/4] corresponds to
% Gray code vector [0 1], respectively.
table=exp(j*[0 -pi]); % generates BPSK symbols
table=table([1 0]+1); % Gray code mapping pattern for BPSK symbols
inp=bits_in;
mod_symbols=table(inp+1); % maps transmitted bits into BPSK symbols
% QPSK modulation
elseif ~isempty(findstr(modulation, 'QPSK'))
% Angle [pi/4 3*pi/4 -3*pi/4 -pi/4] corresponds to
% Gray code vector [00 10 11 01], respectively.
table=exp(j*[-3/4*pi 3/4*pi 1/4*pi -1/4*pi]); % generates QPSK symbols
table=table([0 1 3 2]+1); % Gray code mapping pattern for QPSK symbols
inp=reshape(bits_in,2,full_len/2);
mod_symbols=table([2 1]*inp+1); % maps transmitted bits into QPSK symbols
% 16-QAM modulation
elseif ~isempty(findstr(modulation, '16QAM'))
% generates 16QAM symbols
m=1;
for k=-3:2:3
for l=-3:2:3
table(m) = (k+j*l)/sqrt(10); % power normalization
m=m+1;
end;
end;
table=table([0 1 3 2 4 5 7 6 12 13 15 14 8 9 11 10]+1); % Gray code mapping pattern for 8-PSK symbols
inp=reshape(bits_in,4,full_len/4);
mod_symbols=table([8 4 2 1]*inp+1); % maps transmitted bits into 16QAM symbols
% 64-QAM modulation
elseif ~isempty(findstr(modulation, '64QAM'))
% generates 64QAM symbols
m=1;
for k=-7:2:7
for l=-7:2:7
table(m) = (k+j*l)/sqrt(42); % power normalization
m=m+1;
end;
end;
table=table([[ 0 1 3 2 7 6 4 5]...
8+[ 0 1 3 2 7 6 4 5]...
24+[ 0 1 3 2 7 6 4 5]...
16+[ 0 1 3 2 7 6 4 5]...
56+[ 0 1 3 2 7 6 4 5]...
48+[ 0 1 3 2 7 6 4 5]...
32+[ 0 1 3 2 7 6 4 5]...
40+[ 0 1 3 2 7 6 4 5]]+1);
inp=reshape(bits_in,6,full_len/6);
mod_symbols=table([32 16 8 4 2 1]*inp+1); % maps transmitted bits into 64QAM symbol
else
error('Unimplemented modulation');
end

View File

@ -0,0 +1,36 @@
function txdata = bpsk_tx_func(msgStr)
%% train sequence
seq_sync=tx_gen_m_seq([1 0 0 0 0 0 1]);
sync_symbols=tx_modulate(seq_sync, 'BPSK');
%% message 128-4 byte
%msgStr = 'this is a testing message';
for k = length(msgStr)+1 :60
msgStr = [msgStr, char(0)];
end
%% string to bits
mst_bits=str_to_bits(msgStr);
%% crc32
ret=crc32(mst_bits);
inf_bits=[mst_bits ret.'];
%% scramble
scramble_int=[1,1,0,1,1,0,0];
sym_bits=scramble(scramble_int, inf_bits);
%% modulate
mod_symbols=tx_modulate(sym_bits, 'BPSK');
%% insert pilot
data_symbols=insert_pilot(mod_symbols);
trans_symbols=[sync_symbols data_symbols];
%% srrc
fir=rcosdesign(1,128,4);
tx_frame=upfirdn(trans_symbols,fir,4);
tx_frame=[tx_frame, zeros(1,2e3)];
txdata = tx_frame.';
%% display
%{
plot(real(tx_frame));
hold on
plot(imag(tx_frame));
%}
end

View File

@ -0,0 +1,24 @@
function ret = crc32(bits)
poly = [1 de2bi(hex2dec('EDB88320'), 32)]';
bits = bits(:);
% Flip first 32 bits
bits(1:32) = 1 - bits(1:32);
% Add 32 zeros at the back
bits = [bits; zeros(32,1)];
% Initialize remainder to 0
rem = zeros(32,1);
% Main compution loop for the CRC32
for i = 1:length(bits)
rem = [rem; bits(i)]; %#ok<AGROW>
if rem(1) == 1
rem = xor(rem,poly);%mod(rem + poly, 2);
end
rem = rem(2:33);
end
% Flip the remainder before returning it
ret = 1 - rem;
end

View File

@ -0,0 +1,21 @@
function out_signal = insert_pilot(mod_symbols)
Nr=64;
Ns=length(mod_symbols)/Nr;
temp=reshape(mod_symbols,Ns,Nr);
pilot=repmat(ones(1,4),Ns,1);
pilot=[1 -1 1 -1 -1 1 -1 1];
pilot=repmat(pilot,Ns,1);
last=[pilot temp];
last=last.';
bo=last(:).';
% if len_mod ~= 0
% remain=mod_symbols(end-len_mod+1:end);
% out_signal=[bo remain];
% else
out_signal=bo;
% end
end

View File

@ -0,0 +1,11 @@
%scrambling x^7+x^4+1
function scramble_bits=scramble(scramble_int,data_bits)
A=scramble_int;
for i=1:length(data_bits)
a=xor(A(4),A(7));
a=xor(a,data_bits(i));
data_bits(i)=a;
A(2:7)=A(1:6);
A(1)=a;
end
scramble_bits=data_bits;

View File

@ -0,0 +1,8 @@
function msg_bits = str_to_bits(msgStr)
msgBin = de2bi(int8(msgStr),8,'left-msb');
len = size(msgBin,1).*size(msgBin,2);
msg_bits = reshape(double(msgBin).',len,1).';
end

View File

@ -0,0 +1,17 @@
function seq = tx_gen_m_seq(m_init)
%MSRG模件抽头型结构
connections =m_init;
m=length(connections);%移位寄存器的级数
L=2^m-1;%m序列长度
registers=[zeros(1,m-1) 1];%寄存器初始化
seq(1)=registers(m);%m序列的第一位取移位寄存器移位输出的值
for i=2:L,
new_reg_cont(1)=connections(1)*seq(i-1);%新寄存器的第一位等于连接值乘寄存器最后一位
for j=2:m,
new_reg_cont(j)=rem(registers(j-1)+connections(j)*seq(i-1),2);%其他位等于前边的寄存器值加上连接值乘寄存器最后一位
end
registers=new_reg_cont;
seq(i)=registers(m);%经过一次循环寄存器输出一位得到m序列的其他位
end
end

View File

@ -0,0 +1,65 @@
function mod_symbols = tx_modulate(bits_in, modulation)
full_len = length(bits_in);
% BPSK modulation
if ~isempty(findstr(modulation, 'BPSK'))
% Angle [pi/4 -3*pi/4] corresponds to
% Gray code vector [0 1], respectively.
table=exp(j*[0 -pi]); % generates BPSK symbols
table=table([1 0]+1); % Gray code mapping pattern for BPSK symbols
inp=bits_in;
mod_symbols=table(inp+1); % maps transmitted bits into BPSK symbols
% QPSK modulation
elseif ~isempty(findstr(modulation, 'QPSK'))
% Angle [pi/4 3*pi/4 -3*pi/4 -pi/4] corresponds to
% Gray code vector [00 10 11 01], respectively.
table=exp(j*[-3/4*pi 3/4*pi 1/4*pi -1/4*pi]); % generates QPSK symbols
table=table([0 1 3 2]+1); % Gray code mapping pattern for QPSK symbols
inp=reshape(bits_in,2,full_len/2);
mod_symbols=table([2 1]*inp+1); % maps transmitted bits into QPSK symbols
mod_symbols=mod_symbols.*sqrt(2);
% 16-QAM modulation
elseif ~isempty(findstr(modulation, '16QAM'))
% generates 16QAM symbols
m=1;
for k=-3:2:3
for l=-3:2:3
table(m) = (k+j*l)/sqrt(10); % power normalization
m=m+1;
end;
end;
table=table([0 1 3 2 4 5 7 6 12 13 15 14 8 9 11 10]+1); % Gray code mapping pattern for 8-PSK symbols
inp=reshape(bits_in,4,full_len/4);
mod_symbols=table([8 4 2 1]*inp+1); % maps transmitted bits into 16QAM symbols
% 64-QAM modulation
elseif ~isempty(findstr(modulation, '64QAM'))
% generates 64QAM symbols
m=1;
for k=-7:2:7
for l=-7:2:7
table(m) = (k+j*l)/sqrt(42); % power normalization
m=m+1;
end;
end;
table=table([[ 0 1 3 2 7 6 4 5]...
8+[ 0 1 3 2 7 6 4 5]...
24+[ 0 1 3 2 7 6 4 5]...
16+[ 0 1 3 2 7 6 4 5]...
56+[ 0 1 3 2 7 6 4 5]...
48+[ 0 1 3 2 7 6 4 5]...
32+[ 0 1 3 2 7 6 4 5]...
40+[ 0 1 3 2 7 6 4 5]]+1);
inp=reshape(bits_in,6,full_len/6);
mod_symbols=table([32 16 8 4 2 1]*inp+1); % maps transmitted bits into 64QAM symbol
else
error('Unimplemented modulation');
end

View File

@ -0,0 +1,11 @@
function inf_bits=tx_prbs15(packetlength)
h1=[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1];
for i=1:packetlength*8-32
h2(i)=h1(15);
a=xor(h1(15),h1(14));
h1(2:15)=h1(1:14);
h1(1)=a;
end
ret=crc32(h2);
inf_bits=[h2 ret.'];
end

View File

@ -0,0 +1,158 @@
clearvars -except times;close all;warning off;
set(0,'defaultfigurecolor','w');
addpath ..\..\library
addpath ..\..\library\matlab
ip = '192.168.2.1';
addpath BPSK\transmitter
addpath BPSK\receiver
%% Transmit and Receive using MATLAB libiio
% System Object Configuration
s = iio_sys_obj_matlab; % MATLAB libiio Constructor
s.ip_address = ip;
s.dev_name = 'ad9361';
s.in_ch_no = 2;
s.out_ch_no = 2;
s.in_ch_size = 42568;%length(txdata);
s.out_ch_size = 42568.*8;%length(txdata).*8;
s = s.setupImpl();
input = cell(1, s.in_ch_no + length(s.iio_dev_cfg.cfg_ch));
output = cell(1, s.out_ch_no + length(s.iio_dev_cfg.mon_ch));
% Set the attributes of AD9361
input{s.getInChannel('RX_LO_FREQ')} = 2e9;
input{s.getInChannel('RX_SAMPLING_FREQ')} = 40e6;
input{s.getInChannel('RX_RF_BANDWIDTH')} = 20e6;
input{s.getInChannel('RX1_GAIN_MODE')} = 'manual';%% slow_attack manual
input{s.getInChannel('RX1_GAIN')} = 10;
% input{s.getInChannel('RX2_GAIN_MODE')} = 'slow_attack';
% input{s.getInChannel('RX2_GAIN')} = 0;
input{s.getInChannel('TX_LO_FREQ')} = 1e9;
input{s.getInChannel('TX_SAMPLING_FREQ')} = 40e6;
input{s.getInChannel('TX_RF_BANDWIDTH')} = 20e6;
expectedSeqNum = 1;
allowedSeqNum = 5;
lastRecivedNum = 0;
window = {'','','','',''};
lastSeqNum = 0;
receivedStr = '';
while(1)
output = readRxData(s);
I = output{1};
Q = output{2};
Rx = I+1i*Q;
[rStr, crcResult] = bpsk_rx_func(Rx);
%disp(['received:',rStr]);
seq = rStr(1:3);
if crcResult == 1
%成功接收到消息,回复收到的帧序号
strToReply = '0';
disp(['received:',rStr]);
if seq== 'BYE'
strToReply = 'ACK';
txdata = bpsk_tx_func(strToReply);
txdata = round(txdata .* 2^14);
txdata=repmat(txdata, 8,1);
input{1} = real(txdata);
input{2} = imag(txdata);
for i = 1:10
writeTxData(s, input);
disp('send ack');
pause(0.1);
end
break;
end
seq = str2num(seq);
if expectedSeqNum < allowedSeqNum
if ((expectedSeqNum <= seq) && (seq<=allowedSeqNum))
index = seq - expectedSeqNum + 1;
window{index} = rStr;
end
else
if (expectedSeqNum <= seq) && (seq <= 10)
index = seq - expectedSeqNum + 1;
window{index} = rStr;
end
if (seq>=1) && (seq<=allowedSeqNum)
index = seq + 11 - expectedSeqNum;
window{index} = rStr;
end
end
if expectedSeqNum == seq
for j = 1:5
if isempty(window{j})
expectedSeqNum = expectedSeqNum + j - 1;
allowedSeqNum = allowedSeqNum + j - 1;
lastRecivedNum = str2num(window{j-1}(1:3));
if expectedSeqNum>10
expectedSeqNum = expectedSeqNum - 10;
end
if allowedSeqNum>10
allowedSeqNum = allowedSeqNum - 10;
end
tempWindow={'','','','',''};
if j== 5
window= tempWindow;
else
for m = j:5
tempWindow{m-j+1}=window{m};
end
window = tempWindow;
end
break
end
disp(['!!!success received:',window{j}]);
receivedStr = [receivedStr, window{j}(4:end)];
if j==5 && ~isempty(window{j})
lastRecivedNum = str2num(window{j}(1:3));
window = {'','','','',''};
expectedSeqNum = expectedSeqNum + 5;
allowedSeqNum = allowedSeqNum +5;
if expectedSeqNum>10
expectedSeqNum = expectedSeqNum -10;
end
if allowedSeqNum>10
allowedSeqNum = allowedSeqNum - 10;
end
end
end
disp(['i receive', num2str(lastRecivedNum)]);
strToReply = num2str(lastRecivedNum);
txdata = bpsk_tx_func(strToReply);
txdata = round(txdata .* 2^14);
txdata=repmat(txdata, 8,1);
input{1} = real(txdata);
input{2} = imag(txdata);
writeTxData(s, input);
else
strToReply = num2str(lastRecivedNum);
txdata = bpsk_tx_func(strToReply);
txdata = round(txdata .* 2^14);
txdata=repmat(txdata, 8,1);
input{1} = real(txdata);
input{2} = imag(txdata);
disp(['i receive ', num2str(lastRecivedNum)]);
writeTxData(s, input);
end
end
end
disp(receivedStr);
file = matlab.net.base64decode(receivedStr);
fid = fopen('received', 'wb+');
if fid>0
fwrite(fid, file);
end
fclose(fid);
% Read the RSSI attributes of both channels
rssi1 = output{s.getOutChannel('RX1_RSSI')};
% rssi2 = output{s.getOutChannel('RX2_RSSI')};
s.releaseImpl();

181
code/matlab/slideWindow-sender.m Executable file
View File

@ -0,0 +1,181 @@
clearvars -except times;close all;warning off;
set(0,'defaultfigurecolor','w');
addpath ..\..\library
addpath ..\..\library\matlab
ip = '192.168.2.1';
addpath BPSK\transmitter
addpath BPSK\receiver
%% Transmit and Receive using MATLAB libiio
% System Object Configuration
s = iio_sys_obj_matlab; % MATLAB libiio Constructor
s.ip_address = ip;
s.dev_name = 'ad9361';
s.in_ch_no = 2;
s.out_ch_no = 2;
s.in_ch_size = 42568;%length(txdata);
s.out_ch_size = 42568.*8;%length(txdata).*8;
s = s.setupImpl();
input = cell(1, s.in_ch_no + length(s.iio_dev_cfg.cfg_ch));
output = cell(1, s.out_ch_no + length(s.iio_dev_cfg.mon_ch));
% Set the attributes of AD9361
input{s.getInChannel('RX_LO_FREQ')} = 1e9;
input{s.getInChannel('RX_SAMPLING_FREQ')} = 40e6;
input{s.getInChannel('RX_RF_BANDWIDTH')} = 20e6;
input{s.getInChannel('RX1_GAIN_MODE')} = 'manual';%% slow_attack manual
input{s.getInChannel('RX1_GAIN')} = 10;
% input{s.getInChannel('RX2_GAIN_MODE')} = 'slow_attack';
% input{s.getInChannel('RX2_GAIN')} = 0;
input{s.getInChannel('TX_LO_FREQ')} = 2e9;
input{s.getInChannel('TX_SAMPLING_FREQ')} = 40e6;
input{s.getInChannel('TX_RF_BANDWIDTH')} = 20e6;
%strToSend = 'HomePod is a powerful speaker that sounds amazing and adapts to wherever its playing. Its the ultimate music authority, bringing together Apple Music and Siri to learn your taste in music. Its also an intelligent home assistant, capable of handling everyday tasks — and controlling your smart home. HomePod takes the listening experience to a whole new level. And thats just the beginning. We completely reimagined how music should sound in the home. HomePod combines Apple-engineered audio technology and advanced software to deliver the highest-fidelity sound throughout the room, anywhere its placed. This elegantly designed, compact speaker totally rocks the house. Setting up HomePod is quick and magical. Simply plug it in and your iOS device will detect it. Equipped with spatial awareness, HomePod automatically adjusts to give you optimal sound — wherever its placed. It can even hear your requests from across the room while loud songs are playing. All you need to do is enjoy your music. HomePod is great at playing your music. But it can also tell you the latest news, traffic, sports, and weather. Set reminders and tasks. Send messages. Hand off phone calls. And HomePod is a hub for controlling your smart home accessories — from a single light bulb to the whole house — with just your voice.';
fid = fopen('C:\Users\Berr\Desktop\ok.txt','rb');
bytes = fread(fid);
fclose(fid);
encoder = org.apache.commons.codec.binary.Base64;
strToSend = char(encoder.encode(bytes))';
%在每60个字符之前插入3位帧序号信息
%帧序号是窗口的两倍1-10
arrLength = ceil(length(strToSend)/57);
sendArray = cell(1,arrLength);
seqNum = 1;
for index = 1:arrLength
if seqNum < 10
seqNumStr = ['00', int2str(seqNum)];
else
seqNumStr = ['0', int2str(seqNum)];
end
if seqNum == 10
seqNum = 1;
else
seqNum = seqNum + 1;
end
if index*57 > length(strToSend)
sendArray(index) = {[seqNumStr,strToSend(index*57-56:length(strToSend))]};
else
sendArray(index) = {[seqNumStr,strToSend(index*57-56:index*57)]};
end
end
disp('start sending...');
disp(['totoal packet count: ', int2str(length(sendArray))]);
sendTime = clock;
%开始发送 - 滑动窗口
%窗口长度为5
startIndex = 1; %在sendArray上滑动发送窗口
lastSendIndex = 0;
receivedSeqNum = 0;
lastReceivedSeqNum = 0;
roundCount = 0; %序号回滚了几圈
while startIndex <= length(sendArray)
isTimeOut = 1;
while isTimeOut %超时自动重传
finishIndex = startIndex + 4;
if startIndex + 4 > length(sendArray)
finishIndex = length(sendArray);
end
for i = lastSendIndex+1 : finishIndex
disp(['sending: ', sendArray{i}]);
txdata = bpsk_tx_func(sendArray{i});
txdata = round(txdata .* 2^14);
txdata=repmat(txdata, 8,1);
input{1} = real(txdata);
input{2} = imag(txdata);
writeTxData(s, input); %发送数据
lastSendIndex = i;
pause(0.5);
end
t1 = clock;
isSlide = 0; %是否滑动
while 1
if etime(clock, t1) > 10 %超时
isTimeOut = 1;
disp('timeOut');
if ~isSlide
lastSendIndex = startIndex - 1;
end
break;
end
output = readRxData(s);
I = output{1};
Q = output{2};
Rx = I+1i*Q;
[rStr, crcResult] = bpsk_rx_func(Rx);
if crcResult == 1
disp(['receivedSeq: ', rStr]);
receivedSeqNum = str2num(rStr);
if receivedSeqNum < lastReceivedSeqNum
roundCount = roundCount + 1;
end
startIndex = receivedSeqNum + 1 + 10 * roundCount;
disp(['startIndex set to: ', int2str(startIndex)]);
disp(['progress: ', num2str(startIndex/length(sendArray))]);
if lastReceivedSeqNum ~= receivedSeqNum
isSlide = 1; %收到的序号变化,说明窗口滑动了
isTimeOut = 0;
lastReceivedSeqNum = receivedSeqNum;
break;
else
isSlide = 0;
end
end
end
end
end
disp('finished.');
timeSpand = etime(clock, sendTime);
disp(['time: ', num2str(timeSpand)]);
disp(['average speed: ', num2str(length(sendArray)*57*8/timeSpand), ' bps']);
%发送完毕,挥手再见
receivedACK = 0;
for i = 1:10 %发送十次再见,若十次还没有回应,自己关闭
if(receivedACK == 1)
break;
end
txdata = bpsk_tx_func('BYE');
txdata = round(txdata .* 2^14);
txdata=repmat(txdata, 8,1);
input{1} = real(txdata);
input{2} = imag(txdata);
writeTxData(s, input); %发送再见信息
disp('BYE');
pause(0.1);
sendTime = clock;
while(etime(clock, sendTime) < 10) %未超时一直监听回复的ACK
output = readRxData(s);
I = output{1};
Q = output{2};
Rx = I+1i*Q;
[rStr, crcResult] = bpsk_rx_func(Rx);
disp(['received:', rStr]);
if crcResult == 1 && strcmp(rStr, 'ACK')
receivedACK = 1; %收到ACK 关闭会话
break;
end
end
end
disp('Quit. Bye!');
rssi1 = output{s.getOutChannel('RX1_RSSI')};
s.releaseImpl();

177
code/matlab/stop&Wait-sender.m Executable file
View File

@ -0,0 +1,177 @@
clearvars -except times;close all;warning off;
set(0,'defaultfigurecolor','w');
addpath ..\..\library
addpath ..\..\library\matlab
ip = '192.168.2.1';
addpath BPSK\transmitter
addpath BPSK\receiver
%% Transmit and Receive using MATLAB libiio
% System Object Configuration
s = iio_sys_obj_matlab; % MATLAB libiio Constructor
s.ip_address = ip;
s.dev_name = 'ad9361';
s.in_ch_no = 2;
s.out_ch_no = 2;
s.in_ch_size = 42568;%length(txdata);
s.out_ch_size = 42568.*8;%length(txdata).*8;
s = s.setupImpl();
input = cell(1, s.in_ch_no + length(s.iio_dev_cfg.cfg_ch));
output = cell(1, s.out_ch_no + length(s.iio_dev_cfg.mon_ch));
% Set the attributes of AD9361
input{s.getInChannel('RX_LO_FREQ')} = 1e9;
input{s.getInChannel('RX_SAMPLING_FREQ')} = 40e6;
input{s.getInChannel('RX_RF_BANDWIDTH')} = 20e6;
input{s.getInChannel('RX1_GAIN_MODE')} = 'manual';%% slow_attack manual
input{s.getInChannel('RX1_GAIN')} = 10;
% input{s.getInChannel('RX2_GAIN_MODE')} = 'slow_attack';
% input{s.getInChannel('RX2_GAIN')} = 0;
input{s.getInChannel('TX_LO_FREQ')} = 2e9;
input{s.getInChannel('TX_SAMPLING_FREQ')} = 40e6;
input{s.getInChannel('TX_RF_BANDWIDTH')} = 20e6;
strToSend = 'We all know that rumor goes very fast from person to person. With the development of Internet, the infor '
%在每60个字符之前插入3位帧序号信息
arrLength = ceil(length(strToSend)/57);
sendArray = cell(1,arrLength);
seqNum = 0;
for index = 1:arrLength
seqNumStr = ['00', int2str(seqNum)];
if seqNum == 0
seqNum = 1;
else
seqNum = 0;
end
if index*57 > length(strToSend)
sendArray(index) = {[seqNumStr,strToSend(index*57-56:length(strToSend))]};
else
sendArray(index) = {[seqNumStr,strToSend(index*57-56:index*57)]};
end
end
%开始发送
seqNum = 0;
for index = 1:length(sendArray)
receivedACK = 0;
while(~receivedACK) %自动请求重传
disp(['sending num:', int2str(seqNum), 'context:', sendArray{index}]);
txdata = bpsk_tx_func(sendArray{index});
txdata = round(txdata .* 2^14);
txdata=repmat(txdata, 8,1);
input{1} = real(txdata);
input{2} = imag(txdata);
writeTxData(s, input); %发送数据
pause(0.1);
sendTime = clock;
while(etime(clock, sendTime) < 10) %未超时一直监听回复的ACK
output = readRxData(s);
I = output{1};
Q = output{2};
Rx = I+1i*Q;
[rStr, crcResult] = bpsk_rx_func(Rx);
disp(['received:', rStr]);
if crcResult == 1 && strcmp(rStr, int2str(seqNum))
receivedACK = 1; %收到ACK准备发送下一条
break;
end
end
end
if seqNum == 0
seqNum = 1;
else
seqNum = 0;
end
end
%发送完毕,挥手再见
receivedACK = 0;
for i = 1:10 %发送十次再见,若十次还没有回应,自己关闭
if(receivedACK == 1)
break;
end
txdata = bpsk_tx_func('BYE');
txdata = round(txdata .* 2^14);
txdata=repmat(txdata, 8,1);
input{1} = real(txdata);
input{2} = imag(txdata);
writeTxData(s, input); %发送再见信息
disp('BYE');
pause(0.1);
sendTime = clock;
while(etime(clock, sendTime) < 10) %未超时一直监听回复的ACK
output = readRxData(s);
I = output{1};
Q = output{2};
Rx = I+1i*Q;
[rStr, crcResult] = bpsk_rx_func(Rx);
disp(['received:', rStr]);
if crcResult == 1 && strcmp(rStr, 'ACK')
receivedACK = 1; %收到ACK 关闭会话
break;
end
end
end
%{
index = 1;
disp('[[sending:]]');
disp(strToSend);
disp('[[receiving:]]');
while(1)
for currentIndex = 1:length(sendArray)
%fprintf('txdata number %i ...\n',currentIndex);
isSuccess = 0;
%while(~isSuccess)
index = index+1;
txdata = bpsk_tx_func(sendArray{mod(index, length(sendArray))+1});
txdata = round(txdata .* 2^14);
txdata=repmat(txdata, 8,1);
%fprintf('Transmitting Data Block %i ...\n',currentIndex);
input{1} = real(txdata);
input{2} = imag(txdata);
writeTxData(s, input);
%{
output = readRxData(s);
%output = stepImpl(s, input);
%fprintf('Data Block %i Received...\n',currentIndex);
I = output{1};
Q = output{2};
Rx = I+1i*Q;
[rStr, crcResult] = bpsk_rx_func(Rx);%bpsk_rx_func(Rx(end/2:end));
if crcResult == 1
isSuccess = 1;
fprintf(rStr);
%disp(rStr);
end
%}
pause(0.1);
%end
end
end
%}
%fprintf('Transmission and reception finished\n');
% Read the RSSI attributes of both channels
rssi1 = output{s.getOutChannel('RX1_RSSI')};
% rssi2 = output{s.getOutChannel('RX2_RSSI')};
s.releaseImpl();

View File

@ -0,0 +1,180 @@
clearvars -except times;close all;warning off;
set(0,'defaultfigurecolor','w');
addpath ..\..\library
addpath ..\..\library\matlab
ip = '192.168.2.1';
addpath BPSK\transmitter
addpath BPSK\receiver
%% Transmit and Receive using MATLAB libiio
% System Object Configuration
s = iio_sys_obj_matlab; % MATLAB libiio Constructor
s.ip_address = ip;
s.dev_name = 'ad9361';
s.in_ch_no = 2;
s.out_ch_no = 2;
s.in_ch_size = 42568;%length(txdata);
s.out_ch_size = 42568.*8;%length(txdata).*8;
s = s.setupImpl();
input = cell(1, s.in_ch_no + length(s.iio_dev_cfg.cfg_ch));
output = cell(1, s.out_ch_no + length(s.iio_dev_cfg.mon_ch));
% Set the attributes of AD9361
input{s.getInChannel('RX_LO_FREQ')} = 2e9;
input{s.getInChannel('RX_SAMPLING_FREQ')} = 40e6;
input{s.getInChannel('RX_RF_BANDWIDTH')} = 20e6;
input{s.getInChannel('RX1_GAIN_MODE')} = 'manual';%% slow_attack manual
input{s.getInChannel('RX1_GAIN')} = 10;
% input{s.getInChannel('RX2_GAIN_MODE')} = 'slow_attack';
% input{s.getInChannel('RX2_GAIN')} = 0;
input{s.getInChannel('TX_LO_FREQ')} = 1e9;
input{s.getInChannel('TX_SAMPLING_FREQ')} = 40e6;
input{s.getInChannel('TX_RF_BANDWIDTH')} = 20e6;
expectedSeqNum = 0;
lastSeqNum = 0;
while(1)
output = readRxData(s);
I = output{1};
Q = output{2};
Rx = I+1i*Q;
[rStr, crcResult] = bpsk_rx_func(Rx);
disp(['received:',rStr]);
seq = rStr(1:3);
if crcResult == 1
%成功接收到消息,回复收到的帧序号
strToReply = '0';
if seq== 'BYE'
strToReply = 'ACK';
txdata = bpsk_tx_func(strToReply);
txdata = round(txdata .* 2^14);
txdata=repmat(txdata, 8,1);
input{1} = real(txdata);
input{2} = imag(txdata);
for i = 1:10
writeTxData(s, input);
disp('send ack');
pause(0.1);
end
break;
end
if expectedSeqNum == str2num(seq)
disp(['!!!success received:',rStr]);
lastSeqNum = expectedSeqNum;
if expectedSeqNum == 0
expectedSeqNum = 1;
else
expectedSeqNum = 0;
end
strToReply = int2str(str2num(seq));
else
strToReply = int2str(lastSeqNum);
end
disp(['reply:', strToReply]);
txdata = bpsk_tx_func(strToReply);
txdata = round(txdata .* 2^14);
txdata=repmat(txdata, 8,1);
input{1} = real(txdata);
input{2} = imag(txdata);
writeTxData(s, input);
end
end
%{
strToSend = 'hello world! This is a testing message, which length is more than 60. It should divide in to several parts, and each part will has 60 characters. Bye!';
arrLength = ceil(length(strToSend)/60);
sendArray = cell(1,arrLength);
for index = 1:arrLength
if index*60 > length(strToSend)
sendArray(index) = {strToSend(index*60-59:length(strToSend))};
else
sendArray(index) = {strToSend(index*60-59:index*60)};
end
end
index = 1;
disp('[[sending:]]');
disp(strToSend);
disp('[[receiving:]]');
isSuccess = 0;
while(1)
output = readRxData(s);
%output = stepImpl(s, input);
%fprintf('Data Block %i Received...\n',currentIndex);
I = output{1};
Q = output{2};
Rx = I+1i*Q;
[rStr, crcResult] = bpsk_rx_func(Rx);%bpsk_rx_func(Rx(end/2:end));
seq = rStr(1:3);
seqNum = str2num(seq);
if crcResult == 1
isSuccess = 1;
fprintf(rStr);
%disp(rStr);
end
end
%{
for currentIndex = 1:length(sendArray)
%fprintf('txdata number %i ...\n',currentIndex);
isSuccess = 0;
while(~isSuccess)
index = index+1;
txdata = bpsk_tx_func(sendArray{mod(index, length(sendArray))+1});
txdata = round(txdata .* 2^14);
txdata=repmat(txdata, 8,1);
%fprintf('Transmitting Data Block %i ...\n',currentIndex);
input{1} = real(txdata);
input{2} = imag(txdata);
writeTxData(s, input);
output = readRxData(s);
%output = stepImpl(s, input);
%fprintf('Data Block %i Received...\n',currentIndex);
I = output{1};
Q = output{2};
Rx = I+1i*Q;
[rStr, crcResult] = bpsk_rx_func(Rx);%bpsk_rx_func(Rx(end/2:end));
if crcResult == 1
isSuccess = 1;
fprintf(rStr);
%disp(rStr);
end
pause(0.1);
end
end
%}
%fprintf('Transmission and reception finished\n');
%}
% Read the RSSI attributes of both channels
rssi1 = output{s.getOutChannel('RX1_RSSI')};
% rssi2 = output{s.getOutChannel('RX2_RSSI')};
s.releaseImpl();

12
library/ad9361.cfg Executable file
View File

@ -0,0 +1,12 @@
data_in_device = cf-ad9361-dds-core-lpc
data_out_device = cf-ad9361-lpc
ctrl_device = ad9361-phy
channel = RX_LO_FREQ,IN,out_altvoltage0_RX_LO_frequency,
channel = RX_SAMPLING_FREQ,IN,in_voltage_sampling_frequency,
channel = RX_RF_BANDWIDTH,IN,in_voltage_rf_bandwidth,
channel = RX1_GAIN_MODE,IN,in_voltage0_gain_control_mode,
channel = RX1_GAIN,IN,in_voltage0_hardwaregain,
channel = RX1_RSSI,OUT,in_voltage0_rssi,
channel = TX_LO_FREQ,IN,out_altvoltage1_TX_LO_frequency,
channel = TX_SAMPLING_FREQ,IN,out_voltage_sampling_frequency,
channel = TX_RF_BANDWIDTH,IN,out_voltage_rf_bandwidth,

1589
library/iio.h Executable file

File diff suppressed because it is too large Load Diff

12
library/matlab/ad9361.cfg Executable file
View File

@ -0,0 +1,12 @@
data_in_device = cf-ad9361-dds-core-lpc
data_out_device = cf-ad9361-lpc
ctrl_device = ad9361-phy
channel = RX_LO_FREQ,IN,out_altvoltage0_RX_LO_frequency,
channel = RX_SAMPLING_FREQ,IN,in_voltage_sampling_frequency,
channel = RX_RF_BANDWIDTH,IN,in_voltage_rf_bandwidth,
channel = RX1_GAIN_MODE,IN,in_voltage0_gain_control_mode,
channel = RX1_GAIN,IN,in_voltage0_hardwaregain,
channel = RX1_RSSI,OUT,in_voltage0_rssi,
channel = TX_LO_FREQ,IN,out_altvoltage1_TX_LO_frequency,
channel = TX_SAMPLING_FREQ,IN,out_voltage_sampling_frequency,
channel = TX_RF_BANDWIDTH,IN,out_voltage_rf_bandwidth,

46
library/matlab/iio-wrapper.h Executable file
View File

@ -0,0 +1,46 @@
#ifndef MATLAB_LOADLIBRARY
#define MATLAB_LOADLIBRARY
#include "iio.h"
#ifndef __api
#define __api
#endif
struct iio_scan_block;
/** @brief Create a scan block
* @param backend A NULL-terminated string containing the backend to use for
* scanning. If NULL, all the available backends are used.
* @param flags Unused for now. Set to 0.
* @return on success, a pointer to a iio_scan_block structure
* @return On failure, NULL is returned and errno is set appropriately */
__api struct iio_scan_block * iio_create_scan_block(
const char *backend, unsigned int flags);
/** @brief Destroy the given scan block
* @param ctx A pointer to an iio_scan_block structure
*
* <b>NOTE:</b> After that function, the iio_scan_block pointer shall be invalid. */
__api void iio_scan_block_destroy(struct iio_scan_block *blk);
/** @brief Enumerate available contexts via scan block
* @param blk A pointer to a iio_scan_block structure.
* @returns On success, the number of contexts found.
* @returns On failure, a negative error number.
*/
__api ssize_t iio_scan_block_scan(struct iio_scan_block *blk);
/** @brief Get the iio_context_info for a particular context
* @param blk A pointer to an iio_scan_block structure
* @param index The index corresponding to the context.
* @return A pointer to the iio_context_info for the context
* @returns On success, a pointer to the specified iio_context_info
* @returns On failure, NULL is returned and errno is set appropriately
*/
__api struct iio_context_info *iio_scan_block_get_info(
struct iio_scan_block *blk, unsigned int index);
#endif

1589
library/matlab/iio.h Executable file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,17 @@
function installer_script(varargin)
if nargin > 0
install = varargin{1}; % use the command line arguement
else
install = true; % assume install
end
thisDir = fileparts(mfilename('fullpath')); % path to this script
if install
pathfunc = @addpath; % add paths for installation
else
pathfunc = @rmpath; % remove paths for uninstall
end
pathfunc(thisDir);
savepath;
end

474
library/matlab/iio_sys_obj.m Executable file
View File

@ -0,0 +1,474 @@
% Copyright 2014-15(c) Analog Devices, Inc.
%
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without modification,
% are permitted provided that the following conditions are met:
% - Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% - Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in
% the documentation and/or other materials provided with the
% distribution.
% - Neither the name of Analog Devices, Inc. nor the names of its
% contributors may be used to endorse or promote products derived
% from this software without specific prior written permission.
% - The use of this software may or may not infringe the patent rights
% of one or more patent holders. This license does not release you
% from the requirement that you obtain separate licenses from these
% patent holders to use this software.
% - Use of the software either in source or binary form or filter designs
% resulting from the use of this software, must be connected to, run
% on or loaded to an Analog Devices Inc. component.
%
% THIS SOFTWARE IS PROVIDED BY ANALOG DEVICES "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
% INCLUDING, BUT NOT LIMITED TO, NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A
% PARTICULAR PURPOSE ARE DISCLAIMED.
%
% IN NO EVENT SHALL ANALOG DEVICES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
% EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, INTELLECTUAL PROPERTY
% RIGHTS, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
% BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
% STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
% THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
classdef iio_sys_obj < matlab.System & matlab.system.mixin.Propagates ...
& matlab.system.mixin.CustomIcon
% iio_sys_obj System Object block for IIO devices
properties (Nontunable)
% Public, non-tunable properties.
%ip_address IP address
ip_address = '';
%dev_name Device name
dev_name = '';
%in_ch_no Number of input data channels
in_ch_no = 0;
%in_ch_size Input data channel size [samples]
in_ch_size = 8192;
%out_ch_no Number of output data channels
out_ch_no = 0;
%out_ch_size Output data channel size [samples]
out_ch_size = 8192;
end
properties (Access = protected)
% Protected class properties.
%iio_dev_cfg Device configuration structure
iio_dev_cfg = [];
end
properties (Access = private)
% Private class properties.
%libiio_data_in_dev libiio IIO interface object for the input data device
libiio_data_in_dev = {};
%libiio_data_out_dev libiio IIO interface object for the output data device
libiio_data_out_dev = {};
%libiio_ctrl_dev libiio IIO interface object for the control device
libiio_ctrl_dev = {};
%sys_obj_initialized Holds the initialization status of the system object
sys_obj_initialized = 0;
end
properties (DiscreteState)
% Discrete state properties.
%num_cfg_in Numeric type input control channels data
num_cfg_in;
%str_cfg_in String type input control channels data
str_cfg_in;
end
methods
%% Constructor
function obj = iio_sys_obj(varargin)
% Construct the libiio interface objects
obj.libiio_data_in_dev = libiio_if();
obj.libiio_data_out_dev = libiio_if();
obj.libiio_ctrl_dev = libiio_if();
% Support name-value pair arguments when constructing the object.
setProperties(obj,nargin,varargin{:});
end
end
methods (Access = protected)
%% Utility functions
function config = getObjConfig(obj)
% Read the selected device configuration
% Open the configuration file
fname = sprintf('%s.cfg', obj.dev_name);
fp_cfg = fopen(fname);
if(fp_cfg < 0)
config = {};
return;
end
% Build the object configuration structure
config = struct('data_in_device', '',... % Pointer to the data input device
'data_out_device', '',... % Pointer to the data output device
'ctrl_device', '',... % Pointer to the control device
'cfg_ch', [],... % Configuration channels list
'mon_ch', []); % Monitoring channels list
% Build the configuration/monitoring channels structure
ch_cfg = struct('port_name', '',... % Name of the port to be displayed on the object block
'port_attr', '',... % Associated device attribute name
'ctrl_dev_name', '',... % Control device name
'ctrl_dev', 0); % Pointer to the control device object
% Read the object's configuration
while(~feof(fp_cfg))
line = fgets(fp_cfg);
if(strfind(line,'#'))
continue;
end
if(~isempty(strfind(line, 'channel')))
% Get the associated configuration/monitoring channels
idx = strfind(line, '=');
line = line(idx+1:end);
line = strsplit(line, ',');
ch_cfg.port_name = strtrim(line{1});
ch_cfg.port_attr = strtrim(line{3});
if(length(line) > 4)
ch_cfg.ctrl_dev_name = strtrim(line{4});
else
ch_cfg.ctrl_dev_name = 'ctrl_device';
end
if(strcmp(strtrim(line{2}), 'IN'))
config.cfg_ch = [config.cfg_ch ch_cfg];
elseif(strcmp(strtrim(line{2}), 'OUT'))
config.mon_ch = [config.mon_ch ch_cfg];
end
elseif(~isempty(strfind(line, 'data_in_device')))
% Get the associated data input device
idx = strfind(line, '=');
tmp = line(idx+1:end);
tmp = strtrim(tmp);
config.data_in_device = tmp;
elseif(~isempty(strfind(line, 'data_out_device')))
% Get the associated data output device
idx = strfind(line, '=');
tmp = line(idx+1:end);
tmp = strtrim(tmp);
config.data_out_device = tmp;
elseif(~isempty(strfind(line, 'ctrl_device')))
% Get the associated control device
idx = strfind(line, '=');
tmp = line(idx+1:end);
tmp = strtrim(tmp);
config.ctrl_device = tmp;
end
end
fclose(fp_cfg);
end
end
methods (Access = protected)
%% Common functions
function setupImpl(obj)
% Implement tasks that need to be performed only once.
% Set the initialization status to fail
obj.sys_obj_initialized = 0;
% Read the object's configuration from the associated configuration file
obj.iio_dev_cfg = getObjConfig(obj);
if(isempty(obj.iio_dev_cfg))
msgbox('Could not read device configuration!', 'Error','error');
return;
end
% Initialize discrete-state properties.
obj.num_cfg_in = zeros(1, length(obj.iio_dev_cfg.cfg_ch));
obj.str_cfg_in = zeros(length(obj.iio_dev_cfg.cfg_ch), 64);
% Initialize the libiio data input device
if(obj.in_ch_no ~= 0)
[ret, err_msg, msg_log] = init(obj.libiio_data_in_dev, obj.ip_address, ...
obj.iio_dev_cfg.data_in_device, 'OUT', ...
obj.in_ch_no, obj.in_ch_size);
fprintf('%s', msg_log);
if(ret < 0)
msgbox(err_msg, 'Error','error');
return;
end
end
% Initialize the libiio data output device
if(obj.out_ch_no ~= 0)
[ret, err_msg, msg_log] = init(obj.libiio_data_out_dev, obj.ip_address, ...
obj.iio_dev_cfg.data_out_device, 'IN', ...
obj.out_ch_no, obj.out_ch_size);
fprintf('%s', msg_log);
if(ret < 0)
msgbox(err_msg, 'Error','error');
return;
end
end
% Initialize the libiio control device
if(~isempty(obj.iio_dev_cfg.ctrl_device))
[ret, err_msg, msg_log] = init(obj.libiio_ctrl_dev, obj.ip_address, ...
obj.iio_dev_cfg.ctrl_device, '', ...
0, 0);
fprintf('%s', msg_log);
if(ret < 0)
msgbox(err_msg, 'Error','error');
return;
end
end
% Assign the control device for each monitoring channel
for i = 1 : length(obj.iio_dev_cfg.mon_ch)
if(strcmp(obj.iio_dev_cfg.mon_ch(i).ctrl_dev_name, 'data_in_device'))
obj.iio_dev_cfg.mon_ch(i).ctrl_dev = obj.libiio_data_in_dev;
elseif(strcmp(obj.iio_dev_cfg.mon_ch(i).ctrl_dev_name, 'data_out_device'))
obj.iio_dev_cfg.mon_ch(i).ctrl_dev = obj.libiio_data_out_dev;
else
obj.iio_dev_cfg.mon_ch(i).ctrl_dev = obj.libiio_ctrl_dev;
end
end
% Assign the control device for each configuration channel
for i = 1 : length(obj.iio_dev_cfg.cfg_ch)
if(strcmp(obj.iio_dev_cfg.cfg_ch(i).ctrl_dev_name, 'data_in_device'))
obj.iio_dev_cfg.cfg_ch(i).ctrl_dev = obj.libiio_data_in_dev;
elseif(strcmp(obj.iio_dev_cfg.cfg_ch(i).ctrl_dev_name, 'data_out_device'))
obj.iio_dev_cfg.cfg_ch(i).ctrl_dev = obj.libiio_data_out_dev;
else
obj.iio_dev_cfg.cfg_ch(i).ctrl_dev = obj.libiio_ctrl_dev;
end
end
% Set the initialization status to success
obj.sys_obj_initialized = 1;
end
function releaseImpl(obj)
% Release any resources used by the system object.
obj.iio_dev_cfg = {};
delete(obj.libiio_data_in_dev);
delete(obj.libiio_data_out_dev);
delete(obj.libiio_ctrl_dev);
end
function varargout = stepImpl(obj, varargin)
% Implement the system object's processing flow.
varargout = cell(1, obj.out_ch_no + length(obj.iio_dev_cfg.mon_ch));
if(obj.sys_obj_initialized == 0)
return;
end
% Implement the device configuration flow
for i = 1 : length(obj.iio_dev_cfg.cfg_ch)
if(~isempty(varargin{i + obj.in_ch_no}))
if(length(varargin{i + obj.in_ch_no}) == 1)
new_data = (varargin{i + obj.in_ch_no} ~= obj.num_cfg_in(i));
else
new_data = ~strncmp(char(varargin{i + obj.in_ch_no}'), char(obj.str_cfg_in(i,:)), length(varargin{i + obj.in_ch_no}));
end
if(new_data == 1)
if(length(varargin{i + obj.in_ch_no}) == 1)
obj.num_cfg_in(i) = varargin{i + obj.in_ch_no};
str = num2str(obj.num_cfg_in(i));
else
for j = 1:length(varargin{i + obj.in_ch_no})
obj.str_cfg_in(i,j) = varargin{i + obj.in_ch_no}(j);
end
obj.str_cfg_in(i,j+1) = 0;
str = char(obj.str_cfg_in(i,:));
end
writeAttributeString(obj.iio_dev_cfg.cfg_ch(i).ctrl_dev, obj.iio_dev_cfg.cfg_ch(i).port_attr, str);
end
end
end
% Implement the data transmit flow
writeData(obj.libiio_data_in_dev, varargin);
% Implement the data capture flow
[~, data] = readData(obj.libiio_data_out_dev);
for i = 1 : obj.out_ch_no
varargout{i} = data{i};
end
% Implement the parameters monitoring flow
for i = 1 : length(obj.iio_dev_cfg.mon_ch)
[~, val] = readAttributeDouble(obj.iio_dev_cfg.mon_ch(i).ctrl_dev, obj.iio_dev_cfg.mon_ch(i).port_attr);
varargout{obj.out_ch_no + i} = val;
end
end
function resetImpl(obj)
% Initialize discrete-state properties.
obj.num_cfg_in = zeros(1, length(obj.iio_dev_cfg.cfg_ch));
obj.str_cfg_in = zeros(length(obj.iio_dev_cfg.cfg_ch), 64);
end
function num = getNumInputsImpl(obj)
% Get number of inputs.
num = obj.in_ch_no;
config = getObjConfig(obj);
if(~isempty(config))
num = num + length(config.cfg_ch);
end
end
function varargout = getInputNamesImpl(obj)
% Get input names
% Get the number of input data channels
data_ch_no = obj.in_ch_no;
% Get number of control channels
cfg_ch_no = 0;
config = getObjConfig(obj);
if(~isempty(config))
cgf_ch_no = length(config.cfg_ch);
end
if(data_ch_no + cgf_ch_no ~= 0)
varargout = cell(1, data_ch_no + cgf_ch_no);
for i = 1 : data_ch_no
varargout{i} = sprintf('DATA_IN%d', i);
end
for i = data_ch_no + 1 : data_ch_no + cgf_ch_no
varargout{i} = config.cfg_ch(i - data_ch_no).port_name;
end
else
varargout = {};
end
end
function num = getNumOutputsImpl(obj)
% Get number of outputs.
num = obj.out_ch_no;
config = getObjConfig(obj);
if(~isempty(config))
num = num + length(config.mon_ch);
end
end
function varargout = getOutputNamesImpl(obj)
% Get output names
% Get the number of output data channels
data_ch_no = obj.out_ch_no;
% Get number of monitoring channels
mon_ch_no = 0;
config = getObjConfig(obj);
if(~isempty(config))
mon_ch_no = length(config.mon_ch);
end
if(data_ch_no + mon_ch_no ~= 0)
varargout = cell(1, data_ch_no + mon_ch_no);
for i = 1 : data_ch_no
varargout{i} = sprintf('DATA_OUT%d', i);
end
for i = data_ch_no + 1 : data_ch_no + mon_ch_no
varargout{i} = config.mon_ch(i - data_ch_no).port_name;
end
else
varargout = {};
end
end
function varargout = isOutputFixedSizeImpl(obj)
% Get outputs fixed size.
varargout = cell(1, getNumOutputs(obj));
for i = 1 : getNumOutputs(obj)
varargout{i} = true;
end
end
function varargout = getOutputDataTypeImpl(obj)
% Get outputs data types.
varargout = cell(1, getNumOutputs(obj));
for i = 1 : getNumOutputs(obj)
varargout{i} = 'double';
end
end
function varargout = isOutputComplexImpl(obj)
% Get outputs data types.
varargout = cell(1, getNumOutputs(obj));
for i = 1 : getNumOutputs(obj)
varargout{i} = false;
end
end
function varargout = getOutputSizeImpl(obj)
% Implement if input size does not match with output size.
varargout = cell(1, getNumOutputs(obj));
for i = 1:obj.out_ch_no
varargout{i} = [obj.out_ch_size 1];
end
for i = obj.out_ch_no + 1 : length(varargout)
varargout{i} = [1 1];
end
end
function icon = getIconImpl(obj)
% Define a string as the icon for the System block in Simulink.
if(~isempty(obj.dev_name))
icon = obj.dev_name;
else
icon = mfilename('class');
end
end
%% Backup/restore functions
function s = saveObjectImpl(obj)
% Save private, protected, or state properties in a
% structure s. This is necessary to support Simulink
% features, such as SimState.
end
function loadObjectImpl(obj, s, wasLocked)
% Read private, protected, or state properties from
% the structure s and assign it to the object obj.
end
%% Simulink functions
function z = getDiscreteStateImpl(obj)
% Return structure of states with field names as
% DiscreteState properties.
z = struct([]);
end
end
methods(Static, Access = protected)
%% Simulink customization functions
function header = getHeaderImpl(obj)
% Define header for the System block dialog box.
header = matlab.system.display.Header(mfilename('class'));
end
function group = getPropertyGroupsImpl(obj)
% Define section for properties in System block dialog box.
group = matlab.system.display.Section(mfilename('class'));
end
end
end

View File

@ -0,0 +1,390 @@
% Copyright 2014(c) Analog Devices, Inc.
%
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without modification,
% are permitted provided that the following conditions are met:
% - Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% - Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in
% the documentation and/or other materials provided with the
% distribution.
% - Neither the name of Analog Devices, Inc. nor the names of its
% contributors may be used to endorse or promote products derived
% from this software without specific prior written permission.
% - The use of this software may or may not infringe the patent rights
% of one or more patent holders. This license does not release you
% from the requirement that you obtain separate licenses from these
% patent holders to use this software.
% - Use of the software either in source or binary form or filter designs
% resulting from the use of this software, must be connected to, run
% on or loaded to an Analog Devices Inc. component.
%
% THIS SOFTWARE IS PROVIDED BY ANALOG DEVICES "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
% INCLUDING, BUT NOT LIMITED TO, NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A
% PARTICULAR PURPOSE ARE DISCLAIMED.
%
% IN NO EVENT SHALL ANALOG DEVICES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
% EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, INTELLECTUAL PROPERTY
% RIGHTS, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
% BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
% STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
% THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
classdef iio_sys_obj_matlab
% iio_sys_obj System Object block for IIO devices
properties (Access = public)
% Public, non-tunable properties.
%ip_address IP address
ip_address = '';
%dev_name Device name
dev_name = '';
%in_ch_no Number of input data channels
in_ch_no = 0;
%in_ch_size Input data channel size [samples]
in_ch_size = 8192;
%out_ch_no Number of output data channels
out_ch_no = 0;
%out_ch_size Output data channel size [samples]
out_ch_size = 8192;
end
properties (Access = public)
% Protected class properties.
%iio_dev_cfg Device configuration structure
iio_dev_cfg = [];
end
properties (Access = private)
% Private class properties.
%libiio_data_in_dev libiio IIO interface object for the input data device
libiio_data_in_dev = {};
%libiio_data_out_dev libiio IIO interface object for the output data device
libiio_data_out_dev = {};
%libiio_ctrl_dev libiio IIO interface object for the control device
libiio_ctrl_dev = {};
%sys_obj_initialized Holds the initialization status of the system object
sys_obj_initialized = 0;
end
properties (Access = private)
% Discrete state properties.
%num_cfg_in Numeric type input control channels data
num_cfg_in;
%str_cfg_in String type input control channels data
str_cfg_in;
end
methods
%% Constructor
function obj = iio_sys_obj_matlab(varargin)
% Construct the libiio interface objects
obj.libiio_data_in_dev = libiio_if();
obj.libiio_data_out_dev = libiio_if();
obj.libiio_ctrl_dev = libiio_if();
end
end
methods (Access = protected)
%% Utility functions
function config = getObjConfig(obj)
% Read the selected device configuration
% Open the configuration file
fname = sprintf('%s.cfg', obj.dev_name);
fp_cfg = fopen(fname);
if(fp_cfg < 0)
config = {};
return;
end
% Build the object configuration structure
config = struct('data_in_device', '',... % Pointer to the data input device
'data_out_device', '',... % Pointer to the data output device
'ctrl_device', '',... % Pointer to the control device
'cfg_ch', [],... % Configuration channels list
'mon_ch', [],... % Monitoring channels list
'in_ch_names', [],... % Configuration channels names
'out_ch_names', []); % Monitoring channels names
config.in_ch_names = {};
config.out_ch_names = {};
% Build the configuration/monitoring channels structure
ch_cfg = struct('port_name', '',... % Name of the port to be displayed on the object block
'port_attr', '',... % Associated device attribute name
'ctrl_dev_name', '',... % Control device name
'ctrl_dev', 0); % Pointer to the control device object
% Read the object's configuration
while(~feof(fp_cfg))
line = fgets(fp_cfg);
if(strfind(line,'#'))
continue;
end
if(~isempty(strfind(line, 'channel')))
% Get the associated configuration/monitoring channels
idx = strfind(line, '=');
line = line(idx+1:end);
line = strsplit(line, ',');
ch_cfg.port_name = strtrim(line{1});
ch_cfg.port_attr = strtrim(line{3});
if(length(line) > 4)
ch_cfg.ctrl_dev_name = strtrim(line{4});
else
ch_cfg.ctrl_dev_name = 'ctrl_device';
end
if(strcmp(strtrim(line{2}), 'IN'))
config.cfg_ch = [config.cfg_ch ch_cfg];
config.in_ch_names = [config.in_ch_names ch_cfg.port_name];
elseif(strcmp(strtrim(line{2}), 'OUT'))
config.mon_ch = [config.mon_ch ch_cfg];
config.out_ch_names = [config.out_ch_names ch_cfg.port_name];
end
elseif(~isempty(strfind(line, 'data_in_device')))
% Get the associated data input device
idx = strfind(line, '=');
tmp = line(idx+1:end);
tmp = strtrim(tmp);
config.data_in_device = tmp;
elseif(~isempty(strfind(line, 'data_out_device')))
% Get the associated data output device
idx = strfind(line, '=');
tmp = line(idx+1:end);
tmp = strtrim(tmp);
config.data_out_device = tmp;
elseif(~isempty(strfind(line, 'ctrl_device')))
% Get the associated control device
idx = strfind(line, '=');
tmp = line(idx+1:end);
tmp = strtrim(tmp);
config.ctrl_device = tmp;
end
end
fclose(fp_cfg);
end
end
methods (Access = public)
%% Helper functions
function ret = getInChannel(obj, channelName)
% Returns the index of a named input channel
ret = obj.in_ch_no + find(strcmp(obj.iio_dev_cfg.in_ch_names, channelName));
end
function ret = getOutChannel(obj, channelName)
% Returns the index of a named output channel
ret = obj.out_ch_no + find(strcmp(obj.iio_dev_cfg.out_ch_names, channelName));
end
%% Common functions
function ret = setupImpl(obj)
% Implement tasks that need to be performed only once.
% Set the initialization status to fail
obj.sys_obj_initialized = 0;
% Read the object's configuration from the associated configuration file
obj.iio_dev_cfg = getObjConfig(obj);
if(isempty(obj.iio_dev_cfg))
msgbox('Could not read device configuration!', 'Error','error');
return;
end
% Initialize discrete-state properties.
obj.num_cfg_in = zeros(1, length(obj.iio_dev_cfg.cfg_ch));
obj.str_cfg_in = zeros(length(obj.iio_dev_cfg.cfg_ch), 64);
% Initialize the libiio data input device
if(obj.in_ch_no ~= 0)
[ret, err_msg, msg_log] = init(obj.libiio_data_in_dev, obj.ip_address, ...
obj.iio_dev_cfg.data_in_device, 'OUT', ...
obj.in_ch_no, obj.in_ch_size);
fprintf('%s', msg_log);
if(ret < 0)
msgbox(err_msg, 'Error','error');
return;
end
end
% Initialize the libiio data output device
if(obj.out_ch_no ~= 0)
[ret, err_msg, msg_log] = init(obj.libiio_data_out_dev, obj.ip_address, ...
obj.iio_dev_cfg.data_out_device, 'IN', ...
obj.out_ch_no, obj.out_ch_size);
fprintf('%s', msg_log);
if(ret < 0)
msgbox(err_msg, 'Error','error');
return;
end
end
% Initialize the libiio control device
if(~isempty(obj.iio_dev_cfg.ctrl_device))
[ret, err_msg, msg_log] = init(obj.libiio_ctrl_dev, obj.ip_address, ...
obj.iio_dev_cfg.ctrl_device, '', ...
0, 0);
fprintf('%s', msg_log);
if(ret < 0)
msgbox(err_msg, 'Error','error');
return;
end
end
% Assign the control device for each monitoring channel
for i = 1 : length(obj.iio_dev_cfg.mon_ch)
if(strcmp(obj.iio_dev_cfg.mon_ch(i).ctrl_dev_name, 'data_in_device'))
obj.iio_dev_cfg.mon_ch(i).ctrl_dev = obj.libiio_data_in_dev;
elseif(strcmp(obj.iio_dev_cfg.mon_ch(i).ctrl_dev_name, 'data_out_device'))
obj.iio_dev_cfg.mon_ch(i).ctrl_dev = obj.libiio_data_out_dev;
else
obj.iio_dev_cfg.mon_ch(i).ctrl_dev = obj.libiio_ctrl_dev;
end
end
% Assign the control device for each configuration channel
for i = 1 : length(obj.iio_dev_cfg.cfg_ch)
if(strcmp(obj.iio_dev_cfg.cfg_ch(i).ctrl_dev_name, 'data_in_device'))
obj.iio_dev_cfg.cfg_ch(i).ctrl_dev = obj.libiio_data_in_dev;
elseif(strcmp(obj.iio_dev_cfg.cfg_ch(i).ctrl_dev_name, 'data_out_device'))
obj.iio_dev_cfg.cfg_ch(i).ctrl_dev = obj.libiio_data_out_dev;
else
obj.iio_dev_cfg.cfg_ch(i).ctrl_dev = obj.libiio_ctrl_dev;
end
end
% Set the initialization status to success
obj.sys_obj_initialized = 1;
ret = obj;
end
function releaseImpl(obj)
% Release any resources used by the system object.
obj.iio_dev_cfg = {};
delete(obj.libiio_data_in_dev);
delete(obj.libiio_data_out_dev);
delete(obj.libiio_ctrl_dev);
end
function ret = stepImpl(obj, varargin)
% Implement the system object's processing flow.
varargout = cell(1, obj.out_ch_no + length(obj.iio_dev_cfg.mon_ch));
if(obj.sys_obj_initialized == 0)
return;
end
% Implement the device configuration flow
for i = 1 : length(obj.iio_dev_cfg.cfg_ch)
if(~isempty(varargin{1}{i + obj.in_ch_no}))
if(length(varargin{1}{i + obj.in_ch_no}) == 1)
new_data = (varargin{1}{i + obj.in_ch_no} ~= obj.num_cfg_in(i));
else
new_data = ~strncmp(char(varargin{1}{i + obj.in_ch_no}'), char(obj.str_cfg_in(i,:)), length(varargin{1}{i + obj.in_ch_no}));
end
if(new_data == 1)
if(length(varargin{1}{i + obj.in_ch_no}) == 1)
obj.num_cfg_in(i) = varargin{1}{i + obj.in_ch_no};
str = num2str(obj.num_cfg_in(i));
else
for j = 1:length(varargin{1}{i + obj.in_ch_no})
obj.str_cfg_in(i,j) = varargin{1}{i + obj.in_ch_no}(j);
end
obj.str_cfg_in(i,j+1) = 0;
str = char(obj.str_cfg_in(i,:));
end
writeAttributeString(obj.iio_dev_cfg.cfg_ch(i).ctrl_dev, obj.iio_dev_cfg.cfg_ch(i).port_attr, str);
end
end
end
% Implement the data transmit flow
writeData(obj.libiio_data_in_dev, varargin{1});
% --------------
% Implement the data capture flow
[~, data] = readData(obj.libiio_data_out_dev);
for i = 1 : obj.out_ch_no
varargout{i} = data{i};
end
% Implement the parameters monitoring flow
for i = 1 : length(obj.iio_dev_cfg.mon_ch)
[~, val] = readAttributeDouble(obj.iio_dev_cfg.mon_ch(i).ctrl_dev, obj.iio_dev_cfg.mon_ch(i).port_attr);
varargout{obj.out_ch_no + i} = val;
end
ret=varargout;
end
% wly--
function writeTxData(obj, varargin)
if(obj.sys_obj_initialized == 0)
return;
end
% Implement the device configuration flow
for i = 1 : length(obj.iio_dev_cfg.cfg_ch)
if(~isempty(varargin{1}{i + obj.in_ch_no}))
if(length(varargin{1}{i + obj.in_ch_no}) == 1)
new_data = (varargin{1}{i + obj.in_ch_no} ~= obj.num_cfg_in(i));
else
new_data = ~strncmp(char(varargin{1}{i + obj.in_ch_no}'), char(obj.str_cfg_in(i,:)), length(varargin{1}{i + obj.in_ch_no}));
end
if(new_data == 1)
if(length(varargin{1}{i + obj.in_ch_no}) == 1)
obj.num_cfg_in(i) = varargin{1}{i + obj.in_ch_no};
str = num2str(obj.num_cfg_in(i));
else
for j = 1:length(varargin{1}{i + obj.in_ch_no})
obj.str_cfg_in(i,j) = varargin{1}{i + obj.in_ch_no}(j);
end
obj.str_cfg_in(i,j+1) = 0;
str = char(obj.str_cfg_in(i,:));
end
writeAttributeString(obj.iio_dev_cfg.cfg_ch(i).ctrl_dev, obj.iio_dev_cfg.cfg_ch(i).port_attr, str);
end
end
end
writeData(obj.libiio_data_in_dev, varargin{1});
end
%wly--
function ret = readRxData(obj)
varargout = cell(1, obj.out_ch_no + length(obj.iio_dev_cfg.mon_ch));
[~, data] = readData(obj.libiio_data_out_dev);
for i = 1 : obj.out_ch_no
varargout{i} = data{i};
end
% Implement the parameters monitoring flow
for i = 1 : length(obj.iio_dev_cfg.mon_ch)
[~, val] = readAttributeDouble(obj.iio_dev_cfg.mon_ch(i).ctrl_dev, obj.iio_dev_cfg.mon_ch(i).port_attr);
varargout{obj.out_ch_no + i} = val;
end
ret=varargout;
end
function ret = writeFirData(obj, fir_data_file)
fir_data_str = fileread(fir_data_file);
ret = writeAttributeString(obj.libiio_ctrl_dev, 'filter_fir_config', fir_data_str);
end
end
end

701
library/matlab/libiio_if.m Executable file
View File

@ -0,0 +1,701 @@
% Copyright 2014(c) Analog Devices, Inc.
%
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without modification,
% are permitted provided that the following conditions are met:
% - Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% - Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in
% the documentation and/or other materials provided with the
% distribution.
% - Neither the name of Analog Devices, Inc. nor the names of its
% contributors may be used to endorse or promote products derived
% from this software without specific prior written permission.
% - The use of this software may or may not infringe the patent rights
% of one or more patent holders. This license does not release you
% from the requirement that you obtain separate licenses from these
% patent holders to use this software.
% - Use of the software either in source or binary form or filter designs
% resulting from the use of this software, must be connected to, run
% on or loaded to an Analog Devices Inc. component.
%
% THIS SOFTWARE IS PROVIDED BY ANALOG DEVICES "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
% INCLUDING, BUT NOT LIMITED TO, NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A
% PARTICULAR PURPOSE ARE DISCLAIMED.
%
% IN NO EVENT SHALL ANALOG DEVICES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
% EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, INTELLECTUAL PROPERTY
% RIGHTS, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
% BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
% STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
% THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
classdef libiio_if < handle
% libiio_if Interface object for for IIO devices
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Protected properties
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
properties (Access = protected)
libname = 'libiio';
hname = 'iio-wrapper.h';
dev_name = '';
data_ch_no = 0;
data_ch_size = 0;
dev_type = '';
iio_ctx = {};
iio_dev = {};
iio_buffer = {};
iio_channel = {};
iio_buf_size = 8192;
iio_scan_elm_no = 0;
if_initialized = 0;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Static private methods
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
methods (Static, Access = private)
function out = modInstanceCnt(val)
% Manages the number of object instances to handle proper DLL unloading
persistent instance_cnt;
if isempty(instance_cnt)
instance_cnt = 0;
end
instance_cnt = instance_cnt + val;
out = instance_cnt;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Protected methods
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
methods (Access = protected)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Creates the network context
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [ret, err_msg, msg_log] = createNetworkContext(obj, ip_address)
% Initialize the return values
ret = -1;
err_msg = '';
msg_log = [];
% Create the network context
obj.iio_ctx = calllib(obj.libname, 'iio_create_network_context', ip_address);
% Check if the network context is valid
if (isNull(obj.iio_ctx))
obj.iio_ctx = {};
err_msg = 'Could not connect to the IIO server!';
return;
end
% Increase the object's instance count
libiio_if.modInstanceCnt(1);
msg_log = [msg_log sprintf('%s: Connected to IP %s\n', class(obj), ip_address)];
% Set the return code to success
ret = 0;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Releases the network context and unload the libiio library
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function releaseContext(obj)
calllib(obj.libname, 'iio_context_destroy', obj.iio_ctx);
obj.iio_ctx = {};
instCnt = libiio_if.modInstanceCnt(-1);
if(instCnt == 0)
unloadlibrary(obj.libname);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Checks the compatibility of the different software modules.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [ret, err_msg, msg_log] = checkVersions(obj)
% Initialize the return values
ret = -1;
err_msg = '';
msg_log = [];
% Create a set of pointers to read the iiod and dll versions
data = zeros(1, 10);
remote_pMajor = libpointer('uint32Ptr', data(1));
remote_pMinor = libpointer('uint32Ptr', data(2));
remote_pGitTag = libpointer('int8Ptr', [int8(data(3:end)) 0]);
local_pMajor = libpointer('uint32Ptr', data(1));
local_pMinor = libpointer('uint32Ptr', data(2));
local_pGitTag = libpointer('int8Ptr', [int8(data(3:end)) 0]);
% get remote libiio version
calllib(obj.libname, 'iio_context_get_version', obj.iio_ctx, remote_pMajor, remote_pMinor, remote_pGitTag);
% extract git hash without trailing null char
remote_githash = remote_pGitTag.Value(1:7);
remote_version_str = sprintf('Remote libiio version: %d.%d, (git-%s)', remote_pMajor.Value, remote_pMinor.Value, remote_githash);
msg_log = [msg_log sprintf('%s: %s\n', class(obj), remote_version_str)];
% get local libiio version
calllib(obj.libname, 'iio_library_get_version', local_pMajor, local_pMinor, local_pGitTag);
local_githash = local_pGitTag.Value(1:7);
local_version_str = sprintf('Local libiio version: %d.%d, (git-%s)', local_pMajor.Value, local_pMinor.Value, local_githash);
msg_log = [msg_log sprintf('%s: %s\n', class(obj), local_version_str)];
if(remote_pMajor.Value < local_pMajor.Value)
err_msg = ['The libiio version running on the device is outdated! ' ...
'Run the adi_update_tools.sh script to get libiio up to date.'];
return;
elseif(remote_pMajor.Value > local_pMajor.Value)
err_msg = ['The libiio version on the local host is outdated! ' ...
'On Windows, reinstall the dll using the latest installer ' ...
'from the Analog Devices wiki.'];
return;
end
% Set the return code to success
ret = 0;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Detect if the specified device is present in the system
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [ret, err_msg, msg_log] = initDevice(obj, dev_name)
% Initialize the return values
ret = -1;
err_msg = '';
msg_log = [];
% Store the device name
obj.dev_name = dev_name;
% Get the number of devices
nb_devices = calllib(obj.libname, 'iio_context_get_devices_count', obj.iio_ctx);
% If no devices are present return with error
if(nb_devices == 0)
err_msg = 'No devices were detected in the system!';
return;
end
msg_log = [msg_log sprintf('%s: Found %d devices in the system\n', class(obj), nb_devices)];
% Detect if the targeted device is installed
dev_found = 0;
for i = 0 : nb_devices - 1
dev = calllib(obj.libname, 'iio_context_get_device', obj.iio_ctx, i);
name = calllib(obj.libname, 'iio_device_get_name', dev);
if(strcmp(name, dev_name))
obj.iio_dev = dev;
dev_found = 1;
break;
end
clear dev;
end
% Check if the target device was detected
if(dev_found == 0)
err_msg = 'Could not find target configuration device!';
return;
end
msg_log = [msg_log sprintf('%s: %s was found in the system\n', class(obj), obj.dev_name)];
% Set the return code to success
ret = 0;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Initializes the output data channels
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [ret, err_msg, msg_log] = initOutputDataChannels(obj, ch_no, ch_size)
% Initialize the return values
ret = -1;
err_msg = '';
msg_log = [];
% Save the number of channels and size
obj.data_ch_no = ch_no;
obj.data_ch_size = ch_size;
% Get the number of channels that the device has
nb_channels = calllib(obj.libname, 'iio_device_get_channels_count', obj.iio_dev);
if(nb_channels == 0)
err_msg = 'The selected device does not have any channels!';
return;
end
% Enable the data channels
if(ch_no ~= 0)
% Check if the device has output channels. The
% logic here assumes that a device can have
% only input or only output channels
obj.iio_channel{1} = calllib(obj.libname, 'iio_device_get_channel', obj.iio_dev, 0);
is_output = calllib(obj.libname, 'iio_channel_is_output', obj.iio_channel{1});
if(is_output == 0)
err_msg = 'The selected device does not have output channels!';
return;
end
% Enable all the channels
for j = 0 : nb_channels - 1
obj.iio_channel{j+1} = calllib(obj.libname, 'iio_device_get_channel', obj.iio_dev, j);
calllib(obj.libname, 'iio_channel_enable', obj.iio_channel{j+1});
is_scan_element = calllib(obj.libname, 'iio_channel_is_scan_element', obj.iio_channel{j+1});
if(is_scan_element == 1)
obj.iio_scan_elm_no = obj.iio_scan_elm_no + 1;
end
end
msg_log = [msg_log sprintf('%s: Found %d output channels for the device %s\n', class(obj), obj.iio_scan_elm_no, obj.dev_name)];
% Check if the number of channels in the device
% is greater or equal to the system object
% input channels
if(obj.iio_scan_elm_no < ch_no)
obj.iio_channel = {};
err_msg = 'The selected device does not have enough output channels!';
return;
end
% Enable the DAC buffer output
obj.if_initialized = 1;
ret = writeAttributeString(obj, 'altvoltage0*raw', '0');
obj.if_initialized = 0;
if(ret < 0)
obj.iio_channel = {};
err_msg = 'Could not enable the DAC buffer output!';
return;
end
% Create the IIO buffer used to write data
obj.iio_buf_size = obj.data_ch_size * obj.iio_scan_elm_no;
obj.iio_buffer = calllib(obj.libname, 'iio_device_create_buffer', obj.iio_dev,...
obj.data_ch_size, 1);
end
msg_log = [msg_log sprintf('%s: %s output data channels successfully initialized\n', class(obj), obj.dev_name)];
% Set the return code to success
ret = 0;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Initializes the input data channels
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [ret, err_msg, msg_log] = initInputDataChannels(obj, ch_no, ch_size)
% Initialize the return values
ret = -1;
err_msg = '';
msg_log = [];
% Save the number of channels and size
obj.data_ch_no = ch_no;
obj.data_ch_size = ch_size;
% Get the number of channels that the device has
nb_channels = calllib(obj.libname, 'iio_device_get_channels_count', obj.iio_dev);
if(nb_channels == 0)
err_msg = 'The selected device does not have any channels!';
return;
end
% Enable the system object output channels
if(ch_no ~= 0)
% Check if the device has input channels. The
% logic here assumes that a device can have
% only input or only output channels
obj.iio_channel{1} = calllib(obj.libname, 'iio_device_get_channel', obj.iio_dev, 0);
is_output = calllib(obj.libname, 'iio_channel_is_output', obj.iio_channel{1});
if(is_output == 1)
err_msg = 'The selected device does not have input channels!';
return;
end
msg_log = [msg_log sprintf('%s: Found %d input channels for the device %s\n', class(obj), nb_channels, obj.dev_name)];
% Check if the number of channels in the device
% is greater or equal to the system object
% output channels
if(nb_channels < ch_no)
obj.iio_channel = {};
err_msg = 'The selected device does not have enough input channels!';
return;
end
% Enable the channels
for j = 0 : ch_no - 1
obj.iio_channel{j+1} = calllib(obj.libname, 'iio_device_get_channel', obj.iio_dev, j);
calllib(obj.libname, 'iio_channel_enable', obj.iio_channel{j+1});
end
for j = ch_no : nb_channels - 1
obj.iio_channel{j+1} = calllib(obj.libname, 'iio_device_get_channel', obj.iio_dev, j);
calllib(obj.libname, 'iio_channel_disable', obj.iio_channel{j+1});
end
% Create the IIO buffer used to read data
obj.iio_buf_size = obj.data_ch_size * obj.data_ch_no;
obj.iio_buffer = calllib(obj.libname, 'iio_device_create_buffer', obj.iio_dev, obj.iio_buf_size, 0);
end
msg_log = [msg_log sprintf('%s: %s input data channels successfully initialized\n', class(obj), obj.dev_name)];
% Set the return code to success
ret = 0;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Public methods
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
methods
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Constructor
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function obj = libiio_if()
% Constructor
obj.if_initialized = 0;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Destructor
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function delete(obj)
% Release any resources used by the system object.
if((obj.if_initialized == 1) && libisloaded(obj.libname))
if(~isempty(obj.iio_buffer))
calllib(obj.libname, 'iio_buffer_destroy', obj.iio_buffer);
end
if(~isempty(obj.iio_ctx))
calllib(obj.libname, 'iio_context_destroy', obj.iio_ctx);
end
obj.iio_buffer = {};
obj.iio_channel = {};
obj.iio_dev = {};
obj.iio_ctx = {};
instCnt = libiio_if.modInstanceCnt(-1);
if(instCnt == 0)
unloadlibrary(obj.libname);
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Initializes the libiio interface
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [ret, err_msg, msg_log] = init(obj, ip_address, ...
dev_name, dev_type, ...
data_ch_no, data_ch_size)
% Initialize the return values
ret = -1;
err_msg = '';
msg_log = [];
% Save the device type
obj.dev_type = dev_type;
% Set the initialization status to fail
obj.if_initialized = 0;
% Load the libiio library
if(~libisloaded(obj.libname))
try
% ignore unknown type warnings due to header parsing limitations
warnState = warning('off', 'MATLAB:loadlibrary:TypeNotFound');
cleanupObj = onCleanup(@()warning(warnState));
[notfound, warnings] = loadlibrary(obj.libname, obj.hname, 'addheader', 'iio.h');
cleanupObj = []; % restore the warning state
catch exception
err_msg = exception.message;
return;
end
end
if(~libisloaded(obj.libname))
err_msg = 'Could not load the libiio library!';
return;
end
% Create the network context
[ret, err_msg, msg_log] = createNetworkContext(obj, ip_address);
if(ret < 0)
return;
end
% Check the software versions
[ret, err_msg, msg_log_new] = checkVersions(obj);
msg_log = [msg_log msg_log_new];
if(ret < 0)
releaseContext(obj);
return;
end
% Initialize the device
[ret, err_msg, msg_log_new] = initDevice(obj, dev_name);
msg_log = [msg_log msg_log_new];
if(ret < 0)
releaseContext(obj);
return;
end
% Initialize the output data channels
if(strcmp(dev_type, 'OUT'))
[ret, err_msg, msg_log_new] = initOutputDataChannels(obj, data_ch_no, data_ch_size);
msg_log = [msg_log msg_log_new];
if(ret < 0)
releaseContext(obj);
return;
end
end
% Initialize the input data channels
if(strcmp(dev_type, 'IN'))
[ret, err_msg, msg_log_new] = initInputDataChannels(obj, data_ch_no, data_ch_size);
msg_log = [msg_log msg_log_new];
if(ret < 0)
releaseContext(obj);
return;
end
end
% Set the initialization status to success
obj.if_initialized = 1;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Implement the data capture flow
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [ret, data] = readData(obj)
% Initialize the return values
ret = -1;
data = cell(1, obj.data_ch_no);
for i = 1 : obj.data_ch_no
data{i} = zeros(obj.data_ch_size, 1);
end
% Check if the interface is initialized
if(obj.if_initialized == 0)
return;
end
% Check if the device type is output
if(~strcmp(obj.dev_type, 'IN'))
return;
end
% Read the data
calllib(obj.libname, 'iio_buffer_refill', obj.iio_buffer);
buffer = calllib(obj.libname, 'iio_buffer_first', obj.iio_buffer, obj.iio_channel{1});
setdatatype(buffer, 'int16Ptr', obj.iio_buf_size);
for i = 1 : obj.data_ch_no
data{i} = double(buffer.Value(i:obj.data_ch_no:end));
end
% Set the return code to success
ret = 0;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Implement the data transmit flow
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ret = writeData(obj, data)
% Initialize the return values
ret = -1;
% Check if the interface is initialized
if(obj.if_initialized == 0)
return;
end
% Check if the device type is input
if(~strcmp(obj.dev_type, 'OUT'))
return;
end
% Destroy the buffer
calllib(obj.libname, 'iio_buffer_destroy', obj.iio_buffer);
obj.iio_buffer = {};
% Enable the DAC buffer output
ret = writeAttributeString(obj, 'altvoltage0*raw', '0');
if(ret < 0)
obj.iio_channel = {};
err_msg = 'Could not enable the DAC buffer output!';
return;
end
% Create the IIO buffer used to write data
obj.iio_buf_size = obj.data_ch_size * obj.iio_scan_elm_no;
obj.iio_buffer = calllib(obj.libname, 'iio_device_create_buffer', obj.iio_dev,...
obj.data_ch_size, 1);
% Transmit the data
buffer = calllib(obj.libname, 'iio_buffer_start', obj.iio_buffer);
setdatatype(buffer, 'int16Ptr', obj.iio_buf_size);
for i = 1 : obj.data_ch_no
buffer.Value(i : obj.iio_scan_elm_no : obj.iio_buf_size) = int16(data{i});
end
for i = obj.data_ch_no + 1 : obj.iio_scan_elm_no
buffer.Value(i : obj.iio_scan_elm_no : obj.iio_buf_size) = 0;
end
calllib(obj.libname, 'iio_buffer_push', obj.iio_buffer);
% Set the return code to success
ret = 0;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Find an attribute based on the name. The name can contain wildcard '*' characters
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [ret, ch, attr] = findAttribute(obj, attr_name)
% Initialize the return values
ret = -1;
ch = 0;
attr = '';
% Check if the interface is initialized
if(obj.if_initialized == 0)
return;
end
% Check if this is a device attribute
name = calllib(obj.libname, 'iio_device_find_attr', obj.iio_dev, attr_name);
if(~isempty(name))
ret = 0;
return;
end
% This is a channel attribute, search for the corresponding channel
chn_no = calllib(obj.libname, 'iio_device_get_channels_count', obj.iio_dev);
for k = 0 : chn_no - 1
ch = calllib(obj.libname, 'iio_device_get_channel', obj.iio_dev, k);
attr_no = calllib(obj.libname, 'iio_channel_get_attrs_count', ch);
attr_found = 0;
for l = 0 : attr_no - 1
attr = calllib(obj.libname, 'iio_channel_get_attr', ch, l);
name = calllib(obj.libname, 'iio_channel_attr_get_filename', ch, attr);
% The attribute to find can contain wildcard '*' characters,
% search for all the substrings in the attribute name
str_find = strsplit(attr_name, '*');
str_find = str_find(find(~strcmp(str_find, '')));
has_wildcard = ~isempty(strfind(attr_name, '*'));
attr_found = 1;
for i = 1 : length(str_find)
if(has_wildcard == 0)
ret = strcmp(name, str_find{i});
if(ret == 0)
ret = [];
end
else
ret = strfind(name, str_find{i});
end
if(isempty(ret))
attr_found = 0;
break;
end
end
if(attr_found == 1)
break;
end
clear attr;
end
% Check if the attribute was found
if(attr_found == 0)
clear ch;
else
ret = 1;
break;
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Read an attribute as a double value
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [ret, val] = readAttributeDouble(obj, attr_name)
% Find the attribute
[ret, ch, attr] = findAttribute(obj, attr_name);
if(ret < 0)
val = 0;
return;
end
% Create a double pointer to be used for data read
data = zeros(1, 10);
pData = libpointer('doublePtr', data(1));
% Read the attribute value
if(ret > 0)
calllib(obj.libname, 'iio_channel_attr_read_double', ch, attr, pData);
clear ch;
clear attr;
else
calllib(obj.libname, 'iio_device_attr_read_double', obj.iio_dev, attr_name, pData);
end
val = pData.Value;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Read an attribute as a string value
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [ret, val] = readAttributeString(obj, attr_name)
% Find the attribute
[ret, ch, attr] = findAttribute(obj, attr_name);
if(ret < 0)
val = '';
return;
end
% Create a pointer to be used for data read
data = char(ones(1, 512));
pData = libpointer('stringPtr', data);
% Read the attribute value
if(ret > 0)
[~, ~, ~, val] = calllib(obj.libname, 'iio_channel_attr_read', ch, attr, pData, 512);
clear ch;
clear attr;
else
[~, ~, ~, val] = calllib(obj.libname, 'iio_device_attr_read', obj.iio_dev, attr_name, pData, 512);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Write a string double value
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ret = writeAttributeDouble(obj, attr_name, val)
% Find the attribute
[ret, ch, attr] = findAttribute(obj, attr_name);
if(ret < 0)
return;
end
% Write the attribute
if(ret > 0)
calllib(obj.libname, 'iio_channel_attr_write_double', ch, attr, val);
clear ch;
clear attr;
else
calllib(obj.libname, 'iio_device_attr_write_double', obj.iio_dev, attr_name, val);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Write a string attribute value
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ret = writeAttributeString(obj, attr_name, str)
% Find the attribute
[ret, ch, attr] = findAttribute(obj, attr_name);
if(ret < 0)
return;
end
% Write the attribute
if(ret > 0)
calllib(obj.libname, 'iio_channel_attr_write', ch, attr, str);
clear ch;
clear attr;
else
calllib(obj.libname, 'iio_device_attr_write', obj.iio_dev, attr_name, str);
end
end
end
end

701
library/matlab/libiio_if_daq2.m Executable file
View File

@ -0,0 +1,701 @@
% Copyright 2014(c) Analog Devices, Inc.
%
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without modification,
% are permitted provided that the following conditions are met:
% - Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% - Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in
% the documentation and/or other materials provided with the
% distribution.
% - Neither the name of Analog Devices, Inc. nor the names of its
% contributors may be used to endorse or promote products derived
% from this software without specific prior written permission.
% - The use of this software may or may not infringe the patent rights
% of one or more patent holders. This license does not release you
% from the requirement that you obtain separate licenses from these
% patent holders to use this software.
% - Use of the software either in source or binary form or filter designs
% resulting from the use of this software, must be connected to, run
% on or loaded to an Analog Devices Inc. component.
%
% THIS SOFTWARE IS PROVIDED BY ANALOG DEVICES "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
% INCLUDING, BUT NOT LIMITED TO, NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A
% PARTICULAR PURPOSE ARE DISCLAIMED.
%
% IN NO EVENT SHALL ANALOG DEVICES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
% EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, INTELLECTUAL PROPERTY
% RIGHTS, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
% BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
% STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
% THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
classdef libiio_if < handle
% libiio_if Interface object for for IIO devices
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Protected properties
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
properties (Access = protected)
libname = 'libiio';
hname = 'iio.h';
dev_name = '';
data_ch_no = 0;
data_ch_size = 0;
dev_type = '';
iio_ctx = {};
iio_dev = {};
iio_buffer = {};
iio_channel = {};
iio_buf_size = 8192;
iio_scan_elm_no = 0;
if_initialized = 0;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Static private methods
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
methods (Static, Access = private)
function out = modInstanceCnt(val)
% Manages the number of object instances to handle proper DLL unloading
persistent instance_cnt;
if isempty(instance_cnt)
instance_cnt = 0;
end
instance_cnt = instance_cnt + val;
out = instance_cnt;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Protected methods
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
methods (Access = protected)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Creates the network context
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [ret, err_msg, msg_log] = createNetworkContext(obj, ip_address)
% Initialize the return values
ret = -1;
err_msg = '';
msg_log = [];
% Create the network context
obj.iio_ctx = calllib(obj.libname, 'iio_create_network_context', ip_address);
% Check if the network context is valid
if (isNull(obj.iio_ctx))
obj.iio_ctx = {};
err_msg = 'Could not connect to the IIO server!';
return;
end
% Increase the object's instance count
libiio_if.modInstanceCnt(1);
msg_log = [msg_log sprintf('%s: Connected to IP %s\n', class(obj), ip_address)];
% Set the return code to success
ret = 0;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Releases the network context and unload the libiio library
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function releaseContext(obj)
calllib(obj.libname, 'iio_context_destroy', obj.iio_ctx);
obj.iio_ctx = {};
instCnt = libiio_if.modInstanceCnt(-1);
if(instCnt == 0)
unloadlibrary(obj.libname);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Checks the compatibility of the different software modules.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [ret, err_msg, msg_log] = checkVersions(obj)
% Initialize the return values
ret = -1;
err_msg = '';
msg_log = [];
% Create a set of pointers to read the iiod and dll versions
data = zeros(1, 10);
remote_pMajor = libpointer('uint32Ptr', data(1));
remote_pMinor = libpointer('uint32Ptr', data(2));
remote_pGitTag = libpointer('int8Ptr', [int8(data(3:end)) 0]);
local_pMajor = libpointer('uint32Ptr', data(1));
local_pMinor = libpointer('uint32Ptr', data(2));
local_pGitTag = libpointer('int8Ptr', [int8(data(3:end)) 0]);
% get remote libiio version
calllib(obj.libname, 'iio_context_get_version', obj.iio_ctx, remote_pMajor, remote_pMinor, remote_pGitTag);
% extract git hash without trailing null char
remote_githash = remote_pGitTag.Value(1:7);
remote_version_str = sprintf('Remote libiio version: %d.%d, (git-%s)', remote_pMajor.Value, remote_pMinor.Value, remote_githash);
msg_log = [msg_log sprintf('%s: %s\n', class(obj), remote_version_str)];
% get local libiio version
calllib(obj.libname, 'iio_library_get_version', local_pMajor, local_pMinor, local_pGitTag);
local_githash = local_pGitTag.Value(1:7);
local_version_str = sprintf('Local libiio version: %d.%d, (git-%s)', local_pMajor.Value, local_pMinor.Value, local_githash);
msg_log = [msg_log sprintf('%s: %s\n', class(obj), local_version_str)];
if(remote_pMajor.Value < local_pMajor.Value)
err_msg = ['The libiio version running on the device is outdated! ' ...
'Run the adi_update_tools.sh script to get libiio up to date.'];
return;
elseif(remote_pMajor.Value > local_pMajor.Value)
err_msg = ['The libiio version on the local host is outdated! ' ...
'On Windows, reinstall the dll using the latest installer ' ...
'from the Analog Devices wiki.'];
return;
end
% Set the return code to success
ret = 0;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Detect if the specified device is present in the system
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [ret, err_msg, msg_log] = initDevice(obj, dev_name)
% Initialize the return values
ret = -1;
err_msg = '';
msg_log = [];
% Store the device name
obj.dev_name = dev_name;
% Get the number of devices
nb_devices = calllib(obj.libname, 'iio_context_get_devices_count', obj.iio_ctx);
% If no devices are present return with error
if(nb_devices == 0)
err_msg = 'No devices were detected in the system!';
return;
end
msg_log = [msg_log sprintf('%s: Found %d devices in the system\n', class(obj), nb_devices)];
% Detect if the targeted device is installed
dev_found = 0;
for i = 0 : nb_devices - 1
dev = calllib(obj.libname, 'iio_context_get_device', obj.iio_ctx, i);
name = calllib(obj.libname, 'iio_device_get_name', dev);
if(strcmp(name, dev_name))
obj.iio_dev = dev;
dev_found = 1;
break;
end
clear dev;
end
% Check if the target device was detected
if(dev_found == 0)
err_msg = 'Could not find target configuration device!';
return;
end
msg_log = [msg_log sprintf('%s: %s was found in the system\n', class(obj), obj.dev_name)];
% Set the return code to success
ret = 0;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Initializes the output data channels
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [ret, err_msg, msg_log] = initOutputDataChannels(obj, ch_no, ch_size)
% Initialize the return values
ret = -1;
err_msg = '';
msg_log = [];
% Save the number of channels and size
obj.data_ch_no = ch_no;
obj.data_ch_size = ch_size;
% Get the number of channels that the device has
nb_channels = calllib(obj.libname, 'iio_device_get_channels_count', obj.iio_dev);
if(nb_channels == 0)
err_msg = 'The selected device does not have any channels!';
return;
end
% Enable the data channels
if(ch_no ~= 0)
% Check if the device has output channels. The
% logic here assumes that a device can have
% only input or only output channels
obj.iio_channel{1} = calllib(obj.libname, 'iio_device_get_channel', obj.iio_dev, 0);
is_output = calllib(obj.libname, 'iio_channel_is_output', obj.iio_channel{1});
if(is_output == 0)
err_msg = 'The selected device does not have output channels!';
return;
end
% Enable all the channels
for j = 0 : nb_channels - 1
obj.iio_channel{j+1} = calllib(obj.libname, 'iio_device_get_channel', obj.iio_dev, j);
if(j < ch_no)
calllib(obj.libname, 'iio_channel_enable', obj.iio_channel{j+1});
is_scan_element = calllib(obj.libname, 'iio_channel_is_scan_element', obj.iio_channel{j+1});
if(is_scan_element == 1)
obj.iio_scan_elm_no = obj.iio_scan_elm_no + 1;
end
else
calllib(obj.libname, 'iio_channel_disable', obj.iio_channel{j+1});
end
end
msg_log = [msg_log sprintf('%s: Found %d output channels for the device %s\n', class(obj), obj.iio_scan_elm_no, obj.dev_name)];
% Check if the number of channels in the device
% is greater or equal to the system object
% input channels
if(obj.iio_scan_elm_no < ch_no)
obj.iio_channel = {};
err_msg = 'The selected device does not have enough output channels!';
return;
end
% Enable the DAC buffer output
obj.if_initialized = 1;
ret = writeAttributeString(obj, 'altvoltage0*raw', '0');
obj.if_initialized = 0;
if(ret < 0)
obj.iio_channel = {};
err_msg = 'Could not enable the DAC buffer output!';
return;
end
% Create the IIO buffer used to write data
obj.iio_buf_size = obj.data_ch_size * obj.iio_scan_elm_no;
obj.iio_buffer = calllib(obj.libname, 'iio_device_create_buffer', obj.iio_dev,...
obj.data_ch_size, 1);
end
msg_log = [msg_log sprintf('%s: %s output data channels successfully initialized\n', class(obj), obj.dev_name)];
% Set the return code to success
ret = 0;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Initializes the input data channels
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [ret, err_msg, msg_log] = initInputDataChannels(obj, ch_no, ch_size)
% Initialize the return values
ret = -1;
err_msg = '';
msg_log = [];
% Save the number of channels and size
obj.data_ch_no = ch_no;
obj.data_ch_size = ch_size;
% Get the number of channels that the device has
nb_channels = calllib(obj.libname, 'iio_device_get_channels_count', obj.iio_dev);
if(nb_channels == 0)
err_msg = 'The selected device does not have any channels!';
return;
end
% Enable the system object output channels
if(ch_no ~= 0)
% Check if the device has input channels. The
% logic here assumes that a device can have
% only input or only output channels
obj.iio_channel{1} = calllib(obj.libname, 'iio_device_get_channel', obj.iio_dev, 0);
is_output = calllib(obj.libname, 'iio_channel_is_output', obj.iio_channel{1});
if(is_output == 1)
err_msg = 'The selected device does not have input channels!';
return;
end
msg_log = [msg_log sprintf('%s: Found %d input channels for the device %s\n', class(obj), nb_channels, obj.dev_name)];
% Check if the number of channels in the device
% is greater or equal to the system object
% output channels
if(nb_channels < ch_no)
obj.iio_channel = {};
err_msg = 'The selected device does not have enough input channels!';
return;
end
% Enable the channels
for j = 0 : ch_no - 1
obj.iio_channel{j+1} = calllib(obj.libname, 'iio_device_get_channel', obj.iio_dev, j);
calllib(obj.libname, 'iio_channel_enable', obj.iio_channel{j+1});
end
for j = ch_no : nb_channels - 1
obj.iio_channel{j+1} = calllib(obj.libname, 'iio_device_get_channel', obj.iio_dev, j);
calllib(obj.libname, 'iio_channel_disable', obj.iio_channel{j+1});
end
% Create the IIO buffer used to read data
obj.iio_buf_size = obj.data_ch_size * obj.data_ch_no;
obj.iio_buffer = calllib(obj.libname, 'iio_device_create_buffer', obj.iio_dev, obj.iio_buf_size, 0);
end
msg_log = [msg_log sprintf('%s: %s input data channels successfully initialized\n', class(obj), obj.dev_name)];
% Set the return code to success
ret = 0;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Public methods
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
methods
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Constructor
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function obj = libiio_if()
% Constructor
obj.if_initialized = 0;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Destructor
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function delete(obj)
% Release any resources used by the system object.
if((obj.if_initialized == 1) && libisloaded(obj.libname))
if(~isempty(obj.iio_buffer))
calllib(obj.libname, 'iio_buffer_destroy', obj.iio_buffer);
end
if(~isempty(obj.iio_ctx))
calllib(obj.libname, 'iio_context_destroy', obj.iio_ctx);
end
obj.iio_buffer = {};
obj.iio_channel = {};
obj.iio_dev = {};
obj.iio_ctx = {};
instCnt = libiio_if.modInstanceCnt(-1);
if(instCnt == 0)
unloadlibrary(obj.libname);
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Initializes the libiio interface
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [ret, err_msg, msg_log] = init(obj, ip_address, ...
dev_name, dev_type, ...
data_ch_no, data_ch_size)
% Initialize the return values
ret = -1;
err_msg = '';
msg_log = [];
% Save the device type
obj.dev_type = dev_type;
% Set the initialization status to fail
obj.if_initialized = 0;
% Load the libiio library
if(~libisloaded(obj.libname))
try
[notfound, warnings] = loadlibrary(obj.libname, obj.hname);
catch exception
err_msg = exception.message;
return;
end
end
if(~libisloaded(obj.libname))
err_msg = 'Could not load the libiio library!';
return;
end
% Create the network context
[ret, err_msg, msg_log] = createNetworkContext(obj, ip_address);
if(ret < 0)
return;
end
% Check the software versions
[ret, err_msg, msg_log_new] = checkVersions(obj);
msg_log = [msg_log msg_log_new];
if(ret < 0)
releaseContext(obj);
return;
end
% Initialize the device
[ret, err_msg, msg_log_new] = initDevice(obj, dev_name);
msg_log = [msg_log msg_log_new];
if(ret < 0)
releaseContext(obj);
return;
end
% Initialize the output data channels
if(strcmp(dev_type, 'OUT'))
[ret, err_msg, msg_log_new] = initOutputDataChannels(obj, data_ch_no, data_ch_size);
msg_log = [msg_log msg_log_new];
if(ret < 0)
releaseContext(obj);
return;
end
end
% Initialize the input data channels
if(strcmp(dev_type, 'IN'))
[ret, err_msg, msg_log_new] = initInputDataChannels(obj, data_ch_no, data_ch_size);
msg_log = [msg_log msg_log_new];
if(ret < 0)
releaseContext(obj);
return;
end
end
% Set the initialization status to success
obj.if_initialized = 1;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Implement the data capture flow
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [ret, data] = readData(obj)
% Initialize the return values
ret = -1;
data = cell(1, obj.data_ch_no);
for i = 1 : obj.data_ch_no
data{i} = zeros(obj.data_ch_size, 1);
end
% Check if the interface is initialized
if(obj.if_initialized == 0)
return;
end
% Check if the device type is output
if(~strcmp(obj.dev_type, 'IN'))
return;
end
% Read the data
calllib(obj.libname, 'iio_buffer_refill', obj.iio_buffer);
buffer = calllib(obj.libname, 'iio_buffer_first', obj.iio_buffer, obj.iio_channel{1});
setdatatype(buffer, 'int16Ptr', obj.iio_buf_size);
for i = 1 : obj.data_ch_no
data{i} = double(buffer.Value(i:obj.data_ch_no:end));
end
% Set the return code to success
ret = 0;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Implement the data transmit flow
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ret = writeData(obj, data)
% Initialize the return values
ret = -1;
% Check if the interface is initialized
if(obj.if_initialized == 0)
return;
end
% Check if the device type is input
if(~strcmp(obj.dev_type, 'OUT'))
return;
end
% Destroy the buffer
calllib(obj.libname, 'iio_buffer_destroy', obj.iio_buffer);
obj.iio_buffer = {};
% Enable the DAC buffer output
ret = writeAttributeString(obj, 'altvoltage0*raw', '0');
if(ret < 0)
obj.iio_channel = {};
err_msg = 'Could not enable the DAC buffer output!';
return;
end
% Create the IIO buffer used to write data
obj.iio_buf_size = obj.data_ch_size * obj.iio_scan_elm_no;
obj.iio_buffer = calllib(obj.libname, 'iio_device_create_buffer', obj.iio_dev,...
obj.data_ch_size, 1);
% Transmit the data
buffer = calllib(obj.libname, 'iio_buffer_start', obj.iio_buffer);
setdatatype(buffer, 'int16Ptr', obj.iio_buf_size);
for i = 1 : obj.data_ch_no
buffer.Value(i : obj.iio_scan_elm_no : obj.iio_buf_size) = int16(data{i});
end
for i = obj.data_ch_no + 1 : obj.iio_scan_elm_no
buffer.Value(i : obj.iio_scan_elm_no : obj.iio_buf_size) = 0;
end
calllib(obj.libname, 'iio_buffer_push', obj.iio_buffer);
% Set the return code to success
ret = 0;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Find an attribute based on the name. The name can contain wildcard '*' characters
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [ret, ch, attr] = findAttribute(obj, attr_name)
% Initialize the return values
ret = -1;
ch = 0;
attr = '';
% Check if the interface is initialized
if(obj.if_initialized == 0)
return;
end
% Check if this is a device attribute
name = calllib(obj.libname, 'iio_device_find_attr', obj.iio_dev, attr_name);
if(~isempty(name))
ret = 0;
return;
end
% This is a channel attribute, search for the corresponding channel
chn_no = calllib(obj.libname, 'iio_device_get_channels_count', obj.iio_dev);
for k = 0 : chn_no - 1
ch = calllib(obj.libname, 'iio_device_get_channel', obj.iio_dev, k);
attr_no = calllib(obj.libname, 'iio_channel_get_attrs_count', ch);
attr_found = 0;
for l = 0 : attr_no - 1
attr = calllib(obj.libname, 'iio_channel_get_attr', ch, l);
name = calllib(obj.libname, 'iio_channel_attr_get_filename', ch, attr);
% The attribute to find can contain wildcard '*' characters,
% search for all the substrings in the attribute name
str_find = strsplit(attr_name, '*');
str_find = str_find(find(~strcmp(str_find, '')));
has_wildcard = ~isempty(strfind(attr_name, '*'));
attr_found = 1;
for i = 1 : length(str_find)
if(has_wildcard == 0)
ret = strcmp(name, str_find{i});
if(ret == 0)
ret = [];
end
else
ret = strfind(name, str_find{i});
end
if(isempty(ret))
attr_found = 0;
break;
end
end
if(attr_found == 1)
break;
end
clear attr;
end
% Check if the attribute was found
if(attr_found == 0)
clear ch;
else
ret = 1;
break;
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Read an attribute as a double value
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [ret, val] = readAttributeDouble(obj, attr_name)
% Find the attribute
[ret, ch, attr] = findAttribute(obj, attr_name);
if(ret < 0)
val = 0;
return;
end
% Create a double pointer to be used for data read
data = zeros(1, 10);
pData = libpointer('doublePtr', data(1));
% Read the attribute value
if(ret > 0)
calllib(obj.libname, 'iio_channel_attr_read_double', ch, attr, pData);
clear ch;
clear attr;
else
calllib(obj.libname, 'iio_device_attr_read_double', obj.iio_dev, attr_name, pData);
end
val = pData.Value;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Read an attribute as a string value
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [ret, val] = readAttributeString(obj, attr_name)
% Find the attribute
[ret, ch, attr] = findAttribute(obj, attr_name);
if(ret < 0)
val = '';
return;
end
% Create a pointer to be used for data read
data = char(ones(1, 512));
pData = libpointer('stringPtr', data);
% Read the attribute value
if(ret > 0)
[~, ~, ~, val] = calllib(obj.libname, 'iio_channel_attr_read', ch, attr, pData, 512);
clear ch;
clear attr;
else
[~, ~, ~, val] = calllib(obj.libname, 'iio_device_attr_read', obj.iio_dev, attr_name, pData, 512);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Write a string double value
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ret = writeAttributeDouble(obj, attr_name, val)
% Find the attribute
[ret, ch, attr] = findAttribute(obj, attr_name);
if(ret < 0)
return;
end
% Write the attribute
if(ret > 0)
calllib(obj.libname, 'iio_channel_attr_write_double', ch, attr, val);
clear ch;
clear attr;
else
calllib(obj.libname, 'iio_device_attr_write_double', obj.iio_dev, attr_name, val);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Write a string attribute value
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ret = writeAttributeString(obj, attr_name, str)
% Find the attribute
[ret, ch, attr] = findAttribute(obj, attr_name);
if(ret < 0)
return;
end
% Write the attribute
if(ret > 0)
calllib(obj.libname, 'iio_channel_attr_write', ch, attr, str);
clear ch;
clear attr;
else
calllib(obj.libname, 'iio_device_attr_write', obj.iio_dev, attr_name, str);
end
end
end
end