【MATLAB GUI】作为上位机当TCP/IP Server进行socket通信

MATLAB在帮助手册中给出的TCP server代码如下

obj1 = instrfind('Type', 'tcpip', 'LocalHost', '192.168.0.120', 'LocalPort', 1680, 'Tag', '');
if isempty(obj1)
    obj1 = tcpip('192.168.0.120', 1680, 'NetworkRole', 'server');
else
    fclose(obj1);
    obj1 = obj1(1)
end
fclose(obj1);

在测试运行之后发现,只能进行本机与本机之间的通信。

通过百度查找发现,使用MATLAB作为server端进行通信的时候一次只能同一个远程主机通信,因此需要添加client的IP才能进行通信,代码如下。

% 建立TCP Server
    obj1 = instrfind('Type', 'tcpip', 'LocalHost', '192.168.0.102', 'LocalPort', 8080, 'Tag', '');
    % 如果tcpip对象不存在,则创建
    % 否则,找到对象
    if isempty(obj1)
        obj1 = tcpip('192.168.0.102', 8080, 'NetworkRole', 'server');
    else
        fclose(obj1);
        obj1 = obj1(1);
    end
    fclose(obj1);
    % 配置client IP
    set(obj1, 'RemoteHost', '192.168.0.111');
    fopen(obj1);

调用代码如下

%发送数据
fprintf(obj1, '%s\r\n', '发送的内容');

%接收数据     
recvRaw=fscanf(obj1);

如果需要进行数据提取,则需要进行数据处理

1.将接收到的数据按  “ , ”分割成多个元胞数组保存到recvR中,采用recvR(1),recvR(2)就可以调用分割的数据了

recvR=regexp(data1,',','split');

2.这里接收的数据类型为Temp:%d,Humidity:%d,PM:%d,Voice:%d\n,提取其中的数据

    recvR = str2double(regexp(recvRaw,'\d*\.?\d*','match'));  %提取数据
    temp = recvR(1);
    hum = recvR(2);
    pm = recvR(3);
    voice = recvR(4);

【简单应用实例】

GUI如下

代码

function varargout = untitled(varargin)
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @untitled_OpeningFcn, ...
                   'gui_OutputFcn',  @untitled_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before untitled is made visible.
function untitled_OpeningFcn(hObject, eventdata, handles, varargin)
global name
handles.output = hObject;
%设置图标
warning('off');
javaFrame = get(hObject, 'JavaFrame');
javaFrame.setFigureIcon(javax.swing.ImageIcon('icon.jpg'));
%连接数据库
conn=database('test','root','','com.mysql.jdbc.Driver','jdbc:mysql://localhost:3306/test');
%将开始时间设置为表名
name=strrep(datestr(datetime('now')),'-','_');
name=strrep(name,' ','_');
name=strrep(name,':','_');
%创建表
testSQL=['CREATE TABLE ',name,' (Temp INT , Humidity INT , PM INT , Voice INT , Time VARCHAR(50))'];
exec(conn,testSQL);
%断开连接
close(conn);

guidata(hObject, handles);

% UIWAIT makes untitled wait for user response (see UIRESUME)
% uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = untitled_OutputFcn(hObject, eventdata, handles) 
varargout{1} = handles.output;



function edit1_Callback(hObject, eventdata, handles)
% hObject    handle to edit1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit1 as text
%        str2double(get(hObject,'String')) returns contents of edit1 as a double


% --- Executes during object creation, after setting all properties.
function edit1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function edit2_Callback(hObject, eventdata, handles)
% hObject    handle to edit2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit2 as text
%        str2double(get(hObject,'String')) returns contents of edit2 as a double


% --- Executes during object creation, after setting all properties.
function edit2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function axes1_CreateFcn(hObject, eventdata, handles)

% --- Executes during object creation, after setting all properties.
function axes2_CreateFcn(hObject, eventdata, handles)


% --- Executes during object creation, after setting all properties.
function axes3_CreateFcn(hObject, eventdata, handles)


% --- Executes during object creation, after setting all properties.
function axes4_CreateFcn(hObject, eventdata, handles)
% hObject    handle to axes4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: place code in OpeningFcn to populate axes4


% --- Executes on button press in togglebutton1.
function togglebutton1_Callback(hObject, eventdata, handles)
% hObject    handle to togglebutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global name
global obj1
if get(hObject, 'value')
    % 更改本按钮文本为“断开”
	set(hObject, 'String', '断开');  %设置本按钮文本为“关闭串口”
    % 建立TCP Server
    obj1 = instrfind('Type', 'tcpip', 'LocalHost', '192.168.0.102', 'LocalPort', 8080, 'Tag', '');
    % Create the tcpip object if it does not exist
    % otherwise use the object that was found.
    if isempty(obj1)
        obj1 = tcpip('192.168.0.102', 8080, 'NetworkRole', 'server');
    else
        fclose(obj1);
        obj1 = obj1(1);
    end
    fclose(obj1);
    % Configure instrument object, obj1.
    set(obj1, 'RemoteHost', '192.168.0.111');
    fopen(obj1);
     x1=0;
     x2=0;
     x3=0;
     x4=0;
    go = true;
    while go
        % 接收      
        recvRaw=fscanf(obj1);    %从host读数据
        recvR = str2double(regexp(recvRaw,'\d*\.?\d*','match'));  %提取数据
        temp = recvR(1);
        hum = recvR(2);
        pm = recvR(3);
        voice = recvR(4);
        % 显示
         %当前时间
        timenow=datestr(datetime('now'));
        set(handles.time,'String',timenow);
        %温度
        set(handles.temp,'String',temp);
        x1 = [x1 temp];
        plot(handles.axes1,x1);
        xlabel(handles.axes1,'时间(min)');
        ylabel(handles.axes1,'温度(°C)');
        title(handles.axes1,'实时温度图');
        grid(handles.axes1,'on');
        drawnow
        %湿度
        set(handles.hum,'String',hum);
        x2 = [x2 hum];
        plot(handles.axes2,x2);
        grid(handles.axes2,'on');
        xlabel(handles.axes2,'时间(min)');
        ylabel(handles.axes2,'湿度(Rh)');
        title(handles.axes2,'实时湿度图');
        drawnow
        %PM2.5
        set(handles.pm,'String',pm);
        x3 = [x3 pm];
        plot(handles.axes3,x3);
        grid(handles.axes3,'on');
        xlabel(handles.axes3,'时间(min)');
        ylabel(handles.axes3,'PM2.5(ug/m3)');
        title(handles.axes3,'实时PM2.5图');
        drawnow
        %噪声
        set(handles.voice,'String',voice);
        x4 = [x4 voice];
        plot(handles.axes4,x4);
        grid(handles.axes4,'on');
        xlabel(handles.axes4,'时间(min)');
        ylabel(handles.axes4,'噪声(db)');
        title(handles.axes4,'实时噪声图');
        drawnow
        %存储
        %连接数据库
        conn=database('test','root','','com.mysql.jdbc.Driver','jdbc:mysql://localhost:3306/test');
        %将数据存入创建的表中
        colnames = {'Temp','Humidity','PM','Voice','Time'};
        data={temp,hum,pm,voice,timenow};
        datainsert(conn,name,colnames,data);
        %断开连接
        close(conn);
        pause(1);
    end
else  %若关闭串口
    % 更改本按钮文本为“连接”
    set(hObject, 'String', '连接');
    % 停止TCP Sever
    fclose(obj1);
    delete(obj1);
    clear obj1
end
% Hint: get(hObject,'Value') returns toggle state of togglebutton1

 

  • 3
    点赞
  • 42
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值