Commit f0eb6151 authored by John, Fabian's avatar John, Fabian
Browse files
parents f76fed8a 0a0aa4a2
lib/__pycache__/
%% alter path to your python (3.8 is tested) distribution here
py_path = 'C:\Users\Arthur-Vincent\AppData\Local\Programs\Python\Python38\python.exe';
broker_ip = '127.0.0.1';
%% Init components
%oscilloscope properties --> delivering mqtt string for RedPitaya Inputs
%mqtt stuff
addpath('../../lib');
addpath('../../lib/redpitaya');
op = OscilloscopeProperties(); % get an object of the OscilloscopeProperties class
% Two options to set sample rate
op = op.set_sample_rate_by_div(1.01e-4); % Set time per Oszilloscope-Div
%op.SampleRate = 15.6e6; % Set samplerate in MHz
op.TriggerDelay =+8192; %Delay in samples (0 delay -> Start writing in the center of the buffer)
op.TriggerLevel = .001; % Trigger level in Volt
test_message = op.get_mqtt_message();
%test_message = '[OSC]\ntrigger_delay=100\ndecimation=1\ntrigger_level=0.2\ntrigger_ch=CH_1\ntrigger_src=CH_1_PE';
myMqtt = mqtt_py_matlab(py_path);
myMqtt.connect_mqtt(broker_ip);
% Subscription to RP1 with wildcard (#)
myMqtt.sub_mqtt_topics(broker_ip, "RP1/#");
% Subscription without wildcard
myMqtt.sub_mqtt_topics(broker_ip, "RP1/CONFIGURE/RECONFIG");
myMqtt.sub_mqtt_topics(broker_ip, "RP1/raw/CH1");
pause(2);
% Publish Redpitaya API message
myMqtt.pub_mqtt(broker_ip, "RP1/CONFIGURE/RECONFIG", test_message);
% Read the last published message
fprintf('%s', myMqtt.get_payload_str("RP1/CONFIGURE/RECONFIG"));
% get max length of x axis
x_axis = op.get_ordinate();
pause(2);
% Start oszilloscope
myMqtt.pub_mqtt(broker_ip, "RP1/CONFIGURE/START", test_message);
%% Filter
Hd = fir_highpass2k;
%% Signal aquisition
%while(1)
% Read input 1
arr = myMqtt.get_payload_float("RP1/raw/CH1");
y_mat = cell2mat(cell(arr));
%filter input 1
y_filt = filter(Hd,y_mat);
% Plot input 1
subplot (2,1,1)
plot(x_axis, y_mat);
grid on;
% Plot filtered input 1
subplot (2,1,2)
plot(x_axis, y_filt);
grid on;
% Stop the aquisition
myMqtt.pub_mqtt(broker_ip, "RP1/CONFIGURE/RECONFIG", "STOP");
%end
function Hd = fir_highpass2k
%FIR_HIGHPASS2K Returns a discrete-time filter object.
% MATLAB Code
% Generated by MATLAB(R) 9.8 and Signal Processing Toolbox 8.4.
% Generated on: 15-Jun-2021 17:24:37
% Equiripple Highpass filter designed using the FIRPM function.
% All frequency values are in Hz.
Fs = 2000; % Sampling Frequency
N = 300; % Order
Fstop = 0.1; % Stopband Frequency
Fpass = 1; % Passband Frequency
Wstop = 1; % Stopband Weight
Wpass = 1; % Passband Weight
dens = 20; % Density Factor
% Calculate the coefficients using the FIRPM function.
b = firpm(N, [0 Fstop Fpass Fs/2]/(Fs/2), [0 0 1 1], [Wstop Wpass], ...
{dens});
Hd = dfilt.dffir(b);
% [EOF]
%% Define Red Pitaya as TCP/IP object
clear all
close all
clc
IP= '169.254.180.42'; % Input IP of your Red Pitaya...
port = 5000;
tcpipObj = tcpip(IP, port);
tcpipObj.InputBufferSize = 16384*32;
%% Open connection with your Red Pitaya
fopen(tcpipObj);
tcpipObj.Terminator = 'CR/LF';
flushinput(tcpipObj);
flushoutput(tcpipObj);
% Set decimation vale (sampling rate) in respect to you
% acquired signal frequency
fprintf(tcpipObj,'ACQ:RST');
fprintf(tcpipObj,'ACQ:DEC 8');
fprintf(tcpipObj,'ACQ:TRIG:LEV 0');
% there is an option to select coupling when using SIGNALlab 250-12
% fprintf(tcpipObj,'ACQ:SOUR1:COUP AC'); % enables AC coupling on channel 1
% by default LOW level gain is selected
% fprintf(tcpipObj,'ACQ:SOUR1:GAIN LV'); % user can switch gain using this command
% Set trigger delay to 0 samples
% 0 samples delay set trigger to center of the buffer
% Signal on your graph will have trigger in the center (symmetrical)
% Samples from left to the center are samples before trigger
% Samples from center to the right are samples after trigger
fprintf(tcpipObj,'ACQ:TRIG:DLY 0');
%% Start & Trigg
% Trigger source setting must be after ACQ:START
% Set trigger to source 1 positive edge
fprintf(tcpipObj,'ACQ:START');
% After acquisition is started some time delay is needed in order to acquire fresh samples in to buffer
% Here we have used time delay of one second but you can calculate exact value taking in to account buffer
% length and smaling rate
pause(1)
fprintf(tcpipObj,'ACQ:TRIG CH1_PE');
% Wait for trigger
% Until trigger is true wait with acquiring
% Be aware of while loop if trigger is not achieved
% Ctrl+C will stop code executing in Matlab
while 1
trig_rsp=query(tcpipObj,'ACQ:TRIG:STAT?')
if strcmp('TD',trig_rsp(1:2)) % Read only TD
break
end
end
% Read data from buffer
signal_str=query(tcpipObj,'ACQ:SOUR1:DATA?');
signal_str_2=query(tcpipObj,'ACQ:SOUR2:DATA?');
% Convert values to numbers.% First character in string is “{“
% and 2 latest are empty spaces and last is “}”.
signal_num=str2num(signal_str(1,2:length(signal_str)-3));
signal_num_2=str2num(signal_str_2(1,2:length(signal_str_2)-3));
plot(signal_num)
hold on
plot(signal_num_2,'r')
grid on
ylabel('Voltage / V')
xlabel('samples')
fclose(tcpipObj)
\ No newline at end of file
%% alter path to your python (3.8 is tested) distribution here
py_path = 'C:\Users\Arthur-Vincent\AppData\Local\Programs\Python\Python38\python.exe';
broker_ip = '127.0.0.1';
%% doing init
addpath('../lib');
myMqtt = mqtt_py_matlab(py_path);
myMqtt.connect_mqtt(broker_ip);
pause(1);
%% sending and receiving a string value
myMqtt.sub_mqtt_topics(broker_ip, "hello/test");
myMqtt.pub_mqtt(broker_ip, "hello/test", "WORLD!");
pause(1);
fprintf('%s', myMqtt.get_payload_str("hello/test"));
%% sending and receiving a binary value
signal = rand(1, 2000)';
signal_b = typecast(single(signal), 'uint8');
myMqtt.sub_mqtt_topics(broker_ip, "hello/numericBinary");
myMqtt.pub_mqtt_binary(broker_ip, "hello/numericBinary", signal_b);
signal_in_b = myMqtt.get_payload_float("hello/numericBinary");
signal_in = cell2mat(cell(signal_in_b));
subplot(2,1,1);
plot(signal);
title('MQTT submitted signal');
subplot(2,1,2);
plot(signal_in);
title('MQTT received signal');
import paho.mqtt.client as mqtt
import logging
import socket
import struct
import ctypes
import threading
cfg = {
'application_example_stuff': {
'ip': "10.21.1.77"
},
'serial_example_stuff': {
'port': "Com8",
'baud': 115200
},
# ---------------------------
# take logging as it is
# Levels:
# FATAL = 50
# ERROR = 40
# WARNING = 30
# INFO = 20
# DEBUG = 10
# ---------------------------
'logging': {
'level': logging.INFO,
'filename': "log.txt",
'console': True,
'format': "%(asctime)s %(levelname)s: %(message)s"
}
}
# ------------------------------
# STARTING APPLICATION
# Use this section as it is
# ------------------------------
if cfg['logging']['console']:
logging.basicConfig(level=cfg['logging']['level'], format=cfg['logging']['format'])
else:
logging.basicConfig(filename=cfg['logging']['filename'], filemode='w', level=cfg['logging']['level'],
format=cfg['logging']['format'])
if cfg['logging']['console']:
ch = logging.StreamHandler()
ch.setLevel(cfg['logging']['level'])
def init_globals():
global isConnected
global mqtt_received
global mqtt_subscriptions
global queue_lck
isConnected = ""
mqtt_received = []
mqtt_subscriptions = []
queue_lck = threading.Lock()
def on_connect(client, userdata, flags, rc):
global isConnected
isConnected = "CONNECTED"
def on_message(client, userdata, msg):
global mqtt_rec_msg
global mqtt_received
global mqtt_subscriptions
global clientMqtt
global queue_lck
logging.debug("received top: " + msg.topic + " | received payload: " + str(msg.payload))
queue_lck.acquire()
try:
if mqtt_subscriptions.count(msg.topic) > 0:
mqtt_received.append(msg)
mqtt_subscriptions.remove(msg.topic)
if mqtt_subscriptions.count(msg.topic) < 1:
clientMqtt.unsubscribe(msg.topic)
finally:
queue_lck.release()
def on_disconnect(client, userdata, rc):
global isConnected
isConnected = ""
def connect(broker, keepalive=60):
global clientMqtt
global isConnected
if isConnected == "CONNECTED":
return
clientMqtt = mqtt.Client(socket.gethostname())
clientMqtt.on_connect = on_connect
clientMqtt.on_message = on_message
clientMqtt.on_disconnect = on_disconnect
clientMqtt.connect(broker, 1883, keepalive)
while isConnected != "CONNECTED":
clientMqtt.loop(.5)
def pub_mqtt_message(broker, topic, message):
global clientMqtt
connect(broker, 60)
clientMqtt.publish(topic, message)
clientMqtt.loop(.01)
def pub_mqtt_binary(broker, topic, message_bin):
global clientMqtt
connect(broker, 60)
clientMqtt.publish(topic, bytes(message_bin))
clientMqtt.loop(.01)
def sub_mqtt_topics(broker, topics):
global clientMqtt
global mqtt_subscriptions
global queue_lck
connect(broker, 60)
queue_lck.acquire()
try:
for t in topics:
mqtt_subscriptions.append(t)
clientMqtt.subscribe(t)
logging.debug("subscribed: " + t)
logging.debug(mqtt_subscriptions)
finally:
queue_lck.release()
def get_mqtt_msg():
global mqtt_received
if mqtt_received.len() > 0:
ret_elm = mqtt_received[0]
mqtt_received.pop(0)
return ret_elm
else:
clientMqtt.loop(.01)
return 0
def get_payload_str(topic):
global mqtt_received
global mqtt_subscriptions
for msg in mqtt_received:
if msg.topic == topic:
ret_val = str(msg.payload)
mqtt_received.remove(msg)
return ret_val
if mqtt_subscriptions.count(topic) > 0:
loop_keepalive()
return ""
return "EMPTY"
def get_payload_float(topic):
global mqtt_received
global mqtt_subscriptions
logging.debug(mqtt_subscriptions)
logging.debug(mqtt_received)
logging.debug(topic)
for msg in mqtt_received:
if msg.topic == topic:
arr_size = len(msg.payload) / ctypes.sizeof(ctypes.c_float)
ret_val = struct.unpack(str(int(arr_size)) + 'f', msg.payload)
mqtt_received.remove(msg)
return ret_val
if mqtt_subscriptions.count(topic) > 0:
loop_keepalive()
return float(0)
return float(-1)
def loop_keepalive():
global clientMqtt
clientMqtt.loop(.1)
def disconnect():
global clientMqtt
global isConnected
isConnected = ""
clientMqtt.disconnect()
classdef mqtt_py_matlab < handle
%MQTT_PY_MATLAB wrapper to read MQTT messages
properties (Access = public)
log_active = 0
log_text = ""
end
methods
function obj = mqtt_py_matlab(python_exe_64_path)
%MQTT_PY_MATLAB Construct an instance of this class
% python_exe_64_path: path to 64bit python exe
fprintf("Setting up local virtual environment");
envName = "py_venv";
system("virtualenv --python " + python_exe_64_path + " " + envName)
system(".\" + envName + "\Scripts\activate");
system(envName + "\Scripts\pip install paho-mqtt");
try
pyversion(".\" + envName + "\Scripts\python.exe");
catch
end
pyversion
mqttClientPath = fileparts(which('cosaMqttClient.py'));
if count(py.sys.path,mqttClientPath) == 0
insert(py.sys.path,int32(0),mqttClientPath);
end
py.cosaMqttClient.init_globals();
end
function delete(obj)
py.cosaMqttClient.disconnect();
if obj.log_active > 0
obj.log_text = [obj.log_text; "Client Disconnected"];
end
end
function connect_mqtt(obj, broker)
py.cosaMqttClient.connect(broker);
if obj.log_active > 0
obj.log_text = [obj.log_text; "Client Connected to Broker: " + broker];
end
end
function pub_mqtt(obj, broker, topic, message)
topic = cellstr(topic);
message = cellstr(message);
py.cosaMqttClient.pub_mqtt_message(broker, topic{1}, message{1});
if obj.log_active > 0
obj.log_text = [obj.log_text ; "PUB topic: " + topic + " | Message: " + message];
end
pause(0.01);
end
function pub_mqtt_binary(obj, broker, topic, message_bin)
topic = cellstr(topic);
py.cosaMqttClient.pub_mqtt_binary(broker, topic{1}, message_bin);
if obj.log_active > 0
obj.log_text = {obj.log_text ; "PUB topic: " + topic + " | Message: " + message_bin};
end
end
function sub_mqtt_topics(obj, broker, topics)
topics = cellstr(topics);
py.cosaMqttClient.sub_mqtt_topics(broker, topics);
if obj.log_active > 0
obj.log_text = [obj.log_text ; "SUB topics: " + topics];
end
end
function payload = get_payload_str(obj, topic)
topic = cellstr(topic);
while 1
payload = string(py.cosaMqttClient.get_payload_str(topic{1}));
if payload == "EMPTY"
error("Tried to read topic without result or active subscription");
end
if payload ~= ""
if obj.log_active > 0
obj.log_text = [obj.log_text; "Received Topic: " + topic{1} + " | Message: " + payload];
end
return;
end
end
end
function payload = get_payload_float(obj, topic)
topic = cellstr(topic);
while 1
payload = py.cosaMqttClient.get_payload_float(topic{1});
if payload == -1
error("Tried to read topic without result or active subscription");
end
if payload ~= 0
if obj.log_active > 0
obj.log_text = [obj.log_text; "Received Topic: " + topic{1} + " | Message: " + payload];
end
return;
end
end
end
function payload = get_payload_float_once(obj, topic)
topic = cellstr(topic);
payload = py.cosaMqttClient.get_payload_float(topic{1});
end
end
methods (Static)
function loop_keepalive()
py.cosaMqttClient.loop_keepalive();
end
end
end
classdef OscilloscopeProperties
%OSCILLOSCOPEPROPERTIES Summary of this class goes here
% Detailed explanation goes here
properties (Constant)
sample_rates = [125e6, 15.6e6, 1.953e6, 122.07e3, 15.258e3, 1.907e3];
rp_decimation = [1, 8, 64, 1024, 8192, 65536];
end
properties
SampleRate = 125e6;
TriggerDelay = 0;
TriggerLevel = .2;
TriggerCh = 'CH_1';
TriggerSrc = 'CH_1_PE';
Ch1Mode = 'DC';
Ch2Mode = 'DC';
end
methods
function obj = OscilloscopeProperties()
%OSCILLOSCOPEPROPERTIES Construct an instance of this class
end
function mqtt_message = get_mqtt_message(obj)
%METHOD1 Summary of this method goes here
% Detailed explanation goes here
mqtt_message = ['[OSC]\n',...
'trigger_delay=', obj.get_trigger_delay_rp(),'\n',...
'decimation=', obj.get_decimation_rp(),'\n',...
'trigger_level=', num2str(obj.TriggerLevel),'\n',...
'trigger_ch=', obj.TriggerCh,'\n',...
'trigger_src=', obj.TriggerSrc,'\n',...
'ch1_mode=', obj.Ch1Mode,'\n',...
'ch2_mode=', obj.Ch2Mode];% obj.Property1 + inputArg;
end
function rp_sample_rate = get_sample_rate_rp(obj)
[~, idx] = min(abs(obj.sample_rates - obj.SampleRate));
rp_sample_rate = obj.sample_rates(idx);
end
function rp_sample_time = get_sample_time_rp(obj)
rp_sample_time = 16384/obj.get_sample_rate_rp();
end
function dec_rp = get_decimation_rp(obj)
idx = find(obj.sample_rates == obj.get_sample_rate_rp(), 1);
dec_rp = num2str(obj.rp_decimation(idx));
end
function trg_del_rp = get_trigger_delay_rp(obj)
trg_del_smpl_num = obj.TriggerDelay*obj.SampleRate;
trg_del_smpl_num = max(-8191, min(8192, trg_del_smpl_num));
trg_del_rp = num2str(round(trg_del_smpl_num, 0));
end
function obj = set_sample_rate_by_div(obj, time_per_div)
window_lengths = (8192*2+1)./(obj.sample_rates);
div_lengths = window_lengths/10;
[~, idx] = min(abs(div_lengths - time_per_div));
obj.SampleRate = obj.sample_rates(idx);
end
function ordinate = get_ordinate(obj)
trg_del = double(string(obj.get_trigger_delay_rp()));
o_start = (-8191+trg_del)/obj.get_sample_rate_rp();
o_stop = (8192+trg_del)/obj.get_sample_rate_rp();
ordinate = o_start:1/obj.get_sample_rate_rp():o_stop;
end
end
end