From 9173a31acc042421e5f15a7dda10bf31ba60b2ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E8=B7=AF=E8=BF=9C?= Date: Mon, 29 Jan 2018 22:11:44 -0800 Subject: [PATCH] create repo --- README.md | 7 + code/matlab/BPSK/receiver/bpsk_rx_func.m | 119 ++ code/matlab/BPSK/receiver/crc32.m | 23 + code/matlab/BPSK/receiver/debug.m | 22 + code/matlab/BPSK/receiver/descramble.m | 11 + code/matlab/BPSK/receiver/rx_bpsk_demod.m | 19 + code/matlab/BPSK/receiver/rx_channel_est.m | 20 + code/matlab/BPSK/receiver/rx_delete_pilot.m | 20 + code/matlab/BPSK/receiver/rx_freq_sync.m | 20 + code/matlab/BPSK/receiver/rx_package_search.m | 19 + .../matlab/BPSK/receiver/rx_package_search2.m | 15 + code/matlab/BPSK/receiver/rx_phase_sync.m | 14 + code/matlab/BPSK/receiver/rx_phase_track.m | 17 + code/matlab/BPSK/receiver/rx_qpsk_demod.m | 35 + code/matlab/BPSK/receiver/rx_time_equalize.m | 25 + .../matlab/BPSK/receiver/rx_timing_recovery.m | 94 + code/matlab/BPSK/receiver/tx_gen_m_seq.m | 17 + code/matlab/BPSK/receiver/tx_modulate.m | 65 + code/matlab/BPSK/transmitter/bpsk_tx_func.m | 36 + code/matlab/BPSK/transmitter/crc32.m | 24 + code/matlab/BPSK/transmitter/insert_pilot.m | 21 + code/matlab/BPSK/transmitter/scramble.m | 11 + code/matlab/BPSK/transmitter/str_to_bits.m | 8 + code/matlab/BPSK/transmitter/tx_gen_m_seq.m | 17 + code/matlab/BPSK/transmitter/tx_modulate.m | 65 + code/matlab/BPSK/transmitter/tx_prbs15.m | 11 + code/matlab/slideWindow-receiver.m | 158 ++ code/matlab/slideWindow-sender.m | 181 ++ code/matlab/stop&Wait-sender.m | 177 ++ code/matlab/stop&wait-receiver.m | 180 ++ library/ad9361.cfg | 12 + library/iio.h | 1589 +++++++++++++++++ library/matlab/ad9361.cfg | 12 + library/matlab/iio-wrapper.h | 46 + library/matlab/iio.h | 1589 +++++++++++++++++ library/matlab/iio_installer_script.m | 17 + library/matlab/iio_sys_obj.m | 474 +++++ library/matlab/iio_sys_obj_matlab.m | 390 ++++ library/matlab/libiio_if.m | 701 ++++++++ library/matlab/libiio_if_daq2.m | 701 ++++++++ 40 files changed, 6982 insertions(+) create mode 100644 README.md create mode 100755 code/matlab/BPSK/receiver/bpsk_rx_func.m create mode 100755 code/matlab/BPSK/receiver/crc32.m create mode 100755 code/matlab/BPSK/receiver/debug.m create mode 100755 code/matlab/BPSK/receiver/descramble.m create mode 100755 code/matlab/BPSK/receiver/rx_bpsk_demod.m create mode 100755 code/matlab/BPSK/receiver/rx_channel_est.m create mode 100755 code/matlab/BPSK/receiver/rx_delete_pilot.m create mode 100755 code/matlab/BPSK/receiver/rx_freq_sync.m create mode 100755 code/matlab/BPSK/receiver/rx_package_search.m create mode 100755 code/matlab/BPSK/receiver/rx_package_search2.m create mode 100755 code/matlab/BPSK/receiver/rx_phase_sync.m create mode 100755 code/matlab/BPSK/receiver/rx_phase_track.m create mode 100755 code/matlab/BPSK/receiver/rx_qpsk_demod.m create mode 100755 code/matlab/BPSK/receiver/rx_time_equalize.m create mode 100755 code/matlab/BPSK/receiver/rx_timing_recovery.m create mode 100755 code/matlab/BPSK/receiver/tx_gen_m_seq.m create mode 100755 code/matlab/BPSK/receiver/tx_modulate.m create mode 100755 code/matlab/BPSK/transmitter/bpsk_tx_func.m create mode 100755 code/matlab/BPSK/transmitter/crc32.m create mode 100755 code/matlab/BPSK/transmitter/insert_pilot.m create mode 100755 code/matlab/BPSK/transmitter/scramble.m create mode 100755 code/matlab/BPSK/transmitter/str_to_bits.m create mode 100755 code/matlab/BPSK/transmitter/tx_gen_m_seq.m create mode 100755 code/matlab/BPSK/transmitter/tx_modulate.m create mode 100755 code/matlab/BPSK/transmitter/tx_prbs15.m create mode 100644 code/matlab/slideWindow-receiver.m create mode 100755 code/matlab/slideWindow-sender.m create mode 100755 code/matlab/stop&Wait-sender.m create mode 100644 code/matlab/stop&wait-receiver.m create mode 100755 library/ad9361.cfg create mode 100755 library/iio.h create mode 100755 library/matlab/ad9361.cfg create mode 100755 library/matlab/iio-wrapper.h create mode 100755 library/matlab/iio.h create mode 100755 library/matlab/iio_installer_script.m create mode 100755 library/matlab/iio_sys_obj.m create mode 100755 library/matlab/iio_sys_obj_matlab.m create mode 100755 library/matlab/libiio_if.m create mode 100755 library/matlab/libiio_if_daq2.m diff --git a/README.md b/README.md new file mode 100644 index 0000000..b102b66 --- /dev/null +++ b/README.md @@ -0,0 +1,7 @@ +# Pluto-Network + +本项目使用 Pluto SDR 设备实现了简化版的停止等待和滑动窗口两个可靠传输协议。可在两台设备之间任意的传输文字或文件。 + +需要使用两台 Pluto 设备,一台作为接收机,另外一台作为发射机,并分别运行相应的代码。具体的实验报告发布在了我的 Blog 上。 + +如果有疑问或发现了什么问题,欢迎发邮件联系我。我的邮箱是 e@wangluyuan.cc \ No newline at end of file diff --git a/code/matlab/BPSK/receiver/bpsk_rx_func.m b/code/matlab/BPSK/receiver/bpsk_rx_func.m new file mode 100755 index 0000000..f902483 --- /dev/null +++ b/code/matlab/BPSK/receiver/bpsk_rx_func.m @@ -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 + diff --git a/code/matlab/BPSK/receiver/crc32.m b/code/matlab/BPSK/receiver/crc32.m new file mode 100755 index 0000000..8e27e45 --- /dev/null +++ b/code/matlab/BPSK/receiver/crc32.m @@ -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 + 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 diff --git a/code/matlab/BPSK/receiver/debug.m b/code/matlab/BPSK/receiver/debug.m new file mode 100755 index 0000000..809d892 --- /dev/null +++ b/code/matlab/BPSK/receiver/debug.m @@ -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; \ No newline at end of file diff --git a/code/matlab/BPSK/receiver/descramble.m b/code/matlab/BPSK/receiver/descramble.m new file mode 100755 index 0000000..f7de70d --- /dev/null +++ b/code/matlab/BPSK/receiver/descramble.m @@ -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 diff --git a/code/matlab/BPSK/receiver/rx_bpsk_demod.m b/code/matlab/BPSK/receiver/rx_bpsk_demod.m new file mode 100755 index 0000000..36e9ea8 --- /dev/null +++ b/code/matlab/BPSK/receiver/rx_bpsk_demod.m @@ -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); + + diff --git a/code/matlab/BPSK/receiver/rx_channel_est.m b/code/matlab/BPSK/receiver/rx_channel_est.m new file mode 100755 index 0000000..4dd700b --- /dev/null +++ b/code/matlab/BPSK/receiver/rx_channel_est.m @@ -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); %еij; +uw_num = size(uw,2); %ֵij; +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 diff --git a/code/matlab/BPSK/receiver/rx_delete_pilot.m b/code/matlab/BPSK/receiver/rx_delete_pilot.m new file mode 100755 index 0000000..e6d28da --- /dev/null +++ b/code/matlab/BPSK/receiver/rx_delete_pilot.m @@ -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 + diff --git a/code/matlab/BPSK/receiver/rx_freq_sync.m b/code/matlab/BPSK/receiver/rx_freq_sync.m new file mode 100755 index 0000000..03512e9 --- /dev/null +++ b/code/matlab/BPSK/receiver/rx_freq_sync.m @@ -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 + diff --git a/code/matlab/BPSK/receiver/rx_package_search.m b/code/matlab/BPSK/receiver/rx_package_search.m new file mode 100755 index 0000000..aa004a9 --- /dev/null +++ b/code/matlab/BPSK/receiver/rx_package_search.m @@ -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 + diff --git a/code/matlab/BPSK/receiver/rx_package_search2.m b/code/matlab/BPSK/receiver/rx_package_search2.m new file mode 100755 index 0000000..50c23f6 --- /dev/null +++ b/code/matlab/BPSK/receiver/rx_package_search2.m @@ -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 + diff --git a/code/matlab/BPSK/receiver/rx_phase_sync.m b/code/matlab/BPSK/receiver/rx_phase_sync.m new file mode 100755 index 0000000..c43b1dc --- /dev/null +++ b/code/matlab/BPSK/receiver/rx_phase_sync.m @@ -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 + diff --git a/code/matlab/BPSK/receiver/rx_phase_track.m b/code/matlab/BPSK/receiver/rx_phase_track.m new file mode 100755 index 0000000..e5e56b1 --- /dev/null +++ b/code/matlab/BPSK/receiver/rx_phase_track.m @@ -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 diff --git a/code/matlab/BPSK/receiver/rx_qpsk_demod.m b/code/matlab/BPSK/receiver/rx_qpsk_demod.m new file mode 100755 index 0000000..d462e4d --- /dev/null +++ b/code/matlab/BPSK/receiver/rx_qpsk_demod.m @@ -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(:)'; \ No newline at end of file diff --git a/code/matlab/BPSK/receiver/rx_time_equalize.m b/code/matlab/BPSK/receiver/rx_time_equalize.m new file mode 100755 index 0000000..bc48a04 --- /dev/null +++ b/code/matlab/BPSK/receiver/rx_time_equalize.m @@ -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 \ No newline at end of file diff --git a/code/matlab/BPSK/receiver/rx_timing_recovery.m b/code/matlab/BPSK/receiver/rx_timing_recovery.m new file mode 100755 index 0000000..813c9fd --- /dev/null +++ b/code/matlab/BPSK/receiver/rx_timing_recovery.m @@ -0,0 +1,94 @@ +function [time_error,iq] = rx_timing_recovery(signal) + +N=ceil((length(signal))/4); +Ns=4*N; %ܵIJ + +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(i0) + 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 \ No newline at end of file diff --git a/code/matlab/BPSK/receiver/tx_gen_m_seq.m b/code/matlab/BPSK/receiver/tx_gen_m_seq.m new file mode 100755 index 0000000..9aa38e9 --- /dev/null +++ b/code/matlab/BPSK/receiver/tx_gen_m_seq.m @@ -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 + diff --git a/code/matlab/BPSK/receiver/tx_modulate.m b/code/matlab/BPSK/receiver/tx_modulate.m new file mode 100755 index 0000000..660e3f1 --- /dev/null +++ b/code/matlab/BPSK/receiver/tx_modulate.m @@ -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 + + + diff --git a/code/matlab/BPSK/transmitter/bpsk_tx_func.m b/code/matlab/BPSK/transmitter/bpsk_tx_func.m new file mode 100755 index 0000000..9661d0d --- /dev/null +++ b/code/matlab/BPSK/transmitter/bpsk_tx_func.m @@ -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 + diff --git a/code/matlab/BPSK/transmitter/crc32.m b/code/matlab/BPSK/transmitter/crc32.m new file mode 100755 index 0000000..6353ee6 --- /dev/null +++ b/code/matlab/BPSK/transmitter/crc32.m @@ -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 + 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 diff --git a/code/matlab/BPSK/transmitter/insert_pilot.m b/code/matlab/BPSK/transmitter/insert_pilot.m new file mode 100755 index 0000000..cdf130f --- /dev/null +++ b/code/matlab/BPSK/transmitter/insert_pilot.m @@ -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 \ No newline at end of file diff --git a/code/matlab/BPSK/transmitter/scramble.m b/code/matlab/BPSK/transmitter/scramble.m new file mode 100755 index 0000000..87aee0c --- /dev/null +++ b/code/matlab/BPSK/transmitter/scramble.m @@ -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; \ No newline at end of file diff --git a/code/matlab/BPSK/transmitter/str_to_bits.m b/code/matlab/BPSK/transmitter/str_to_bits.m new file mode 100755 index 0000000..cd294ca --- /dev/null +++ b/code/matlab/BPSK/transmitter/str_to_bits.m @@ -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 + diff --git a/code/matlab/BPSK/transmitter/tx_gen_m_seq.m b/code/matlab/BPSK/transmitter/tx_gen_m_seq.m new file mode 100755 index 0000000..9aa38e9 --- /dev/null +++ b/code/matlab/BPSK/transmitter/tx_gen_m_seq.m @@ -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 + diff --git a/code/matlab/BPSK/transmitter/tx_modulate.m b/code/matlab/BPSK/transmitter/tx_modulate.m new file mode 100755 index 0000000..7f8b56d --- /dev/null +++ b/code/matlab/BPSK/transmitter/tx_modulate.m @@ -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 + + + diff --git a/code/matlab/BPSK/transmitter/tx_prbs15.m b/code/matlab/BPSK/transmitter/tx_prbs15.m new file mode 100755 index 0000000..177a6b1 --- /dev/null +++ b/code/matlab/BPSK/transmitter/tx_prbs15.m @@ -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 diff --git a/code/matlab/slideWindow-receiver.m b/code/matlab/slideWindow-receiver.m new file mode 100644 index 0000000..807dbd8 --- /dev/null +++ b/code/matlab/slideWindow-receiver.m @@ -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(); diff --git a/code/matlab/slideWindow-sender.m b/code/matlab/slideWindow-sender.m new file mode 100755 index 0000000..cea2819 --- /dev/null +++ b/code/matlab/slideWindow-sender.m @@ -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(); + + + + + diff --git a/code/matlab/stop&Wait-sender.m b/code/matlab/stop&Wait-sender.m new file mode 100755 index 0000000..625607f --- /dev/null +++ b/code/matlab/stop&Wait-sender.m @@ -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(); + + + diff --git a/code/matlab/stop&wait-receiver.m b/code/matlab/stop&wait-receiver.m new file mode 100644 index 0000000..1faadcc --- /dev/null +++ b/code/matlab/stop&wait-receiver.m @@ -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(); + + + diff --git a/library/ad9361.cfg b/library/ad9361.cfg new file mode 100755 index 0000000..7e4b5bc --- /dev/null +++ b/library/ad9361.cfg @@ -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, diff --git a/library/iio.h b/library/iio.h new file mode 100755 index 0000000..3b47a9f --- /dev/null +++ b/library/iio.h @@ -0,0 +1,1589 @@ +/* + * libiio - Library for interfacing industrial I/O (IIO) devices + * + * Copyright (C) 2014 Analog Devices, Inc. + * Author: Paul Cercueil + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * */ + +/** @file iio.h + * @brief Public interface */ + +#ifndef __IIO_H__ +#define __IIO_H__ + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include +#include + +#if (defined(_WIN32) || defined(__MBED__)) +#ifndef _SSIZE_T_DEFINED +typedef ptrdiff_t ssize_t; +#define _SSIZE_T_DEFINED +#endif +#else +#include +#endif + +#if defined(_MSC_VER) && (_MSC_VER < 1800) && !defined(__BOOL_DEFINED) +#undef bool +#undef false +#undef true +#define bool char +#define false 0 +#define true 1 +#else +#include +#endif + +#if defined(__GNUC__) && !defined(MATLAB_MEX_FILE) && !defined(MATLAB_LOADLIBRARY) +#ifndef __cnst +#define __cnst __attribute__((const)) +#endif +#ifndef __pure +#define __pure __attribute__((pure)) +#endif +#define __notused __attribute__((unused)) +#else +#define __cnst +#define __pure +#define __notused +#endif + +#ifdef _WIN32 +# ifdef LIBIIO_EXPORTS +# define __api __declspec(dllexport) +# else +# define __api __declspec(dllimport) +# endif +#elif __GNUC__ >= 4 && !defined(MATLAB_MEX_FILE) && !defined(MATLAB_LOADLIBRARY) +# define __api __attribute__((visibility ("default"))) +#else +# define __api +#endif + +struct iio_context; +struct iio_device; +struct iio_channel; +struct iio_buffer; + +struct iio_context_info; +struct iio_scan_context; + +/** + * @enum iio_chan_type + * @brief IIO channel type + * + * A IIO channel has a type specifying the type of data associated with the + * channel. + */ +enum iio_chan_type { + IIO_VOLTAGE, + IIO_CURRENT, + IIO_POWER, + IIO_ACCEL, + IIO_ANGL_VEL, + IIO_MAGN, + IIO_LIGHT, + IIO_INTENSITY, + IIO_PROXIMITY, + IIO_TEMP, + IIO_INCLI, + IIO_ROT, + IIO_ANGL, + IIO_TIMESTAMP, + IIO_CAPACITANCE, + IIO_ALTVOLTAGE, + IIO_CCT, + IIO_PRESSURE, + IIO_HUMIDITYRELATIVE, + IIO_ACTIVITY, + IIO_STEPS, + IIO_ENERGY, + IIO_DISTANCE, + IIO_VELOCITY, + IIO_CONCENTRATION, + IIO_RESISTANCE, + IIO_PH, + IIO_CHAN_TYPE_UNKNOWN = INT_MAX +}; + +/** + * @enum iio_modifier + * @brief IIO channel modifier + * + * In a addition to a type a IIO channel can optionally have a channel modifier + * further specifying the data type of of the channel. + */ +enum iio_modifier { + IIO_NO_MOD, + IIO_MOD_X, + IIO_MOD_Y, + IIO_MOD_Z, + IIO_MOD_X_AND_Y, + IIO_MOD_X_AND_Z, + IIO_MOD_Y_AND_Z, + IIO_MOD_X_AND_Y_AND_Z, + IIO_MOD_X_OR_Y, + IIO_MOD_X_OR_Z, + IIO_MOD_Y_OR_Z, + IIO_MOD_X_OR_Y_OR_Z, + IIO_MOD_LIGHT_BOTH, + IIO_MOD_LIGHT_IR, + IIO_MOD_ROOT_SUM_SQUARED_X_Y, + IIO_MOD_SUM_SQUARED_X_Y_Z, + IIO_MOD_LIGHT_CLEAR, + IIO_MOD_LIGHT_RED, + IIO_MOD_LIGHT_GREEN, + IIO_MOD_LIGHT_BLUE, + IIO_MOD_QUATERNION, + IIO_MOD_TEMP_AMBIENT, + IIO_MOD_TEMP_OBJECT, + IIO_MOD_NORTH_MAGN, + IIO_MOD_NORTH_TRUE, + IIO_MOD_NORTH_MAGN_TILT_COMP, + IIO_MOD_NORTH_TRUE_TILT_COMP, + IIO_MOD_RUNNING, + IIO_MOD_JOGGING, + IIO_MOD_WALKING, + IIO_MOD_STILL, + IIO_MOD_ROOT_SUM_SQUARED_X_Y_Z, + IIO_MOD_I, + IIO_MOD_Q, + IIO_MOD_CO2, + IIO_MOD_VOC, +}; + +/* ---------------------------------------------------------------------------*/ +/* ------------------------- Scan functions ----------------------------------*/ +/** @defgroup Scan Functions for scanning available contexts + * @{ + * @struct iio_scan_context + * @brief The scanning context + * + * @struct iio_context_info + * @brief The information related to a discovered context + */ + + +/** @brief Create a scan context + * @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_context structure + * @return On failure, NULL is returned and errno is set appropriately */ +__api struct iio_scan_context * iio_create_scan_context( + const char *backend, unsigned int flags); + + +/** @brief Destroy the given scan context + * @param ctx A pointer to an iio_scan_context structure + * + * NOTE: After that function, the iio_scan_context pointer shall be invalid. */ +__api void iio_scan_context_destroy(struct iio_scan_context *ctx); + + +/** @brief Enumerate available contexts + * @param ctx A pointer to an iio_scan_context structure + * @param info A pointer to a 'const struct iio_context_info **' typed variable. + * The pointed variable will be initialized on success. + * @returns On success, the number of contexts found. + * @returns On failure, a negative error number. + */ +__api ssize_t iio_scan_context_get_info_list(struct iio_scan_context *ctx, + struct iio_context_info ***info); + + +/** @brief Free a context info list + * @param info A pointer to a 'const struct iio_context_info *' typed variable + */ +__api void iio_context_info_list_free(struct iio_context_info **info); + + +/** @brief Get a description of a discovered context + * @param info A pointer to an iio_context_info structure + * @return A pointer to a static NULL-terminated string + */ +__api __pure const char * iio_context_info_get_description( + const struct iio_context_info *info); + + +/** @brief Get the URI of a discovered context + * @param info A pointer to an iio_context_info structure + * @return A pointer to a static NULL-terminated string + */ +__api __pure const char * iio_context_info_get_uri( + const struct iio_context_info *info); + + +/** @} *//* ------------------------------------------------------------------*/ +/* ------------------------- Top-level functions -----------------------------*/ +/** @defgroup TopLevel Top-level functions + * @{ */ + + +/** @brief Get the version of the libiio library + * @param major A pointer to an unsigned integer (NULL accepted) + * @param minor A pointer to an unsigned integer (NULL accepted) + * @param git_tag A pointer to a 8-characters buffer (NULL accepted) */ +__api void iio_library_get_version(unsigned int *major, + unsigned int *minor, char git_tag[8]); + + +/** @brief Get a string description of an error code + * @param err The error code + * @param dst A pointer to the memory area where the NULL-terminated string + * corresponding to the error message will be stored + * @param len The available length of the memory area, in bytes */ +__api void iio_strerror(int err, char *dst, size_t len); + + +/** @brief Check if the specified backend is available + * @param backend The name of the backend to query + * @return True if the backend is available, false otherwise + * + * Introduced in version 0.9. */ +__api __cnst bool iio_has_backend(const char *backend); + + +/** @brief Get the number of available backends + * @return The number of available backends + * + * Introduced in version 0.9. */ +__api __cnst unsigned int iio_get_backends_count(void); + + +/** @brief Retrieve the name of a given backend + * @param index The index corresponding to the attribute + * @return On success, a pointer to a static NULL-terminated string + * @return If the index is invalid, NULL is returned + * + * Introduced in version 0.9. */ +__api __cnst const char * iio_get_backend(unsigned int index); + + +/** @} *//* ------------------------------------------------------------------*/ +/* ------------------------- Context functions -------------------------------*/ +/** @defgroup Context Context + * @{ + * @struct iio_context + * @brief Contains the representation of an IIO context */ + + +/** @brief Create a context from local or remote IIO devices + * @return On success, A pointer to an iio_context structure + * @return On failure, NULL is returned and errno is set appropriately + * + * NOTE: This function will create a network context if the IIOD_REMOTE + * environment variable is set to the hostname where the IIOD server runs. If + * set to an empty string, the server will be discovered using ZeroConf. + * If the environment variable is not set, a local context will be created + * instead. */ +__api struct iio_context * iio_create_default_context(void); + + +/** @brief Create a context from local IIO devices (Linux only) + * @return On success, A pointer to an iio_context structure + * @return On failure, NULL is returned and errno is set appropriately */ +__api struct iio_context * iio_create_local_context(void); + + +/** @brief Create a context from a XML file + * @param xml_file Path to the XML file to open + * @return On success, A pointer to an iio_context structure + * @return On failure, NULL is returned and errno is set appropriately + * + * NOTE: The format of the XML must comply to the one returned by + * iio_context_get_xml. */ +__api struct iio_context * iio_create_xml_context(const char *xml_file); + + +/** @brief Create a context from XML data in memory + * @param xml Pointer to the XML data in memory + * @param len Length of the XML string in memory (excluding the final \0) + * @return On success, A pointer to an iio_context structure + * @return On failure, NULL is returned and errno is set appropriately + * + * NOTE: The format of the XML must comply to the one returned by + * iio_context_get_xml */ +__api struct iio_context * iio_create_xml_context_mem( + const char *xml, size_t len); + + +/** @brief Create a context from the network + * @param host Hostname, IPv4 or IPv6 address where the IIO Daemon is running + * @return On success, a pointer to an iio_context structure + * @return On failure, NULL is returned and errno is set appropriately */ +__api struct iio_context * iio_create_network_context(const char *host); + + +/** @brief Create a context from a URI description + * @param uri A URI describing the context location + * @return On success, a pointer to a iio_context structure + * @return On failure, NULL is returned and errno is set appropriately */ +__api struct iio_context * iio_create_context_from_uri(const char *uri); + + +/** @brief Duplicate a pre-existing IIO context + * @param ctx A pointer to an iio_context structure + * @return On success, A pointer to an iio_context structure + * @return On failure, NULL is returned and errno is set appropriately */ +__api struct iio_context * iio_context_clone(const struct iio_context *ctx); + + +/** @brief Destroy the given context + * @param ctx A pointer to an iio_context structure + * + * NOTE: After that function, the iio_context pointer shall be invalid. */ +__api void iio_context_destroy(struct iio_context *ctx); + + +/** @brief Get the version of the backend in use + * @param ctx A pointer to an iio_context structure + * @param major A pointer to an unsigned integer (NULL accepted) + * @param minor A pointer to an unsigned integer (NULL accepted) + * @param git_tag A pointer to a 8-characters buffer (NULL accepted) + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_context_get_version(const struct iio_context *ctx, + unsigned int *major, unsigned int *minor, char git_tag[8]); + + +/** @brief Obtain a XML representation of the given context + * @param ctx A pointer to an iio_context structure + * @return A pointer to a static NULL-terminated string */ +__api __pure const char * iio_context_get_xml(const struct iio_context *ctx); + + +/** @brief Get the name of the given context + * @param ctx A pointer to an iio_context structure + * @return A pointer to a static NULL-terminated string + * + * NOTE:The returned string will be local, + * xml or network when the context has been + * created with the local, xml and network backends respectively.*/ +__api __pure const char * iio_context_get_name(const struct iio_context *ctx); + + +/** @brief Get a description of the given context + * @param ctx A pointer to an iio_context structure + * @return A pointer to a static NULL-terminated string + * + * NOTE:The returned string will contain human-readable information about + * the current context. */ +__api __pure const char * iio_context_get_description( + const struct iio_context *ctx); + + +/** @brief Get the number of context-specific attributes + * @param ctx A pointer to an iio_context structure + * @return The number of context-specific attributes + * + * Introduced in version 0.9. */ +__api __pure unsigned int iio_context_get_attrs_count( + const struct iio_context *ctx); + + +/** @brief Retrieve the name and value of a context-specific attribute + * @param ctx A pointer to an iio_context structure + * @param index The index corresponding to the attribute + * @param name A pointer to a const char * pointer (NULL accepted) + * @param value A pointer to a const char * pointer (NULL accepted) + * @return On success, 0 is returned + * @return On error, a negative errno code is returned + * + * Introduced in version 0.9. */ +__api int iio_context_get_attr( + const struct iio_context *ctx, unsigned int index, + const char **name, const char **value); + + +/** @brief Retrieve the value of a context-specific attribute + * @param ctx A pointer to an iio_context structure + * @param name The name of the context attribute to read + * @return On success, a pointer to a static NULL-terminated string + * @return If the name does not correspond to any attribute, NULL is + * returned + * + * Introduced in version 0.9. */ +__api const char * iio_context_get_attr_value( + const struct iio_context *ctx, const char *name); + + +/** @brief Enumerate the devices found in the given context + * @param ctx A pointer to an iio_context structure + * @return The number of devices found */ +__api __pure unsigned int iio_context_get_devices_count( + const struct iio_context *ctx); + + +/** @brief Get the device present at the given index + * @param ctx A pointer to an iio_context structure + * @param index The index corresponding to the device + * @return On success, a pointer to an iio_device structure + * @return If the index is invalid, NULL is returned */ +__api __pure struct iio_device * iio_context_get_device( + const struct iio_context *ctx, unsigned int index); + + +/** @brief Try to find a device structure by its name of ID + * @param ctx A pointer to an iio_context structure + * @param name A NULL-terminated string corresponding to the name or the ID of + * the device to search for + * @return On success, a pointer to an iio_device structure + * @return If the name or ID does not correspond to any known device, NULL is + * returned */ +__api __pure struct iio_device * iio_context_find_device( + const struct iio_context *ctx, const char *name); + + +/** @brief Set a timeout for I/O operations + * @param ctx A pointer to an iio_context structure + * @param timeout_ms A positive integer representing the time in milliseconds + * after which a timeout occurs. A value of 0 is used to specify that no + * timeout should occur. + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_context_set_timeout( + struct iio_context *ctx, unsigned int timeout_ms); + + +/** @} *//* ------------------------------------------------------------------*/ +/* ------------------------- Device functions --------------------------------*/ +/** @defgroup Device Device + * @{ + * @struct iio_device + * @brief Represents a device in the IIO context */ + + +/** @brief Retrieve a pointer to the iio_context structure + * @param dev A pointer to an iio_device structure + * @return A pointer to an iio_context structure */ +__api __pure const struct iio_context * iio_device_get_context( + const struct iio_device *dev); + + +/** @brief Retrieve the device ID (e.g. iio:device0) + * @param dev A pointer to an iio_device structure + * @return A pointer to a static NULL-terminated string */ +__api __pure const char * iio_device_get_id(const struct iio_device *dev); + + +/** @brief Retrieve the device name (e.g. xadc) + * @param dev A pointer to an iio_device structure + * @return A pointer to a static NULL-terminated string + * + * NOTE: if the device has no name, NULL is returned. */ +__api __pure const char * iio_device_get_name(const struct iio_device *dev); + + +/** @brief Enumerate the channels of the given device + * @param dev A pointer to an iio_device structure + * @return The number of channels found */ +__api __pure unsigned int iio_device_get_channels_count( + const struct iio_device *dev); + + +/** @brief Enumerate the device-specific attributes of the given device + * @param dev A pointer to an iio_device structure + * @return The number of device-specific attributes found */ +__api __pure unsigned int iio_device_get_attrs_count( + const struct iio_device *dev); + + +/** @brief Get the channel present at the given index + * @param dev A pointer to an iio_device structure + * @param index The index corresponding to the channel + * @return On success, a pointer to an iio_channel structure + * @return If the index is invalid, NULL is returned */ +__api __pure struct iio_channel * iio_device_get_channel( + const struct iio_device *dev, unsigned int index); + + +/** @brief Get the device-specific attribute present at the given index + * @param dev A pointer to an iio_device structure + * @param index The index corresponding to the attribute + * @return On success, a pointer to a static NULL-terminated string + * @return If the index is invalid, NULL is returned */ +__api __pure const char * iio_device_get_attr( + const struct iio_device *dev, unsigned int index); + + +/** @brief Try to find a channel structure by its name of ID + * @param dev A pointer to an iio_device structure + * @param name A NULL-terminated string corresponding to the name or the ID of + * the channel to search for + * @param output True if the searched channel is output, False otherwise + * @return On success, a pointer to an iio_channel structure + * @return If the name or ID does not correspond to any known channel of the + * given device, NULL is returned */ +__api __pure struct iio_channel * iio_device_find_channel( + const struct iio_device *dev, const char *name, bool output); + + +/** @brief Try to find a device-specific attribute by its name + * @param dev A pointer to an iio_device structure + * @param name A NULL-terminated string corresponding to the name of the + * attribute + * @return On success, a pointer to a static NULL-terminated string + * @return If the name does not correspond to any known attribute of the given + * device, NULL is returned + * + * NOTE: This function is useful to detect the presence of an attribute. + * It can also be used to retrieve the name of an attribute as a pointer to a + * static string from a dynamically allocated string. */ +__api __pure const char * iio_device_find_attr( + const struct iio_device *dev, const char *name); + + +/** @brief Read the content of the given device-specific attribute + * @param dev A pointer to an iio_device structure + * @param attr A NULL-terminated string corresponding to the name of the + * attribute + * @param dst A pointer to the memory area where the NULL-terminated string + * corresponding to the value read will be stored + * @param len The available length of the memory area, in bytes + * @return On success, the number of bytes written to the buffer + * @return On error, a negative errno code is returned + * + * NOTE:By passing NULL as the "attr" argument to iio_device_attr_read, + * it is now possible to read all of the attributes of a device. + * + * The buffer is filled with one block of data per attribute of the device, + * by the order they appear in the iio_device structure. + * + * The first four bytes of one block correspond to a 32-bit signed value in + * network order. If negative, it corresponds to the errno code that were + * returned when reading the attribute; if positive, it corresponds to the + * length of the data read. In that case, the rest of the block contains + * the data. */ + __api ssize_t iio_device_attr_read(const struct iio_device *dev, + const char *attr, char *dst, size_t len); + + +/** @brief Read the content of all device-specific attributes + * @param dev A pointer to an iio_device structure + * @param cb A pointer to a callback function + * @param data A pointer that will be passed to the callback function + * @return On success, 0 is returned + * @return On error, a negative errno code is returned + * + * NOTE: This function is especially useful when used with the network + * backend, as all the device-specific attributes are read in one single + * command. */ +__api int iio_device_attr_read_all(struct iio_device *dev, + int (*cb)(struct iio_device *dev, const char *attr, + const char *value, size_t len, void *d), + void *data); + + +/** @brief Read the content of the given device-specific attribute + * @param dev A pointer to an iio_device structure + * @param attr A NULL-terminated string corresponding to the name of the + * attribute + * @param val A pointer to a bool variable where the value should be stored + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_device_attr_read_bool(const struct iio_device *dev, + const char *attr, bool *val); + + +/** @brief Read the content of the given device-specific attribute + * @param dev A pointer to an iio_device structure + * @param attr A NULL-terminated string corresponding to the name of the + * attribute + * @param val A pointer to a long long variable where the value should be stored + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_device_attr_read_longlong(const struct iio_device *dev, + const char *attr, long long *val); + + +/** @brief Read the content of the given device-specific attribute + * @param dev A pointer to an iio_device structure + * @param attr A NULL-terminated string corresponding to the name of the + * attribute + * @param val A pointer to a double variable where the value should be stored + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_device_attr_read_double(const struct iio_device *dev, + const char *attr, double *val); + + +/** @brief Set the value of the given device-specific attribute + * @param dev A pointer to an iio_device structure + * @param attr A NULL-terminated string corresponding to the name of the + * attribute + * @param src A NULL-terminated string to set the attribute to + * @return On success, the number of bytes written + * @return On error, a negative errno code is returned + * + * NOTE:By passing NULL as the "attr" argument to iio_device_attr_write, + * it is now possible to write all of the attributes of a device. + * + * The buffer must contain one block of data per attribute of the device, + * by the order they appear in the iio_device structure. + * + * The first four bytes of one block correspond to a 32-bit signed value in + * network order. If negative, the attribute is not written; if positive, + * it corresponds to the length of the data to write. In that case, the rest + * of the block must contain the data. */ +__api ssize_t iio_device_attr_write(const struct iio_device *dev, + const char *attr, const char *src); + + +/** @brief Set the value of the given device-specific attribute + * @param dev A pointer to an iio_device structure + * @param attr A NULL-terminated string corresponding to the name of the + * attribute + * @param src A pointer to the data to be written + * @param len The number of bytes that should be written + * @return On success, the number of bytes written + * @return On error, a negative errno code is returned */ +__api ssize_t iio_device_attr_write_raw(const struct iio_device *dev, + const char *attr, const void *src, size_t len); + + +/** @brief Set the values of all device-specific attributes + * @param dev A pointer to an iio_device structure + * @param cb A pointer to a callback function + * @param data A pointer that will be passed to the callback function + * @return On success, 0 is returned + * @return On error, a negative errno code is returned + * + * NOTE: This function is especially useful when used with the network + * backend, as all the device-specific attributes are written in one single + * command. */ +__api int iio_device_attr_write_all(struct iio_device *dev, + ssize_t (*cb)(struct iio_device *dev, + const char *attr, void *buf, size_t len, void *d), + void *data); + + +/** @brief Set the value of the given device-specific attribute + * @param dev A pointer to an iio_device structure + * @param attr A NULL-terminated string corresponding to the name of the + * attribute + * @param val A bool value to set the attribute to + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_device_attr_write_bool(const struct iio_device *dev, + const char *attr, bool val); + + +/** @brief Set the value of the given device-specific attribute + * @param dev A pointer to an iio_device structure + * @param attr A NULL-terminated string corresponding to the name of the + * attribute + * @param val A long long value to set the attribute to + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_device_attr_write_longlong(const struct iio_device *dev, + const char *attr, long long val); + + +/** @brief Set the value of the given device-specific attribute + * @param dev A pointer to an iio_device structure + * @param attr A NULL-terminated string corresponding to the name of the + * attribute + * @param val A double value to set the attribute to + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_device_attr_write_double(const struct iio_device *dev, + const char *attr, double val); + + +/** @brief Associate a pointer to an iio_device structure + * @param dev A pointer to an iio_device structure + * @param data The pointer to be associated */ +__api void iio_device_set_data(struct iio_device *dev, void *data); + + +/** @brief Retrieve a previously associated pointer of an iio_device structure + * @param dev A pointer to an iio_device structure + * @return The pointer previously associated if present, or NULL */ +__api void * iio_device_get_data(const struct iio_device *dev); + + +/** @brief Retrieve the trigger of a given device + * @param dev A pointer to an iio_device structure + * @param trigger a pointer to a pointer of an iio_device structure. The pointed + * pointer will be set to the address of the iio_device structure corresponding + * to the associated trigger device. + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_device_get_trigger(const struct iio_device *dev, + const struct iio_device **trigger); + + +/** @brief Associate a trigger to a given device + * @param dev A pointer to an iio_device structure + * @param trigger a pointer to the iio_device structure corresponding to the + * trigger that should be associated. + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_device_set_trigger(const struct iio_device *dev, + const struct iio_device *trigger); + + +/** @brief Return True if the given device is a trigger + * @param dev A pointer to an iio_device structure + * @return True if the device is a trigger, False otherwise */ +__api __pure bool iio_device_is_trigger(const struct iio_device *dev); + +/** + * @brief Configure the number of kernel buffers for a device + * + * This function allows to change the number of buffers on kernel side. + * @param dev A pointer to an iio_device structure + * @param nb_buffers The number of buffers + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_device_set_kernel_buffers_count(const struct iio_device *dev, + unsigned int nb_buffers); + +/** @} *//* ------------------------------------------------------------------*/ +/* ------------------------- Channel functions -------------------------------*/ +/** @defgroup Channel Channel + * @{ + * @struct iio_channel + * @brief Represents an input or output channel of a device */ + + +/** @brief Retrieve a pointer to the iio_device structure + * @param chn A pointer to an iio_channel structure + * @return A pointer to an iio_device structure */ +__api __pure const struct iio_device * iio_channel_get_device( + const struct iio_channel *chn); + + +/** @brief Retrieve the channel ID (e.g. voltage0) + * @param chn A pointer to an iio_channel structure + * @return A pointer to a static NULL-terminated string */ +__api __pure const char * iio_channel_get_id(const struct iio_channel *chn); + + +/** @brief Retrieve the channel name (e.g. vccint) + * @param chn A pointer to an iio_channel structure + * @return A pointer to a static NULL-terminated string + * + * NOTE: if the channel has no name, NULL is returned. */ +__api __pure const char * iio_channel_get_name(const struct iio_channel *chn); + + +/** @brief Return True if the given channel is an output channel + * @param chn A pointer to an iio_channel structure + * @return True if the channel is an output channel, False otherwise */ +__api __pure bool iio_channel_is_output(const struct iio_channel *chn); + + +/** @brief Return True if the given channel is a scan element + * @param chn A pointer to an iio_channel structure + * @return True if the channel is a scan element, False otherwise + * + * NOTE: a channel that is a scan element is a channel that can + * generate samples (for an input channel) or receive samples (for an output + * channel) after being enabled. */ +__api __pure bool iio_channel_is_scan_element(const struct iio_channel *chn); + + +/** @brief Enumerate the channel-specific attributes of the given channel + * @param chn A pointer to an iio_channel structure + * @return The number of channel-specific attributes found */ +__api __pure unsigned int iio_channel_get_attrs_count( + const struct iio_channel *chn); + + +/** @brief Get the channel-specific attribute present at the given index + * @param chn A pointer to an iio_channel structure + * @param index The index corresponding to the attribute + * @return On success, a pointer to a static NULL-terminated string + * @return If the index is invalid, NULL is returned */ +__api __pure const char * iio_channel_get_attr( + const struct iio_channel *chn, unsigned int index); + + +/** @brief Try to find a channel-specific attribute by its name + * @param chn A pointer to an iio_channel structure + * @param name A NULL-terminated string corresponding to the name of the + * attribute + * @return On success, a pointer to a static NULL-terminated string + * @return If the name does not correspond to any known attribute of the given + * channel, NULL is returned + * + * NOTE: This function is useful to detect the presence of an attribute. + * It can also be used to retrieve the name of an attribute as a pointer to a + * static string from a dynamically allocated string. */ +__api __pure const char * iio_channel_find_attr( + const struct iio_channel *chn, const char *name); + + +/** @brief Retrieve the filename of an attribute + * @param chn A pointer to an iio_channel structure + * @param attr a NULL-terminated string corresponding to the name of the + * attribute + * @return On success, a pointer to a static NULL-terminated string + * @return If the attribute name is unknown, NULL is returned */ +__api __pure const char * iio_channel_attr_get_filename( + const struct iio_channel *chn, const char *attr); + + +/** @brief Read the content of the given channel-specific attribute + * @param chn A pointer to an iio_channel structure + * @param attr A NULL-terminated string corresponding to the name of the + * attribute + * @param dst A pointer to the memory area where the NULL-terminated string + * corresponding to the value read will be stored + * @param len The available length of the memory area, in bytes + * @return On success, the number of bytes written to the buffer + * @return On error, a negative errno code is returned + * + * NOTE:By passing NULL as the "attr" argument to iio_channel_attr_read, + * it is now possible to read all of the attributes of a channel. + * + * The buffer is filled with one block of data per attribute of the channel, + * by the order they appear in the iio_channel structure. + * + * The first four bytes of one block correspond to a 32-bit signed value in + * network order. If negative, it corresponds to the errno code that were + * returned when reading the attribute; if positive, it corresponds to the + * length of the data read. In that case, the rest of the block contains + * the data. */ +__api ssize_t iio_channel_attr_read(const struct iio_channel *chn, + const char *attr, char *dst, size_t len); + + +/** @brief Read the content of all channel-specific attributes + * @param chn A pointer to an iio_channel structure + * @param cb A pointer to a callback function + * @param data A pointer that will be passed to the callback function + * @return On success, 0 is returned + * @return On error, a negative errno code is returned + * + * NOTE: This function is especially useful when used with the network + * backend, as all the channel-specific attributes are read in one single + * command. */ +__api int iio_channel_attr_read_all(struct iio_channel *chn, + int (*cb)(struct iio_channel *chn, + const char *attr, const char *val, size_t len, void *d), + void *data); + + +/** @brief Read the content of the given channel-specific attribute + * @param chn A pointer to an iio_channel structure + * @param attr A NULL-terminated string corresponding to the name of the + * attribute + * @param val A pointer to a bool variable where the value should be stored + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_channel_attr_read_bool(const struct iio_channel *chn, + const char *attr, bool *val); + + +/** @brief Read the content of the given channel-specific attribute + * @param chn A pointer to an iio_channel structure + * @param attr A NULL-terminated string corresponding to the name of the + * attribute + * @param val A pointer to a long long variable where the value should be stored + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_channel_attr_read_longlong(const struct iio_channel *chn, + const char *attr, long long *val); + + +/** @brief Read the content of the given channel-specific attribute + * @param chn A pointer to an iio_channel structure + * @param attr A NULL-terminated string corresponding to the name of the + * attribute + * @param val A pointer to a double variable where the value should be stored + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_channel_attr_read_double(const struct iio_channel *chn, + const char *attr, double *val); + + +/** @brief Set the value of the given channel-specific attribute + * @param chn A pointer to an iio_channel structure + * @param attr A NULL-terminated string corresponding to the name of the + * attribute + * @param src A NULL-terminated string to set the attribute to + * @return On success, the number of bytes written + * @return On error, a negative errno code is returned + * + * NOTE:By passing NULL as the "attr" argument to iio_channel_attr_write, + * it is now possible to write all of the attributes of a channel. + * + * The buffer must contain one block of data per attribute of the channel, + * by the order they appear in the iio_channel structure. + * + * The first four bytes of one block correspond to a 32-bit signed value in + * network order. If negative, the attribute is not written; if positive, + * it corresponds to the length of the data to write. In that case, the rest + * of the block must contain the data. */ +__api ssize_t iio_channel_attr_write(const struct iio_channel *chn, + const char *attr, const char *src); + + +/** @brief Set the value of the given channel-specific attribute + * @param chn A pointer to an iio_channel structure + * @param attr A NULL-terminated string corresponding to the name of the + * attribute + * @param src A pointer to the data to be written + * @param len The number of bytes that should be written + * @return On success, the number of bytes written + * @return On error, a negative errno code is returned */ +__api ssize_t iio_channel_attr_write_raw(const struct iio_channel *chn, + const char *attr, const void *src, size_t len); + + +/** @brief Set the values of all channel-specific attributes + * @param chn A pointer to an iio_channel structure + * @param cb A pointer to a callback function + * @param data A pointer that will be passed to the callback function + * @return On success, 0 is returned + * @return On error, a negative errno code is returned + * + * NOTE: This function is especially useful when used with the network + * backend, as all the channel-specific attributes are written in one single + * command. */ +__api int iio_channel_attr_write_all(struct iio_channel *chn, + ssize_t (*cb)(struct iio_channel *chn, + const char *attr, void *buf, size_t len, void *d), + void *data); + + +/** @brief Set the value of the given channel-specific attribute + * @param chn A pointer to an iio_channel structure + * @param attr A NULL-terminated string corresponding to the name of the + * attribute + * @param val A bool value to set the attribute to + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_channel_attr_write_bool(const struct iio_channel *chn, + const char *attr, bool val); + + +/** @brief Set the value of the given channel-specific attribute + * @param chn A pointer to an iio_channel structure + * @param attr A NULL-terminated string corresponding to the name of the + * attribute + * @param val A long long value to set the attribute to + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_channel_attr_write_longlong(const struct iio_channel *chn, + const char *attr, long long val); + + +/** @brief Set the value of the given channel-specific attribute + * @param chn A pointer to an iio_channel structure + * @param attr A NULL-terminated string corresponding to the name of the + * attribute + * @param val A double value to set the attribute to + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_channel_attr_write_double(const struct iio_channel *chn, + const char *attr, double val); + + +/** @brief Enable the given channel + * @param chn A pointer to an iio_channel structure + * + * NOTE:Before creating an iio_buffer structure with + * iio_device_create_buffer, it is required to enable at least one channel of + * the device to read from. */ +__api void iio_channel_enable(struct iio_channel *chn); + + +/** @brief Disable the given channel + * @param chn A pointer to an iio_channel structure */ +__api void iio_channel_disable(struct iio_channel *chn); + + +/** @brief Returns True if the channel is enabled + * @param chn A pointer to an iio_channel structure + * @return True if the channel is enabled, False otherwise */ +__api bool iio_channel_is_enabled(const struct iio_channel *chn); + + +/** Demultiplex the samples of a given channel + * @param chn A pointer to an iio_channel structure + * @param buffer A pointer to an iio_buffer structure + * @param dst A pointer to the memory area where the demultiplexed data will be + * stored + * @param len The available length of the memory area, in bytes + * @return The size of the demultiplexed data, in bytes */ +__api size_t iio_channel_read_raw(const struct iio_channel *chn, + struct iio_buffer *buffer, void *dst, size_t len); + + +/** Demultiplex and convert the samples of a given channel + * @param chn A pointer to an iio_channel structure + * @param buffer A pointer to an iio_buffer structure + * @param dst A pointer to the memory area where the converted data will be + * stored + * @param len The available length of the memory area, in bytes + * @return The size of the converted data, in bytes */ +__api size_t iio_channel_read(const struct iio_channel *chn, + struct iio_buffer *buffer, void *dst, size_t len); + + +/** Multiplex the samples of a given channel + * @param chn A pointer to an iio_channel structure + * @param buffer A pointer to an iio_buffer structure + * @param src A pointer to the memory area where the sequential data will + * be read from + * @param len The length of the memory area, in bytes + * @return The number of bytes actually multiplexed */ +__api size_t iio_channel_write_raw(const struct iio_channel *chn, + struct iio_buffer *buffer, const void *src, size_t len); + + +/** Convert and multiplex the samples of a given channel + * @param chn A pointer to an iio_channel structure + * @param buffer A pointer to an iio_buffer structure + * @param src A pointer to the memory area where the sequential data will + * be read from + * @param len The length of the memory area, in bytes + * @return The number of bytes actually converted and multiplexed */ +__api size_t iio_channel_write(const struct iio_channel *chn, + struct iio_buffer *buffer, const void *src, size_t len); + + +/** @brief Associate a pointer to an iio_channel structure + * @param chn A pointer to an iio_channel structure + * @param data The pointer to be associated */ +__api void iio_channel_set_data(struct iio_channel *chn, void *data); + + +/** @brief Retrieve a previously associated pointer of an iio_channel structure + * @param chn A pointer to an iio_channel structure + * @return The pointer previously associated if present, or NULL */ +__api void * iio_channel_get_data(const struct iio_channel *chn); + + +/** @brief Get the type of the given channel + * @param chn A pointer to an iio_channel structure + * @return The type of the channel */ +__api __pure enum iio_chan_type iio_channel_get_type( + const struct iio_channel *chn); + + +/** @brief Get the modifier type of the given channel + * @param chn A pointer to an iio_channel structure + * @return The modifier type of the channel */ +__api __pure enum iio_modifier iio_channel_get_modifier( + const struct iio_channel *chn); + + +/** @} *//* ------------------------------------------------------------------*/ +/* ------------------------- Buffer functions --------------------------------*/ +/** @defgroup Buffer Buffer + * @{ + * @struct iio_buffer + * @brief An input or output buffer, used to read or write samples */ + + +/** @brief Retrieve a pointer to the iio_device structure + * @param buf A pointer to an iio_buffer structure + * @return A pointer to an iio_device structure */ +__api __pure const struct iio_device * iio_buffer_get_device( + const struct iio_buffer *buf); + + +/** @brief Create an input or output buffer associated to the given device + * @param dev A pointer to an iio_device structure + * @param samples_count The number of samples that the buffer should contain + * @param cyclic If True, enable cyclic mode + * @return On success, a pointer to an iio_buffer structure + * @return On error, NULL is returned, and errno is set to the error code + * + * NOTE: Channels that have to be written to / read from must be enabled + * before creating the buffer. */ +__api struct iio_buffer * iio_device_create_buffer(const struct iio_device *dev, + size_t samples_count, bool cyclic); + + +/** @brief Destroy the given buffer + * @param buf A pointer to an iio_buffer structure + * + * NOTE: After that function, the iio_buffer pointer shall be invalid. */ +__api void iio_buffer_destroy(struct iio_buffer *buf); + +/** @brief Get a pollable file descriptor + * + * Can be used to know when iio_buffer_refill() or iio_buffer_push() can be + * called + * @param buf A pointer to an iio_buffer structure + * @return On success, valid file descriptor + * @return On error, a negative errno code is returned + */ +__api int iio_buffer_get_poll_fd(struct iio_buffer *buf); + +/** @brief Make iio_buffer_refill() and iio_buffer_push() blocking or not + * + * After this function has been called with blocking == false, + * iio_buffer_refill() and iio_buffer_push() will return -EAGAIN if no data is + * ready. + * A device is blocking by default. + * @param buf A pointer to an iio_buffer structure + * @param blocking true if the buffer API should be blocking, else false + * @return On success, 0 + * @return On error, a negative errno code is returned + */ +__api int iio_buffer_set_blocking_mode(struct iio_buffer *buf, bool blocking); + + +/** @brief Fetch more samples from the hardware + * @param buf A pointer to an iio_buffer structure + * @return On success, the number of bytes read is returned + * @return On error, a negative errno code is returned + * + * NOTE: Only valid for input buffers */ +__api ssize_t iio_buffer_refill(struct iio_buffer *buf); + + +/** @brief Send the samples to the hardware + * @param buf A pointer to an iio_buffer structure + * @return On success, the number of bytes written is returned + * @return On error, a negative errno code is returned + * + * NOTE: Only valid for output buffers */ +__api ssize_t iio_buffer_push(struct iio_buffer *buf); + + +/** @brief Send a given number of samples to the hardware + * @param buf A pointer to an iio_buffer structure + * @param samples_count The number of samples to submit + * @return On success, the number of bytes written is returned + * @return On error, a negative errno code is returned + * + * NOTE: Only valid for output buffers */ +__api ssize_t iio_buffer_push_partial(struct iio_buffer *buf, + size_t samples_count); + +/** @brief Cancel all buffer operations + * @param buf The buffer for which operations should be canceled + * + * This function cancels all outstanding buffer operations previously scheduled. + * This means any pending iio_buffer_push() or iio_buffer_refill() operation + * will abort and return immediately, any further invocations of these functions + * on the same buffer will return immediately with an error. + * + * Usually iio_buffer_push() and iio_buffer_refill() will block until either all + * data has been transferred or a timeout occurs. This can depending on the + * configuration take a significant amount of time. iio_buffer_cancel() is + * useful to bypass these conditions if the buffer operation is supposed to be + * stopped in response to an external event (e.g. user input). + * + * To be able to capture additional data after calling this function the buffer + * should be destroyed and then re-created. + * + * This function can be called multiple times for the same buffer, but all but + * the first invocation will be without additional effect. + * + * This function is thread-safe, but not signal-safe, i.e. it must not be called + * from a signal handler. + */ +__api void iio_buffer_cancel(struct iio_buffer *buf); + + +/** @brief Get the start address of the buffer + * @param buf A pointer to an iio_buffer structure + * @return A pointer corresponding to the start address of the buffer */ +__api void * iio_buffer_start(const struct iio_buffer *buf); + + +/** @brief Find the first sample of a channel in a buffer + * @param buf A pointer to an iio_buffer structure + * @param chn A pointer to an iio_channel structure + * @return A pointer to the first sample found, or to the end of the buffer if + * no sample for the given channel is present in the buffer + * + * NOTE: This fonction, coupled with iio_buffer_step and iio_buffer_end, + * can be used to iterate on all the samples of a given channel present in the + * buffer, doing the following: + * + * @verbatim + for (void *ptr = iio_buffer_first(buffer, chn); ptr < iio_buffer_end(buffer); ptr += iio_buffer_step(buffer)) { + .... + } + @endverbatim */ +__api void * iio_buffer_first(const struct iio_buffer *buf, + const struct iio_channel *chn); + + +/** @brief Get the step size between two samples of one channel + * @param buf A pointer to an iio_buffer structure + * @return the difference between the addresses of two consecutive samples of + * one same channel */ +__api ptrdiff_t iio_buffer_step(const struct iio_buffer *buf); + + +/** @brief Get the address that follows the last sample in a buffer + * @param buf A pointer to an iio_buffer structure + * @return A pointer corresponding to the address that follows the last sample + * present in the buffer */ +__api void * iio_buffer_end(const struct iio_buffer *buf); + + +/** @brief Call the supplied callback for each sample found in a buffer + * @param buf A pointer to an iio_buffer structure + * @param callback A pointer to a function to call for each sample found + * @param data A user-specified pointer that will be passed to the callback + * @return number of bytes processed. + * + * NOTE: The callback receives four arguments: + * * A pointer to the iio_channel structure corresponding to the sample, + * * A pointer to the sample itself, + * * The length of the sample in bytes, + * * The user-specified pointer passed to iio_buffer_foreach_sample. */ +__api ssize_t iio_buffer_foreach_sample(struct iio_buffer *buf, + ssize_t (*callback)(const struct iio_channel *chn, + void *src, size_t bytes, void *d), void *data); + + +/** @brief Associate a pointer to an iio_buffer structure + * @param buf A pointer to an iio_buffer structure + * @param data The pointer to be associated */ +__api void iio_buffer_set_data(struct iio_buffer *buf, void *data); + + +/** @brief Retrieve a previously associated pointer of an iio_buffer structure + * @param buf A pointer to an iio_buffer structure + * @return The pointer previously associated if present, or NULL */ +__api void * iio_buffer_get_data(const struct iio_buffer *buf); + + +/** @} *//* ------------------------------------------------------------------*/ +/* ------------------------- Low-level functions -----------------------------*/ +/** @defgroup Debug Debug and low-level functions + * @{ + * @struct iio_data_format + * @brief Contains the format of a data sample. + * + * The different fields inform about the correct way to convert one sample from + * its raw format (as read from / generated by the hardware) to its real-world + * value. + */ +struct iio_data_format { + /** @brief Total length of the sample, in bits */ + unsigned int length; + + /** @brief Length of valuable data in the sample, in bits */ + unsigned int bits; + + /** @brief Right-shift to apply when converting sample */ + unsigned int shift; + + /** @brief Contains True if the sample is signed */ + bool is_signed; + + /** @brief Contains True if the sample is fully defined, sign extended, etc. */ + bool is_fully_defined; + + /** @brief Contains True if the sample is in big-endian format */ + bool is_be; + + /** @brief Contains True if the sample should be scaled when converted */ + bool with_scale; + + /** @brief Contains the scale to apply if with_scale is set */ + double scale; + + /** @brief Number of times length repeats (added in v0.8) */ + unsigned int repeat; +}; + + +/** @brief Get the current sample size + * @param dev A pointer to an iio_device structure + * @return On success, the sample size in bytes + * @return On error, a negative errno code is returned + * + * NOTE: The sample size is not constant and will change when channels + * get enabled or disabled. */ +__api ssize_t iio_device_get_sample_size(const struct iio_device *dev); + + +/** @brief Get the index of the given channel + * @param chn A pointer to an iio_channel structure + * @return On success, the index of the specified channel + * @return On error, a negative errno code is returned */ +__api __pure long iio_channel_get_index(const struct iio_channel *chn); + + +/** @brief Get a pointer to a channel's data format structure + * @param chn A pointer to an iio_channel structure + * @return A pointer to the channel's iio_data_format structure */ +__api __cnst const struct iio_data_format * iio_channel_get_data_format( + const struct iio_channel *chn); + + +/** @brief Convert the sample from hardware format to host format + * @param chn A pointer to an iio_channel structure + * @param dst A pointer to the destination buffer where the converted sample + * should be written + * @param src A pointer to the source buffer containing the sample */ +__api void iio_channel_convert(const struct iio_channel *chn, + void *dst, const void *src); + + +/** @brief Convert the sample from host format to hardware format + * @param chn A pointer to an iio_channel structure + * @param dst A pointer to the destination buffer where the converted sample + * should be written + * @param src A pointer to the source buffer containing the sample */ +__api void iio_channel_convert_inverse(const struct iio_channel *chn, + void *dst, const void *src); + + +/** @brief Enumerate the debug attributes of the given device + * @param dev A pointer to an iio_device structure + * @return The number of debug attributes found */ +__api __pure unsigned int iio_device_get_debug_attrs_count( + const struct iio_device *dev); + + +/** @brief Get the debug attribute present at the given index + * @param dev A pointer to an iio_device structure + * @param index The index corresponding to the debug attribute + * @return On success, a pointer to a static NULL-terminated string + * @return If the index is invalid, NULL is returned */ +__api __pure const char * iio_device_get_debug_attr( + const struct iio_device *dev, unsigned int index); + + +/** @brief Try to find a debug attribute by its name + * @param dev A pointer to an iio_device structure + * @param name A NULL-terminated string corresponding to the name of the + * debug attribute + * @return On success, a pointer to a static NULL-terminated string + * @return If the name does not correspond to any known debug attribute of the + * given device, NULL is returned + * + * NOTE: This function is useful to detect the presence of a debug + * attribute. + * It can also be used to retrieve the name of a debug attribute as a pointer + * to a static string from a dynamically allocated string. */ +__api __pure const char * iio_device_find_debug_attr( + const struct iio_device *dev, const char *name); + + +/** @brief Read the content of the given debug attribute + * @param dev A pointer to an iio_device structure + * @param attr A NULL-terminated string corresponding to the name of the + * debug attribute + * @param dst A pointer to the memory area where the NULL-terminated string + * corresponding to the value read will be stored + * @param len The available length of the memory area, in bytes + * @return On success, the number of bytes written to the buffer + * @return On error, a negative errno code is returned + * + * NOTE:By passing NULL as the "attr" argument to + * iio_device_debug_attr_read, it is now possible to read all of the debug + * attributes of a device. + * + * The buffer is filled with one block of data per debug attribute of the + * device, by the order they appear in the iio_device structure. + * + * The first four bytes of one block correspond to a 32-bit signed value in + * network order. If negative, it corresponds to the errno code that were + * returned when reading the debug attribute; if positive, it corresponds + * to the length of the data read. In that case, the rest of the block contains + * the data. */ +__api ssize_t iio_device_debug_attr_read(const struct iio_device *dev, + const char *attr, char *dst, size_t len); + + +/** @brief Read the content of all debug attributes + * @param dev A pointer to an iio_device structure + * @param cb A pointer to a callback function + * @param data A pointer that will be passed to the callback function + * @return On success, 0 is returned + * @return On error, a negative errno code is returned + * + * NOTE: This function is especially useful when used with the network + * backend, as all the debug attributes are read in one single command. */ +__api int iio_device_debug_attr_read_all(struct iio_device *dev, + int (*cb)(struct iio_device *dev, const char *attr, + const char *value, size_t len, void *d), + void *data); + + +/** @brief Set the value of the given debug attribute + * @param dev A pointer to an iio_device structure + * @param attr A NULL-terminated string corresponding to the name of the + * debug attribute + * @param src A NULL-terminated string to set the debug attribute to + * @return On success, the number of bytes written + * @return On error, a negative errno code is returned + * + * NOTE:By passing NULL as the "attr" argument to + * iio_device_debug_attr_write, it is now possible to write all of the + * debug attributes of a device. + * + * The buffer must contain one block of data per debug attribute of the device, + * by the order they appear in the iio_device structure. + * + * The first four bytes of one block correspond to a 32-bit signed value in + * network order. If negative, the debug attribute is not written; if positive, + * it corresponds to the length of the data to write. In that case, the rest + * of the block must contain the data. */ +__api ssize_t iio_device_debug_attr_write(const struct iio_device *dev, + const char *attr, const char *src); + + +/** @brief Set the value of the given debug attribute + * @param dev A pointer to an iio_device structure + * @param attr A NULL-terminated string corresponding to the name of the + * debug attribute + * @param src A pointer to the data to be written + * @param len The number of bytes that should be written + * @return On success, the number of bytes written + * @return On error, a negative errno code is returned */ +__api ssize_t iio_device_debug_attr_write_raw(const struct iio_device *dev, + const char *attr, const void *src, size_t len); + + +/** @brief Set the values of all debug attributes + * @param dev A pointer to an iio_device structure + * @param cb A pointer to a callback function + * @param data A pointer that will be passed to the callback function + * @return On success, 0 is returned + * @return On error, a negative errno code is returned + * + * NOTE: This function is especially useful when used with the network + * backend, as all the debug attributes are written in one single command. */ +__api int iio_device_debug_attr_write_all(struct iio_device *dev, + ssize_t (*cb)(struct iio_device *dev, + const char *attr, void *buf, size_t len, void *d), + void *data); + + +/** @brief Read the content of the given debug attribute + * @param dev A pointer to an iio_device structure + * @param attr A NULL-terminated string corresponding to the name of the + * debug attribute + * @param val A pointer to a bool variable where the value should be stored + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_device_debug_attr_read_bool(const struct iio_device *dev, + const char *attr, bool *val); + + +/** @brief Read the content of the given debug attribute + * @param dev A pointer to an iio_device structure + * @param attr A NULL-terminated string corresponding to the name of the + * debug attribute + * @param val A pointer to a long long variable where the value should be stored + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_device_debug_attr_read_longlong(const struct iio_device *dev, + const char *attr, long long *val); + + +/** @brief Read the content of the given debug attribute + * @param dev A pointer to an iio_device structure + * @param attr A NULL-terminated string corresponding to the name of the + * debug attribute + * @param val A pointer to a double variable where the value should be stored + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_device_debug_attr_read_double(const struct iio_device *dev, + const char *attr, double *val); + + +/** @brief Set the value of the given debug attribute + * @param dev A pointer to an iio_device structure + * @param attr A NULL-terminated string corresponding to the name of the + * debug attribute + * @param val A bool value to set the debug attribute to + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_device_debug_attr_write_bool(const struct iio_device *dev, + const char *attr, bool val); + + +/** @brief Set the value of the given debug attribute + * @param dev A pointer to an iio_device structure + * @param attr A NULL-terminated string corresponding to the name of the + * debug attribute + * @param val A long long value to set the debug attribute to + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_device_debug_attr_write_longlong(const struct iio_device *dev, + const char *attr, long long val); + + +/** @brief Set the value of the given debug attribute + * @param dev A pointer to an iio_device structure + * @param attr A NULL-terminated string corresponding to the name of the + * debug attribute + * @param val A double value to set the debug attribute to + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_device_debug_attr_write_double(const struct iio_device *dev, + const char *attr, double val); + + +/** @brief Identify the channel or debug attribute corresponding to a filename + * @param dev A pointer to an iio_device structure + * @param filename A NULL-terminated string corresponding to the filename + * @param chn A pointer to a pointer of an iio_channel structure. The pointed + * pointer will be set to the address of the iio_channel structure if the + * filename correspond to the attribute of a channel, or NULL otherwise. + * @param attr A pointer to a NULL-terminated string. The pointer + * pointer will be set to point to the name of the attribute corresponding to + * the filename. + * @return On success, 0 is returned, and *chn and *attr are modified. + * @return On error, a negative errno code is returned. *chn and *attr are not + * modified. */ +__api int iio_device_identify_filename(const struct iio_device *dev, + const char *filename, struct iio_channel **chn, + const char **attr); + + +/** @brief Set the value of a hardware register + * @param dev A pointer to an iio_device structure + * @param address The address of the register + * @param value The value to set the register to + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_device_reg_write(struct iio_device *dev, + uint32_t address, uint32_t value); + + +/** @brief Get the value of a hardware register + * @param dev A pointer to an iio_device structure + * @param address The address of the register + * @param value A pointer to the variable where the value will be written + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_device_reg_read(struct iio_device *dev, + uint32_t address, uint32_t *value); + + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#undef __api + +#endif /* __IIO_H__ */ diff --git a/library/matlab/ad9361.cfg b/library/matlab/ad9361.cfg new file mode 100755 index 0000000..7e4b5bc --- /dev/null +++ b/library/matlab/ad9361.cfg @@ -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, diff --git a/library/matlab/iio-wrapper.h b/library/matlab/iio-wrapper.h new file mode 100755 index 0000000..3e918ac --- /dev/null +++ b/library/matlab/iio-wrapper.h @@ -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 +* +* NOTE: 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 diff --git a/library/matlab/iio.h b/library/matlab/iio.h new file mode 100755 index 0000000..3b47a9f --- /dev/null +++ b/library/matlab/iio.h @@ -0,0 +1,1589 @@ +/* + * libiio - Library for interfacing industrial I/O (IIO) devices + * + * Copyright (C) 2014 Analog Devices, Inc. + * Author: Paul Cercueil + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * */ + +/** @file iio.h + * @brief Public interface */ + +#ifndef __IIO_H__ +#define __IIO_H__ + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include +#include + +#if (defined(_WIN32) || defined(__MBED__)) +#ifndef _SSIZE_T_DEFINED +typedef ptrdiff_t ssize_t; +#define _SSIZE_T_DEFINED +#endif +#else +#include +#endif + +#if defined(_MSC_VER) && (_MSC_VER < 1800) && !defined(__BOOL_DEFINED) +#undef bool +#undef false +#undef true +#define bool char +#define false 0 +#define true 1 +#else +#include +#endif + +#if defined(__GNUC__) && !defined(MATLAB_MEX_FILE) && !defined(MATLAB_LOADLIBRARY) +#ifndef __cnst +#define __cnst __attribute__((const)) +#endif +#ifndef __pure +#define __pure __attribute__((pure)) +#endif +#define __notused __attribute__((unused)) +#else +#define __cnst +#define __pure +#define __notused +#endif + +#ifdef _WIN32 +# ifdef LIBIIO_EXPORTS +# define __api __declspec(dllexport) +# else +# define __api __declspec(dllimport) +# endif +#elif __GNUC__ >= 4 && !defined(MATLAB_MEX_FILE) && !defined(MATLAB_LOADLIBRARY) +# define __api __attribute__((visibility ("default"))) +#else +# define __api +#endif + +struct iio_context; +struct iio_device; +struct iio_channel; +struct iio_buffer; + +struct iio_context_info; +struct iio_scan_context; + +/** + * @enum iio_chan_type + * @brief IIO channel type + * + * A IIO channel has a type specifying the type of data associated with the + * channel. + */ +enum iio_chan_type { + IIO_VOLTAGE, + IIO_CURRENT, + IIO_POWER, + IIO_ACCEL, + IIO_ANGL_VEL, + IIO_MAGN, + IIO_LIGHT, + IIO_INTENSITY, + IIO_PROXIMITY, + IIO_TEMP, + IIO_INCLI, + IIO_ROT, + IIO_ANGL, + IIO_TIMESTAMP, + IIO_CAPACITANCE, + IIO_ALTVOLTAGE, + IIO_CCT, + IIO_PRESSURE, + IIO_HUMIDITYRELATIVE, + IIO_ACTIVITY, + IIO_STEPS, + IIO_ENERGY, + IIO_DISTANCE, + IIO_VELOCITY, + IIO_CONCENTRATION, + IIO_RESISTANCE, + IIO_PH, + IIO_CHAN_TYPE_UNKNOWN = INT_MAX +}; + +/** + * @enum iio_modifier + * @brief IIO channel modifier + * + * In a addition to a type a IIO channel can optionally have a channel modifier + * further specifying the data type of of the channel. + */ +enum iio_modifier { + IIO_NO_MOD, + IIO_MOD_X, + IIO_MOD_Y, + IIO_MOD_Z, + IIO_MOD_X_AND_Y, + IIO_MOD_X_AND_Z, + IIO_MOD_Y_AND_Z, + IIO_MOD_X_AND_Y_AND_Z, + IIO_MOD_X_OR_Y, + IIO_MOD_X_OR_Z, + IIO_MOD_Y_OR_Z, + IIO_MOD_X_OR_Y_OR_Z, + IIO_MOD_LIGHT_BOTH, + IIO_MOD_LIGHT_IR, + IIO_MOD_ROOT_SUM_SQUARED_X_Y, + IIO_MOD_SUM_SQUARED_X_Y_Z, + IIO_MOD_LIGHT_CLEAR, + IIO_MOD_LIGHT_RED, + IIO_MOD_LIGHT_GREEN, + IIO_MOD_LIGHT_BLUE, + IIO_MOD_QUATERNION, + IIO_MOD_TEMP_AMBIENT, + IIO_MOD_TEMP_OBJECT, + IIO_MOD_NORTH_MAGN, + IIO_MOD_NORTH_TRUE, + IIO_MOD_NORTH_MAGN_TILT_COMP, + IIO_MOD_NORTH_TRUE_TILT_COMP, + IIO_MOD_RUNNING, + IIO_MOD_JOGGING, + IIO_MOD_WALKING, + IIO_MOD_STILL, + IIO_MOD_ROOT_SUM_SQUARED_X_Y_Z, + IIO_MOD_I, + IIO_MOD_Q, + IIO_MOD_CO2, + IIO_MOD_VOC, +}; + +/* ---------------------------------------------------------------------------*/ +/* ------------------------- Scan functions ----------------------------------*/ +/** @defgroup Scan Functions for scanning available contexts + * @{ + * @struct iio_scan_context + * @brief The scanning context + * + * @struct iio_context_info + * @brief The information related to a discovered context + */ + + +/** @brief Create a scan context + * @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_context structure + * @return On failure, NULL is returned and errno is set appropriately */ +__api struct iio_scan_context * iio_create_scan_context( + const char *backend, unsigned int flags); + + +/** @brief Destroy the given scan context + * @param ctx A pointer to an iio_scan_context structure + * + * NOTE: After that function, the iio_scan_context pointer shall be invalid. */ +__api void iio_scan_context_destroy(struct iio_scan_context *ctx); + + +/** @brief Enumerate available contexts + * @param ctx A pointer to an iio_scan_context structure + * @param info A pointer to a 'const struct iio_context_info **' typed variable. + * The pointed variable will be initialized on success. + * @returns On success, the number of contexts found. + * @returns On failure, a negative error number. + */ +__api ssize_t iio_scan_context_get_info_list(struct iio_scan_context *ctx, + struct iio_context_info ***info); + + +/** @brief Free a context info list + * @param info A pointer to a 'const struct iio_context_info *' typed variable + */ +__api void iio_context_info_list_free(struct iio_context_info **info); + + +/** @brief Get a description of a discovered context + * @param info A pointer to an iio_context_info structure + * @return A pointer to a static NULL-terminated string + */ +__api __pure const char * iio_context_info_get_description( + const struct iio_context_info *info); + + +/** @brief Get the URI of a discovered context + * @param info A pointer to an iio_context_info structure + * @return A pointer to a static NULL-terminated string + */ +__api __pure const char * iio_context_info_get_uri( + const struct iio_context_info *info); + + +/** @} *//* ------------------------------------------------------------------*/ +/* ------------------------- Top-level functions -----------------------------*/ +/** @defgroup TopLevel Top-level functions + * @{ */ + + +/** @brief Get the version of the libiio library + * @param major A pointer to an unsigned integer (NULL accepted) + * @param minor A pointer to an unsigned integer (NULL accepted) + * @param git_tag A pointer to a 8-characters buffer (NULL accepted) */ +__api void iio_library_get_version(unsigned int *major, + unsigned int *minor, char git_tag[8]); + + +/** @brief Get a string description of an error code + * @param err The error code + * @param dst A pointer to the memory area where the NULL-terminated string + * corresponding to the error message will be stored + * @param len The available length of the memory area, in bytes */ +__api void iio_strerror(int err, char *dst, size_t len); + + +/** @brief Check if the specified backend is available + * @param backend The name of the backend to query + * @return True if the backend is available, false otherwise + * + * Introduced in version 0.9. */ +__api __cnst bool iio_has_backend(const char *backend); + + +/** @brief Get the number of available backends + * @return The number of available backends + * + * Introduced in version 0.9. */ +__api __cnst unsigned int iio_get_backends_count(void); + + +/** @brief Retrieve the name of a given backend + * @param index The index corresponding to the attribute + * @return On success, a pointer to a static NULL-terminated string + * @return If the index is invalid, NULL is returned + * + * Introduced in version 0.9. */ +__api __cnst const char * iio_get_backend(unsigned int index); + + +/** @} *//* ------------------------------------------------------------------*/ +/* ------------------------- Context functions -------------------------------*/ +/** @defgroup Context Context + * @{ + * @struct iio_context + * @brief Contains the representation of an IIO context */ + + +/** @brief Create a context from local or remote IIO devices + * @return On success, A pointer to an iio_context structure + * @return On failure, NULL is returned and errno is set appropriately + * + * NOTE: This function will create a network context if the IIOD_REMOTE + * environment variable is set to the hostname where the IIOD server runs. If + * set to an empty string, the server will be discovered using ZeroConf. + * If the environment variable is not set, a local context will be created + * instead. */ +__api struct iio_context * iio_create_default_context(void); + + +/** @brief Create a context from local IIO devices (Linux only) + * @return On success, A pointer to an iio_context structure + * @return On failure, NULL is returned and errno is set appropriately */ +__api struct iio_context * iio_create_local_context(void); + + +/** @brief Create a context from a XML file + * @param xml_file Path to the XML file to open + * @return On success, A pointer to an iio_context structure + * @return On failure, NULL is returned and errno is set appropriately + * + * NOTE: The format of the XML must comply to the one returned by + * iio_context_get_xml. */ +__api struct iio_context * iio_create_xml_context(const char *xml_file); + + +/** @brief Create a context from XML data in memory + * @param xml Pointer to the XML data in memory + * @param len Length of the XML string in memory (excluding the final \0) + * @return On success, A pointer to an iio_context structure + * @return On failure, NULL is returned and errno is set appropriately + * + * NOTE: The format of the XML must comply to the one returned by + * iio_context_get_xml */ +__api struct iio_context * iio_create_xml_context_mem( + const char *xml, size_t len); + + +/** @brief Create a context from the network + * @param host Hostname, IPv4 or IPv6 address where the IIO Daemon is running + * @return On success, a pointer to an iio_context structure + * @return On failure, NULL is returned and errno is set appropriately */ +__api struct iio_context * iio_create_network_context(const char *host); + + +/** @brief Create a context from a URI description + * @param uri A URI describing the context location + * @return On success, a pointer to a iio_context structure + * @return On failure, NULL is returned and errno is set appropriately */ +__api struct iio_context * iio_create_context_from_uri(const char *uri); + + +/** @brief Duplicate a pre-existing IIO context + * @param ctx A pointer to an iio_context structure + * @return On success, A pointer to an iio_context structure + * @return On failure, NULL is returned and errno is set appropriately */ +__api struct iio_context * iio_context_clone(const struct iio_context *ctx); + + +/** @brief Destroy the given context + * @param ctx A pointer to an iio_context structure + * + * NOTE: After that function, the iio_context pointer shall be invalid. */ +__api void iio_context_destroy(struct iio_context *ctx); + + +/** @brief Get the version of the backend in use + * @param ctx A pointer to an iio_context structure + * @param major A pointer to an unsigned integer (NULL accepted) + * @param minor A pointer to an unsigned integer (NULL accepted) + * @param git_tag A pointer to a 8-characters buffer (NULL accepted) + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_context_get_version(const struct iio_context *ctx, + unsigned int *major, unsigned int *minor, char git_tag[8]); + + +/** @brief Obtain a XML representation of the given context + * @param ctx A pointer to an iio_context structure + * @return A pointer to a static NULL-terminated string */ +__api __pure const char * iio_context_get_xml(const struct iio_context *ctx); + + +/** @brief Get the name of the given context + * @param ctx A pointer to an iio_context structure + * @return A pointer to a static NULL-terminated string + * + * NOTE:The returned string will be local, + * xml or network when the context has been + * created with the local, xml and network backends respectively.*/ +__api __pure const char * iio_context_get_name(const struct iio_context *ctx); + + +/** @brief Get a description of the given context + * @param ctx A pointer to an iio_context structure + * @return A pointer to a static NULL-terminated string + * + * NOTE:The returned string will contain human-readable information about + * the current context. */ +__api __pure const char * iio_context_get_description( + const struct iio_context *ctx); + + +/** @brief Get the number of context-specific attributes + * @param ctx A pointer to an iio_context structure + * @return The number of context-specific attributes + * + * Introduced in version 0.9. */ +__api __pure unsigned int iio_context_get_attrs_count( + const struct iio_context *ctx); + + +/** @brief Retrieve the name and value of a context-specific attribute + * @param ctx A pointer to an iio_context structure + * @param index The index corresponding to the attribute + * @param name A pointer to a const char * pointer (NULL accepted) + * @param value A pointer to a const char * pointer (NULL accepted) + * @return On success, 0 is returned + * @return On error, a negative errno code is returned + * + * Introduced in version 0.9. */ +__api int iio_context_get_attr( + const struct iio_context *ctx, unsigned int index, + const char **name, const char **value); + + +/** @brief Retrieve the value of a context-specific attribute + * @param ctx A pointer to an iio_context structure + * @param name The name of the context attribute to read + * @return On success, a pointer to a static NULL-terminated string + * @return If the name does not correspond to any attribute, NULL is + * returned + * + * Introduced in version 0.9. */ +__api const char * iio_context_get_attr_value( + const struct iio_context *ctx, const char *name); + + +/** @brief Enumerate the devices found in the given context + * @param ctx A pointer to an iio_context structure + * @return The number of devices found */ +__api __pure unsigned int iio_context_get_devices_count( + const struct iio_context *ctx); + + +/** @brief Get the device present at the given index + * @param ctx A pointer to an iio_context structure + * @param index The index corresponding to the device + * @return On success, a pointer to an iio_device structure + * @return If the index is invalid, NULL is returned */ +__api __pure struct iio_device * iio_context_get_device( + const struct iio_context *ctx, unsigned int index); + + +/** @brief Try to find a device structure by its name of ID + * @param ctx A pointer to an iio_context structure + * @param name A NULL-terminated string corresponding to the name or the ID of + * the device to search for + * @return On success, a pointer to an iio_device structure + * @return If the name or ID does not correspond to any known device, NULL is + * returned */ +__api __pure struct iio_device * iio_context_find_device( + const struct iio_context *ctx, const char *name); + + +/** @brief Set a timeout for I/O operations + * @param ctx A pointer to an iio_context structure + * @param timeout_ms A positive integer representing the time in milliseconds + * after which a timeout occurs. A value of 0 is used to specify that no + * timeout should occur. + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_context_set_timeout( + struct iio_context *ctx, unsigned int timeout_ms); + + +/** @} *//* ------------------------------------------------------------------*/ +/* ------------------------- Device functions --------------------------------*/ +/** @defgroup Device Device + * @{ + * @struct iio_device + * @brief Represents a device in the IIO context */ + + +/** @brief Retrieve a pointer to the iio_context structure + * @param dev A pointer to an iio_device structure + * @return A pointer to an iio_context structure */ +__api __pure const struct iio_context * iio_device_get_context( + const struct iio_device *dev); + + +/** @brief Retrieve the device ID (e.g. iio:device0) + * @param dev A pointer to an iio_device structure + * @return A pointer to a static NULL-terminated string */ +__api __pure const char * iio_device_get_id(const struct iio_device *dev); + + +/** @brief Retrieve the device name (e.g. xadc) + * @param dev A pointer to an iio_device structure + * @return A pointer to a static NULL-terminated string + * + * NOTE: if the device has no name, NULL is returned. */ +__api __pure const char * iio_device_get_name(const struct iio_device *dev); + + +/** @brief Enumerate the channels of the given device + * @param dev A pointer to an iio_device structure + * @return The number of channels found */ +__api __pure unsigned int iio_device_get_channels_count( + const struct iio_device *dev); + + +/** @brief Enumerate the device-specific attributes of the given device + * @param dev A pointer to an iio_device structure + * @return The number of device-specific attributes found */ +__api __pure unsigned int iio_device_get_attrs_count( + const struct iio_device *dev); + + +/** @brief Get the channel present at the given index + * @param dev A pointer to an iio_device structure + * @param index The index corresponding to the channel + * @return On success, a pointer to an iio_channel structure + * @return If the index is invalid, NULL is returned */ +__api __pure struct iio_channel * iio_device_get_channel( + const struct iio_device *dev, unsigned int index); + + +/** @brief Get the device-specific attribute present at the given index + * @param dev A pointer to an iio_device structure + * @param index The index corresponding to the attribute + * @return On success, a pointer to a static NULL-terminated string + * @return If the index is invalid, NULL is returned */ +__api __pure const char * iio_device_get_attr( + const struct iio_device *dev, unsigned int index); + + +/** @brief Try to find a channel structure by its name of ID + * @param dev A pointer to an iio_device structure + * @param name A NULL-terminated string corresponding to the name or the ID of + * the channel to search for + * @param output True if the searched channel is output, False otherwise + * @return On success, a pointer to an iio_channel structure + * @return If the name or ID does not correspond to any known channel of the + * given device, NULL is returned */ +__api __pure struct iio_channel * iio_device_find_channel( + const struct iio_device *dev, const char *name, bool output); + + +/** @brief Try to find a device-specific attribute by its name + * @param dev A pointer to an iio_device structure + * @param name A NULL-terminated string corresponding to the name of the + * attribute + * @return On success, a pointer to a static NULL-terminated string + * @return If the name does not correspond to any known attribute of the given + * device, NULL is returned + * + * NOTE: This function is useful to detect the presence of an attribute. + * It can also be used to retrieve the name of an attribute as a pointer to a + * static string from a dynamically allocated string. */ +__api __pure const char * iio_device_find_attr( + const struct iio_device *dev, const char *name); + + +/** @brief Read the content of the given device-specific attribute + * @param dev A pointer to an iio_device structure + * @param attr A NULL-terminated string corresponding to the name of the + * attribute + * @param dst A pointer to the memory area where the NULL-terminated string + * corresponding to the value read will be stored + * @param len The available length of the memory area, in bytes + * @return On success, the number of bytes written to the buffer + * @return On error, a negative errno code is returned + * + * NOTE:By passing NULL as the "attr" argument to iio_device_attr_read, + * it is now possible to read all of the attributes of a device. + * + * The buffer is filled with one block of data per attribute of the device, + * by the order they appear in the iio_device structure. + * + * The first four bytes of one block correspond to a 32-bit signed value in + * network order. If negative, it corresponds to the errno code that were + * returned when reading the attribute; if positive, it corresponds to the + * length of the data read. In that case, the rest of the block contains + * the data. */ + __api ssize_t iio_device_attr_read(const struct iio_device *dev, + const char *attr, char *dst, size_t len); + + +/** @brief Read the content of all device-specific attributes + * @param dev A pointer to an iio_device structure + * @param cb A pointer to a callback function + * @param data A pointer that will be passed to the callback function + * @return On success, 0 is returned + * @return On error, a negative errno code is returned + * + * NOTE: This function is especially useful when used with the network + * backend, as all the device-specific attributes are read in one single + * command. */ +__api int iio_device_attr_read_all(struct iio_device *dev, + int (*cb)(struct iio_device *dev, const char *attr, + const char *value, size_t len, void *d), + void *data); + + +/** @brief Read the content of the given device-specific attribute + * @param dev A pointer to an iio_device structure + * @param attr A NULL-terminated string corresponding to the name of the + * attribute + * @param val A pointer to a bool variable where the value should be stored + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_device_attr_read_bool(const struct iio_device *dev, + const char *attr, bool *val); + + +/** @brief Read the content of the given device-specific attribute + * @param dev A pointer to an iio_device structure + * @param attr A NULL-terminated string corresponding to the name of the + * attribute + * @param val A pointer to a long long variable where the value should be stored + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_device_attr_read_longlong(const struct iio_device *dev, + const char *attr, long long *val); + + +/** @brief Read the content of the given device-specific attribute + * @param dev A pointer to an iio_device structure + * @param attr A NULL-terminated string corresponding to the name of the + * attribute + * @param val A pointer to a double variable where the value should be stored + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_device_attr_read_double(const struct iio_device *dev, + const char *attr, double *val); + + +/** @brief Set the value of the given device-specific attribute + * @param dev A pointer to an iio_device structure + * @param attr A NULL-terminated string corresponding to the name of the + * attribute + * @param src A NULL-terminated string to set the attribute to + * @return On success, the number of bytes written + * @return On error, a negative errno code is returned + * + * NOTE:By passing NULL as the "attr" argument to iio_device_attr_write, + * it is now possible to write all of the attributes of a device. + * + * The buffer must contain one block of data per attribute of the device, + * by the order they appear in the iio_device structure. + * + * The first four bytes of one block correspond to a 32-bit signed value in + * network order. If negative, the attribute is not written; if positive, + * it corresponds to the length of the data to write. In that case, the rest + * of the block must contain the data. */ +__api ssize_t iio_device_attr_write(const struct iio_device *dev, + const char *attr, const char *src); + + +/** @brief Set the value of the given device-specific attribute + * @param dev A pointer to an iio_device structure + * @param attr A NULL-terminated string corresponding to the name of the + * attribute + * @param src A pointer to the data to be written + * @param len The number of bytes that should be written + * @return On success, the number of bytes written + * @return On error, a negative errno code is returned */ +__api ssize_t iio_device_attr_write_raw(const struct iio_device *dev, + const char *attr, const void *src, size_t len); + + +/** @brief Set the values of all device-specific attributes + * @param dev A pointer to an iio_device structure + * @param cb A pointer to a callback function + * @param data A pointer that will be passed to the callback function + * @return On success, 0 is returned + * @return On error, a negative errno code is returned + * + * NOTE: This function is especially useful when used with the network + * backend, as all the device-specific attributes are written in one single + * command. */ +__api int iio_device_attr_write_all(struct iio_device *dev, + ssize_t (*cb)(struct iio_device *dev, + const char *attr, void *buf, size_t len, void *d), + void *data); + + +/** @brief Set the value of the given device-specific attribute + * @param dev A pointer to an iio_device structure + * @param attr A NULL-terminated string corresponding to the name of the + * attribute + * @param val A bool value to set the attribute to + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_device_attr_write_bool(const struct iio_device *dev, + const char *attr, bool val); + + +/** @brief Set the value of the given device-specific attribute + * @param dev A pointer to an iio_device structure + * @param attr A NULL-terminated string corresponding to the name of the + * attribute + * @param val A long long value to set the attribute to + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_device_attr_write_longlong(const struct iio_device *dev, + const char *attr, long long val); + + +/** @brief Set the value of the given device-specific attribute + * @param dev A pointer to an iio_device structure + * @param attr A NULL-terminated string corresponding to the name of the + * attribute + * @param val A double value to set the attribute to + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_device_attr_write_double(const struct iio_device *dev, + const char *attr, double val); + + +/** @brief Associate a pointer to an iio_device structure + * @param dev A pointer to an iio_device structure + * @param data The pointer to be associated */ +__api void iio_device_set_data(struct iio_device *dev, void *data); + + +/** @brief Retrieve a previously associated pointer of an iio_device structure + * @param dev A pointer to an iio_device structure + * @return The pointer previously associated if present, or NULL */ +__api void * iio_device_get_data(const struct iio_device *dev); + + +/** @brief Retrieve the trigger of a given device + * @param dev A pointer to an iio_device structure + * @param trigger a pointer to a pointer of an iio_device structure. The pointed + * pointer will be set to the address of the iio_device structure corresponding + * to the associated trigger device. + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_device_get_trigger(const struct iio_device *dev, + const struct iio_device **trigger); + + +/** @brief Associate a trigger to a given device + * @param dev A pointer to an iio_device structure + * @param trigger a pointer to the iio_device structure corresponding to the + * trigger that should be associated. + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_device_set_trigger(const struct iio_device *dev, + const struct iio_device *trigger); + + +/** @brief Return True if the given device is a trigger + * @param dev A pointer to an iio_device structure + * @return True if the device is a trigger, False otherwise */ +__api __pure bool iio_device_is_trigger(const struct iio_device *dev); + +/** + * @brief Configure the number of kernel buffers for a device + * + * This function allows to change the number of buffers on kernel side. + * @param dev A pointer to an iio_device structure + * @param nb_buffers The number of buffers + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_device_set_kernel_buffers_count(const struct iio_device *dev, + unsigned int nb_buffers); + +/** @} *//* ------------------------------------------------------------------*/ +/* ------------------------- Channel functions -------------------------------*/ +/** @defgroup Channel Channel + * @{ + * @struct iio_channel + * @brief Represents an input or output channel of a device */ + + +/** @brief Retrieve a pointer to the iio_device structure + * @param chn A pointer to an iio_channel structure + * @return A pointer to an iio_device structure */ +__api __pure const struct iio_device * iio_channel_get_device( + const struct iio_channel *chn); + + +/** @brief Retrieve the channel ID (e.g. voltage0) + * @param chn A pointer to an iio_channel structure + * @return A pointer to a static NULL-terminated string */ +__api __pure const char * iio_channel_get_id(const struct iio_channel *chn); + + +/** @brief Retrieve the channel name (e.g. vccint) + * @param chn A pointer to an iio_channel structure + * @return A pointer to a static NULL-terminated string + * + * NOTE: if the channel has no name, NULL is returned. */ +__api __pure const char * iio_channel_get_name(const struct iio_channel *chn); + + +/** @brief Return True if the given channel is an output channel + * @param chn A pointer to an iio_channel structure + * @return True if the channel is an output channel, False otherwise */ +__api __pure bool iio_channel_is_output(const struct iio_channel *chn); + + +/** @brief Return True if the given channel is a scan element + * @param chn A pointer to an iio_channel structure + * @return True if the channel is a scan element, False otherwise + * + * NOTE: a channel that is a scan element is a channel that can + * generate samples (for an input channel) or receive samples (for an output + * channel) after being enabled. */ +__api __pure bool iio_channel_is_scan_element(const struct iio_channel *chn); + + +/** @brief Enumerate the channel-specific attributes of the given channel + * @param chn A pointer to an iio_channel structure + * @return The number of channel-specific attributes found */ +__api __pure unsigned int iio_channel_get_attrs_count( + const struct iio_channel *chn); + + +/** @brief Get the channel-specific attribute present at the given index + * @param chn A pointer to an iio_channel structure + * @param index The index corresponding to the attribute + * @return On success, a pointer to a static NULL-terminated string + * @return If the index is invalid, NULL is returned */ +__api __pure const char * iio_channel_get_attr( + const struct iio_channel *chn, unsigned int index); + + +/** @brief Try to find a channel-specific attribute by its name + * @param chn A pointer to an iio_channel structure + * @param name A NULL-terminated string corresponding to the name of the + * attribute + * @return On success, a pointer to a static NULL-terminated string + * @return If the name does not correspond to any known attribute of the given + * channel, NULL is returned + * + * NOTE: This function is useful to detect the presence of an attribute. + * It can also be used to retrieve the name of an attribute as a pointer to a + * static string from a dynamically allocated string. */ +__api __pure const char * iio_channel_find_attr( + const struct iio_channel *chn, const char *name); + + +/** @brief Retrieve the filename of an attribute + * @param chn A pointer to an iio_channel structure + * @param attr a NULL-terminated string corresponding to the name of the + * attribute + * @return On success, a pointer to a static NULL-terminated string + * @return If the attribute name is unknown, NULL is returned */ +__api __pure const char * iio_channel_attr_get_filename( + const struct iio_channel *chn, const char *attr); + + +/** @brief Read the content of the given channel-specific attribute + * @param chn A pointer to an iio_channel structure + * @param attr A NULL-terminated string corresponding to the name of the + * attribute + * @param dst A pointer to the memory area where the NULL-terminated string + * corresponding to the value read will be stored + * @param len The available length of the memory area, in bytes + * @return On success, the number of bytes written to the buffer + * @return On error, a negative errno code is returned + * + * NOTE:By passing NULL as the "attr" argument to iio_channel_attr_read, + * it is now possible to read all of the attributes of a channel. + * + * The buffer is filled with one block of data per attribute of the channel, + * by the order they appear in the iio_channel structure. + * + * The first four bytes of one block correspond to a 32-bit signed value in + * network order. If negative, it corresponds to the errno code that were + * returned when reading the attribute; if positive, it corresponds to the + * length of the data read. In that case, the rest of the block contains + * the data. */ +__api ssize_t iio_channel_attr_read(const struct iio_channel *chn, + const char *attr, char *dst, size_t len); + + +/** @brief Read the content of all channel-specific attributes + * @param chn A pointer to an iio_channel structure + * @param cb A pointer to a callback function + * @param data A pointer that will be passed to the callback function + * @return On success, 0 is returned + * @return On error, a negative errno code is returned + * + * NOTE: This function is especially useful when used with the network + * backend, as all the channel-specific attributes are read in one single + * command. */ +__api int iio_channel_attr_read_all(struct iio_channel *chn, + int (*cb)(struct iio_channel *chn, + const char *attr, const char *val, size_t len, void *d), + void *data); + + +/** @brief Read the content of the given channel-specific attribute + * @param chn A pointer to an iio_channel structure + * @param attr A NULL-terminated string corresponding to the name of the + * attribute + * @param val A pointer to a bool variable where the value should be stored + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_channel_attr_read_bool(const struct iio_channel *chn, + const char *attr, bool *val); + + +/** @brief Read the content of the given channel-specific attribute + * @param chn A pointer to an iio_channel structure + * @param attr A NULL-terminated string corresponding to the name of the + * attribute + * @param val A pointer to a long long variable where the value should be stored + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_channel_attr_read_longlong(const struct iio_channel *chn, + const char *attr, long long *val); + + +/** @brief Read the content of the given channel-specific attribute + * @param chn A pointer to an iio_channel structure + * @param attr A NULL-terminated string corresponding to the name of the + * attribute + * @param val A pointer to a double variable where the value should be stored + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_channel_attr_read_double(const struct iio_channel *chn, + const char *attr, double *val); + + +/** @brief Set the value of the given channel-specific attribute + * @param chn A pointer to an iio_channel structure + * @param attr A NULL-terminated string corresponding to the name of the + * attribute + * @param src A NULL-terminated string to set the attribute to + * @return On success, the number of bytes written + * @return On error, a negative errno code is returned + * + * NOTE:By passing NULL as the "attr" argument to iio_channel_attr_write, + * it is now possible to write all of the attributes of a channel. + * + * The buffer must contain one block of data per attribute of the channel, + * by the order they appear in the iio_channel structure. + * + * The first four bytes of one block correspond to a 32-bit signed value in + * network order. If negative, the attribute is not written; if positive, + * it corresponds to the length of the data to write. In that case, the rest + * of the block must contain the data. */ +__api ssize_t iio_channel_attr_write(const struct iio_channel *chn, + const char *attr, const char *src); + + +/** @brief Set the value of the given channel-specific attribute + * @param chn A pointer to an iio_channel structure + * @param attr A NULL-terminated string corresponding to the name of the + * attribute + * @param src A pointer to the data to be written + * @param len The number of bytes that should be written + * @return On success, the number of bytes written + * @return On error, a negative errno code is returned */ +__api ssize_t iio_channel_attr_write_raw(const struct iio_channel *chn, + const char *attr, const void *src, size_t len); + + +/** @brief Set the values of all channel-specific attributes + * @param chn A pointer to an iio_channel structure + * @param cb A pointer to a callback function + * @param data A pointer that will be passed to the callback function + * @return On success, 0 is returned + * @return On error, a negative errno code is returned + * + * NOTE: This function is especially useful when used with the network + * backend, as all the channel-specific attributes are written in one single + * command. */ +__api int iio_channel_attr_write_all(struct iio_channel *chn, + ssize_t (*cb)(struct iio_channel *chn, + const char *attr, void *buf, size_t len, void *d), + void *data); + + +/** @brief Set the value of the given channel-specific attribute + * @param chn A pointer to an iio_channel structure + * @param attr A NULL-terminated string corresponding to the name of the + * attribute + * @param val A bool value to set the attribute to + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_channel_attr_write_bool(const struct iio_channel *chn, + const char *attr, bool val); + + +/** @brief Set the value of the given channel-specific attribute + * @param chn A pointer to an iio_channel structure + * @param attr A NULL-terminated string corresponding to the name of the + * attribute + * @param val A long long value to set the attribute to + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_channel_attr_write_longlong(const struct iio_channel *chn, + const char *attr, long long val); + + +/** @brief Set the value of the given channel-specific attribute + * @param chn A pointer to an iio_channel structure + * @param attr A NULL-terminated string corresponding to the name of the + * attribute + * @param val A double value to set the attribute to + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_channel_attr_write_double(const struct iio_channel *chn, + const char *attr, double val); + + +/** @brief Enable the given channel + * @param chn A pointer to an iio_channel structure + * + * NOTE:Before creating an iio_buffer structure with + * iio_device_create_buffer, it is required to enable at least one channel of + * the device to read from. */ +__api void iio_channel_enable(struct iio_channel *chn); + + +/** @brief Disable the given channel + * @param chn A pointer to an iio_channel structure */ +__api void iio_channel_disable(struct iio_channel *chn); + + +/** @brief Returns True if the channel is enabled + * @param chn A pointer to an iio_channel structure + * @return True if the channel is enabled, False otherwise */ +__api bool iio_channel_is_enabled(const struct iio_channel *chn); + + +/** Demultiplex the samples of a given channel + * @param chn A pointer to an iio_channel structure + * @param buffer A pointer to an iio_buffer structure + * @param dst A pointer to the memory area where the demultiplexed data will be + * stored + * @param len The available length of the memory area, in bytes + * @return The size of the demultiplexed data, in bytes */ +__api size_t iio_channel_read_raw(const struct iio_channel *chn, + struct iio_buffer *buffer, void *dst, size_t len); + + +/** Demultiplex and convert the samples of a given channel + * @param chn A pointer to an iio_channel structure + * @param buffer A pointer to an iio_buffer structure + * @param dst A pointer to the memory area where the converted data will be + * stored + * @param len The available length of the memory area, in bytes + * @return The size of the converted data, in bytes */ +__api size_t iio_channel_read(const struct iio_channel *chn, + struct iio_buffer *buffer, void *dst, size_t len); + + +/** Multiplex the samples of a given channel + * @param chn A pointer to an iio_channel structure + * @param buffer A pointer to an iio_buffer structure + * @param src A pointer to the memory area where the sequential data will + * be read from + * @param len The length of the memory area, in bytes + * @return The number of bytes actually multiplexed */ +__api size_t iio_channel_write_raw(const struct iio_channel *chn, + struct iio_buffer *buffer, const void *src, size_t len); + + +/** Convert and multiplex the samples of a given channel + * @param chn A pointer to an iio_channel structure + * @param buffer A pointer to an iio_buffer structure + * @param src A pointer to the memory area where the sequential data will + * be read from + * @param len The length of the memory area, in bytes + * @return The number of bytes actually converted and multiplexed */ +__api size_t iio_channel_write(const struct iio_channel *chn, + struct iio_buffer *buffer, const void *src, size_t len); + + +/** @brief Associate a pointer to an iio_channel structure + * @param chn A pointer to an iio_channel structure + * @param data The pointer to be associated */ +__api void iio_channel_set_data(struct iio_channel *chn, void *data); + + +/** @brief Retrieve a previously associated pointer of an iio_channel structure + * @param chn A pointer to an iio_channel structure + * @return The pointer previously associated if present, or NULL */ +__api void * iio_channel_get_data(const struct iio_channel *chn); + + +/** @brief Get the type of the given channel + * @param chn A pointer to an iio_channel structure + * @return The type of the channel */ +__api __pure enum iio_chan_type iio_channel_get_type( + const struct iio_channel *chn); + + +/** @brief Get the modifier type of the given channel + * @param chn A pointer to an iio_channel structure + * @return The modifier type of the channel */ +__api __pure enum iio_modifier iio_channel_get_modifier( + const struct iio_channel *chn); + + +/** @} *//* ------------------------------------------------------------------*/ +/* ------------------------- Buffer functions --------------------------------*/ +/** @defgroup Buffer Buffer + * @{ + * @struct iio_buffer + * @brief An input or output buffer, used to read or write samples */ + + +/** @brief Retrieve a pointer to the iio_device structure + * @param buf A pointer to an iio_buffer structure + * @return A pointer to an iio_device structure */ +__api __pure const struct iio_device * iio_buffer_get_device( + const struct iio_buffer *buf); + + +/** @brief Create an input or output buffer associated to the given device + * @param dev A pointer to an iio_device structure + * @param samples_count The number of samples that the buffer should contain + * @param cyclic If True, enable cyclic mode + * @return On success, a pointer to an iio_buffer structure + * @return On error, NULL is returned, and errno is set to the error code + * + * NOTE: Channels that have to be written to / read from must be enabled + * before creating the buffer. */ +__api struct iio_buffer * iio_device_create_buffer(const struct iio_device *dev, + size_t samples_count, bool cyclic); + + +/** @brief Destroy the given buffer + * @param buf A pointer to an iio_buffer structure + * + * NOTE: After that function, the iio_buffer pointer shall be invalid. */ +__api void iio_buffer_destroy(struct iio_buffer *buf); + +/** @brief Get a pollable file descriptor + * + * Can be used to know when iio_buffer_refill() or iio_buffer_push() can be + * called + * @param buf A pointer to an iio_buffer structure + * @return On success, valid file descriptor + * @return On error, a negative errno code is returned + */ +__api int iio_buffer_get_poll_fd(struct iio_buffer *buf); + +/** @brief Make iio_buffer_refill() and iio_buffer_push() blocking or not + * + * After this function has been called with blocking == false, + * iio_buffer_refill() and iio_buffer_push() will return -EAGAIN if no data is + * ready. + * A device is blocking by default. + * @param buf A pointer to an iio_buffer structure + * @param blocking true if the buffer API should be blocking, else false + * @return On success, 0 + * @return On error, a negative errno code is returned + */ +__api int iio_buffer_set_blocking_mode(struct iio_buffer *buf, bool blocking); + + +/** @brief Fetch more samples from the hardware + * @param buf A pointer to an iio_buffer structure + * @return On success, the number of bytes read is returned + * @return On error, a negative errno code is returned + * + * NOTE: Only valid for input buffers */ +__api ssize_t iio_buffer_refill(struct iio_buffer *buf); + + +/** @brief Send the samples to the hardware + * @param buf A pointer to an iio_buffer structure + * @return On success, the number of bytes written is returned + * @return On error, a negative errno code is returned + * + * NOTE: Only valid for output buffers */ +__api ssize_t iio_buffer_push(struct iio_buffer *buf); + + +/** @brief Send a given number of samples to the hardware + * @param buf A pointer to an iio_buffer structure + * @param samples_count The number of samples to submit + * @return On success, the number of bytes written is returned + * @return On error, a negative errno code is returned + * + * NOTE: Only valid for output buffers */ +__api ssize_t iio_buffer_push_partial(struct iio_buffer *buf, + size_t samples_count); + +/** @brief Cancel all buffer operations + * @param buf The buffer for which operations should be canceled + * + * This function cancels all outstanding buffer operations previously scheduled. + * This means any pending iio_buffer_push() or iio_buffer_refill() operation + * will abort and return immediately, any further invocations of these functions + * on the same buffer will return immediately with an error. + * + * Usually iio_buffer_push() and iio_buffer_refill() will block until either all + * data has been transferred or a timeout occurs. This can depending on the + * configuration take a significant amount of time. iio_buffer_cancel() is + * useful to bypass these conditions if the buffer operation is supposed to be + * stopped in response to an external event (e.g. user input). + * + * To be able to capture additional data after calling this function the buffer + * should be destroyed and then re-created. + * + * This function can be called multiple times for the same buffer, but all but + * the first invocation will be without additional effect. + * + * This function is thread-safe, but not signal-safe, i.e. it must not be called + * from a signal handler. + */ +__api void iio_buffer_cancel(struct iio_buffer *buf); + + +/** @brief Get the start address of the buffer + * @param buf A pointer to an iio_buffer structure + * @return A pointer corresponding to the start address of the buffer */ +__api void * iio_buffer_start(const struct iio_buffer *buf); + + +/** @brief Find the first sample of a channel in a buffer + * @param buf A pointer to an iio_buffer structure + * @param chn A pointer to an iio_channel structure + * @return A pointer to the first sample found, or to the end of the buffer if + * no sample for the given channel is present in the buffer + * + * NOTE: This fonction, coupled with iio_buffer_step and iio_buffer_end, + * can be used to iterate on all the samples of a given channel present in the + * buffer, doing the following: + * + * @verbatim + for (void *ptr = iio_buffer_first(buffer, chn); ptr < iio_buffer_end(buffer); ptr += iio_buffer_step(buffer)) { + .... + } + @endverbatim */ +__api void * iio_buffer_first(const struct iio_buffer *buf, + const struct iio_channel *chn); + + +/** @brief Get the step size between two samples of one channel + * @param buf A pointer to an iio_buffer structure + * @return the difference between the addresses of two consecutive samples of + * one same channel */ +__api ptrdiff_t iio_buffer_step(const struct iio_buffer *buf); + + +/** @brief Get the address that follows the last sample in a buffer + * @param buf A pointer to an iio_buffer structure + * @return A pointer corresponding to the address that follows the last sample + * present in the buffer */ +__api void * iio_buffer_end(const struct iio_buffer *buf); + + +/** @brief Call the supplied callback for each sample found in a buffer + * @param buf A pointer to an iio_buffer structure + * @param callback A pointer to a function to call for each sample found + * @param data A user-specified pointer that will be passed to the callback + * @return number of bytes processed. + * + * NOTE: The callback receives four arguments: + * * A pointer to the iio_channel structure corresponding to the sample, + * * A pointer to the sample itself, + * * The length of the sample in bytes, + * * The user-specified pointer passed to iio_buffer_foreach_sample. */ +__api ssize_t iio_buffer_foreach_sample(struct iio_buffer *buf, + ssize_t (*callback)(const struct iio_channel *chn, + void *src, size_t bytes, void *d), void *data); + + +/** @brief Associate a pointer to an iio_buffer structure + * @param buf A pointer to an iio_buffer structure + * @param data The pointer to be associated */ +__api void iio_buffer_set_data(struct iio_buffer *buf, void *data); + + +/** @brief Retrieve a previously associated pointer of an iio_buffer structure + * @param buf A pointer to an iio_buffer structure + * @return The pointer previously associated if present, or NULL */ +__api void * iio_buffer_get_data(const struct iio_buffer *buf); + + +/** @} *//* ------------------------------------------------------------------*/ +/* ------------------------- Low-level functions -----------------------------*/ +/** @defgroup Debug Debug and low-level functions + * @{ + * @struct iio_data_format + * @brief Contains the format of a data sample. + * + * The different fields inform about the correct way to convert one sample from + * its raw format (as read from / generated by the hardware) to its real-world + * value. + */ +struct iio_data_format { + /** @brief Total length of the sample, in bits */ + unsigned int length; + + /** @brief Length of valuable data in the sample, in bits */ + unsigned int bits; + + /** @brief Right-shift to apply when converting sample */ + unsigned int shift; + + /** @brief Contains True if the sample is signed */ + bool is_signed; + + /** @brief Contains True if the sample is fully defined, sign extended, etc. */ + bool is_fully_defined; + + /** @brief Contains True if the sample is in big-endian format */ + bool is_be; + + /** @brief Contains True if the sample should be scaled when converted */ + bool with_scale; + + /** @brief Contains the scale to apply if with_scale is set */ + double scale; + + /** @brief Number of times length repeats (added in v0.8) */ + unsigned int repeat; +}; + + +/** @brief Get the current sample size + * @param dev A pointer to an iio_device structure + * @return On success, the sample size in bytes + * @return On error, a negative errno code is returned + * + * NOTE: The sample size is not constant and will change when channels + * get enabled or disabled. */ +__api ssize_t iio_device_get_sample_size(const struct iio_device *dev); + + +/** @brief Get the index of the given channel + * @param chn A pointer to an iio_channel structure + * @return On success, the index of the specified channel + * @return On error, a negative errno code is returned */ +__api __pure long iio_channel_get_index(const struct iio_channel *chn); + + +/** @brief Get a pointer to a channel's data format structure + * @param chn A pointer to an iio_channel structure + * @return A pointer to the channel's iio_data_format structure */ +__api __cnst const struct iio_data_format * iio_channel_get_data_format( + const struct iio_channel *chn); + + +/** @brief Convert the sample from hardware format to host format + * @param chn A pointer to an iio_channel structure + * @param dst A pointer to the destination buffer where the converted sample + * should be written + * @param src A pointer to the source buffer containing the sample */ +__api void iio_channel_convert(const struct iio_channel *chn, + void *dst, const void *src); + + +/** @brief Convert the sample from host format to hardware format + * @param chn A pointer to an iio_channel structure + * @param dst A pointer to the destination buffer where the converted sample + * should be written + * @param src A pointer to the source buffer containing the sample */ +__api void iio_channel_convert_inverse(const struct iio_channel *chn, + void *dst, const void *src); + + +/** @brief Enumerate the debug attributes of the given device + * @param dev A pointer to an iio_device structure + * @return The number of debug attributes found */ +__api __pure unsigned int iio_device_get_debug_attrs_count( + const struct iio_device *dev); + + +/** @brief Get the debug attribute present at the given index + * @param dev A pointer to an iio_device structure + * @param index The index corresponding to the debug attribute + * @return On success, a pointer to a static NULL-terminated string + * @return If the index is invalid, NULL is returned */ +__api __pure const char * iio_device_get_debug_attr( + const struct iio_device *dev, unsigned int index); + + +/** @brief Try to find a debug attribute by its name + * @param dev A pointer to an iio_device structure + * @param name A NULL-terminated string corresponding to the name of the + * debug attribute + * @return On success, a pointer to a static NULL-terminated string + * @return If the name does not correspond to any known debug attribute of the + * given device, NULL is returned + * + * NOTE: This function is useful to detect the presence of a debug + * attribute. + * It can also be used to retrieve the name of a debug attribute as a pointer + * to a static string from a dynamically allocated string. */ +__api __pure const char * iio_device_find_debug_attr( + const struct iio_device *dev, const char *name); + + +/** @brief Read the content of the given debug attribute + * @param dev A pointer to an iio_device structure + * @param attr A NULL-terminated string corresponding to the name of the + * debug attribute + * @param dst A pointer to the memory area where the NULL-terminated string + * corresponding to the value read will be stored + * @param len The available length of the memory area, in bytes + * @return On success, the number of bytes written to the buffer + * @return On error, a negative errno code is returned + * + * NOTE:By passing NULL as the "attr" argument to + * iio_device_debug_attr_read, it is now possible to read all of the debug + * attributes of a device. + * + * The buffer is filled with one block of data per debug attribute of the + * device, by the order they appear in the iio_device structure. + * + * The first four bytes of one block correspond to a 32-bit signed value in + * network order. If negative, it corresponds to the errno code that were + * returned when reading the debug attribute; if positive, it corresponds + * to the length of the data read. In that case, the rest of the block contains + * the data. */ +__api ssize_t iio_device_debug_attr_read(const struct iio_device *dev, + const char *attr, char *dst, size_t len); + + +/** @brief Read the content of all debug attributes + * @param dev A pointer to an iio_device structure + * @param cb A pointer to a callback function + * @param data A pointer that will be passed to the callback function + * @return On success, 0 is returned + * @return On error, a negative errno code is returned + * + * NOTE: This function is especially useful when used with the network + * backend, as all the debug attributes are read in one single command. */ +__api int iio_device_debug_attr_read_all(struct iio_device *dev, + int (*cb)(struct iio_device *dev, const char *attr, + const char *value, size_t len, void *d), + void *data); + + +/** @brief Set the value of the given debug attribute + * @param dev A pointer to an iio_device structure + * @param attr A NULL-terminated string corresponding to the name of the + * debug attribute + * @param src A NULL-terminated string to set the debug attribute to + * @return On success, the number of bytes written + * @return On error, a negative errno code is returned + * + * NOTE:By passing NULL as the "attr" argument to + * iio_device_debug_attr_write, it is now possible to write all of the + * debug attributes of a device. + * + * The buffer must contain one block of data per debug attribute of the device, + * by the order they appear in the iio_device structure. + * + * The first four bytes of one block correspond to a 32-bit signed value in + * network order. If negative, the debug attribute is not written; if positive, + * it corresponds to the length of the data to write. In that case, the rest + * of the block must contain the data. */ +__api ssize_t iio_device_debug_attr_write(const struct iio_device *dev, + const char *attr, const char *src); + + +/** @brief Set the value of the given debug attribute + * @param dev A pointer to an iio_device structure + * @param attr A NULL-terminated string corresponding to the name of the + * debug attribute + * @param src A pointer to the data to be written + * @param len The number of bytes that should be written + * @return On success, the number of bytes written + * @return On error, a negative errno code is returned */ +__api ssize_t iio_device_debug_attr_write_raw(const struct iio_device *dev, + const char *attr, const void *src, size_t len); + + +/** @brief Set the values of all debug attributes + * @param dev A pointer to an iio_device structure + * @param cb A pointer to a callback function + * @param data A pointer that will be passed to the callback function + * @return On success, 0 is returned + * @return On error, a negative errno code is returned + * + * NOTE: This function is especially useful when used with the network + * backend, as all the debug attributes are written in one single command. */ +__api int iio_device_debug_attr_write_all(struct iio_device *dev, + ssize_t (*cb)(struct iio_device *dev, + const char *attr, void *buf, size_t len, void *d), + void *data); + + +/** @brief Read the content of the given debug attribute + * @param dev A pointer to an iio_device structure + * @param attr A NULL-terminated string corresponding to the name of the + * debug attribute + * @param val A pointer to a bool variable where the value should be stored + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_device_debug_attr_read_bool(const struct iio_device *dev, + const char *attr, bool *val); + + +/** @brief Read the content of the given debug attribute + * @param dev A pointer to an iio_device structure + * @param attr A NULL-terminated string corresponding to the name of the + * debug attribute + * @param val A pointer to a long long variable where the value should be stored + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_device_debug_attr_read_longlong(const struct iio_device *dev, + const char *attr, long long *val); + + +/** @brief Read the content of the given debug attribute + * @param dev A pointer to an iio_device structure + * @param attr A NULL-terminated string corresponding to the name of the + * debug attribute + * @param val A pointer to a double variable where the value should be stored + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_device_debug_attr_read_double(const struct iio_device *dev, + const char *attr, double *val); + + +/** @brief Set the value of the given debug attribute + * @param dev A pointer to an iio_device structure + * @param attr A NULL-terminated string corresponding to the name of the + * debug attribute + * @param val A bool value to set the debug attribute to + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_device_debug_attr_write_bool(const struct iio_device *dev, + const char *attr, bool val); + + +/** @brief Set the value of the given debug attribute + * @param dev A pointer to an iio_device structure + * @param attr A NULL-terminated string corresponding to the name of the + * debug attribute + * @param val A long long value to set the debug attribute to + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_device_debug_attr_write_longlong(const struct iio_device *dev, + const char *attr, long long val); + + +/** @brief Set the value of the given debug attribute + * @param dev A pointer to an iio_device structure + * @param attr A NULL-terminated string corresponding to the name of the + * debug attribute + * @param val A double value to set the debug attribute to + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_device_debug_attr_write_double(const struct iio_device *dev, + const char *attr, double val); + + +/** @brief Identify the channel or debug attribute corresponding to a filename + * @param dev A pointer to an iio_device structure + * @param filename A NULL-terminated string corresponding to the filename + * @param chn A pointer to a pointer of an iio_channel structure. The pointed + * pointer will be set to the address of the iio_channel structure if the + * filename correspond to the attribute of a channel, or NULL otherwise. + * @param attr A pointer to a NULL-terminated string. The pointer + * pointer will be set to point to the name of the attribute corresponding to + * the filename. + * @return On success, 0 is returned, and *chn and *attr are modified. + * @return On error, a negative errno code is returned. *chn and *attr are not + * modified. */ +__api int iio_device_identify_filename(const struct iio_device *dev, + const char *filename, struct iio_channel **chn, + const char **attr); + + +/** @brief Set the value of a hardware register + * @param dev A pointer to an iio_device structure + * @param address The address of the register + * @param value The value to set the register to + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_device_reg_write(struct iio_device *dev, + uint32_t address, uint32_t value); + + +/** @brief Get the value of a hardware register + * @param dev A pointer to an iio_device structure + * @param address The address of the register + * @param value A pointer to the variable where the value will be written + * @return On success, 0 is returned + * @return On error, a negative errno code is returned */ +__api int iio_device_reg_read(struct iio_device *dev, + uint32_t address, uint32_t *value); + + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#undef __api + +#endif /* __IIO_H__ */ diff --git a/library/matlab/iio_installer_script.m b/library/matlab/iio_installer_script.m new file mode 100755 index 0000000..1276729 --- /dev/null +++ b/library/matlab/iio_installer_script.m @@ -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 diff --git a/library/matlab/iio_sys_obj.m b/library/matlab/iio_sys_obj.m new file mode 100755 index 0000000..1f8380f --- /dev/null +++ b/library/matlab/iio_sys_obj.m @@ -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 diff --git a/library/matlab/iio_sys_obj_matlab.m b/library/matlab/iio_sys_obj_matlab.m new file mode 100755 index 0000000..52048bc --- /dev/null +++ b/library/matlab/iio_sys_obj_matlab.m @@ -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 \ No newline at end of file diff --git a/library/matlab/libiio_if.m b/library/matlab/libiio_if.m new file mode 100755 index 0000000..9fde04d --- /dev/null +++ b/library/matlab/libiio_if.m @@ -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 diff --git a/library/matlab/libiio_if_daq2.m b/library/matlab/libiio_if_daq2.m new file mode 100755 index 0000000..0ac5708 --- /dev/null +++ b/library/matlab/libiio_if_daq2.m @@ -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