% webserver_ctrl.m - web server control example
% RMM, 23 Jun 07

aminit;					% initialize AM macros
apache_lin;				% load web server model

% Design an LQR controller
Q = diag([5, 1]);
R = diag([1/50^2, 1/1000^2]);
K = dlqr(Aws, Bws, Q, R);

% Construct a closed loop system with disturbance inputs
sys = ss(Aws - Bws * K * Cws, [Bws, -Bws * K], Cws, [Dws, eye(2)], 5);

% Extra the dynamics for the processor disturbance response
cpu = sys([1; 2], 3);
[Y, T, X] = step(cpu, 50);
D = transpose([0.3, 0; 0, 0] * ones(size(X')));
U = transpose(diag(uws_eq) * ones(size(X')) - K * (Cws * X' + D'));

% Define a short time vector for 
Ts = (0:5:10)';

figure(1); clf; subplot(321);
  plot([Ts; T+10], ...
       [ones(size(Ts))*xws_eq(1); xws_eq(1) + 0.3*Y(:,1)], ...
       'bo-', 'MarkerSize', AM_data_markersize);
  hold on;
  plot([Ts; T+10], ...
       [ones(size(Ts))*xws_eq(2); xws_eq(2) + 0.3*Y(:,2)], ...
       'x-', 'MarkerSize', AM_data_markersize*1.5, 'Color', [0 0.5 0]);
  amaxis;
  xlabel('Time [ms]');
  ylabel('xcpu, xmem');
  lgh = legend('xcpu', 'xmem', 'Orientation', 'horizontal');
  legend(lgh, 'boxoff');

amprint('webserver-cpu-1.eps');

figure(2); clf; subplot(323);
  [ax, h1, h2] = plotyy(...
    [Ts; T+10], [ones(size(Ts))*uws_eq(1); uws_eq(1) + U(:,1)], ...
    [Ts; T+10], [ones(size(Ts))*uws_eq(2); uws_eq(2) + U(:,2)]);

  lgh = legend([h1, h2], 'ka (l)', 'mc (r)', 'Orientation', 'horizontal', ...
        'Location', 'SouthEast');
  legend(lgh, 'boxoff');
  amaxis(ax(1)); amaxis(ax(2));

  % Reset axis limits; has to be done by hand because of plotyy 
  set(ax(1), 'YLim', [0, 50]);
  set(ax(1), 'YTick', [0 10 20 30 40 50])
  set(ax(1), 'TickLength', [0.02 0.025]);
  set(ax(1), 'FontName', 'Times New Roman');
  set(ax(1), 'FontSize', 12);

  set(ax(2), 'YLim', [0, 1500]);
  set(ax(2), 'YTick', [0 300 600 900 1200 1500])
  set(ax(2), 'TickLength', [0.02 0.025]);
  set(ax(2), 'FontName', 'Times New Roman');
  set(ax(2), 'FontSize', 12);

% amaxis(ax(1), [0 60 0 40]);
% xlabel(ax(1), 'Time [ms]');
  ylabel(ax(1), 'KeepAlive');
  set(h1, 'LineStyle', '-', 'Marker', 'o', 'MarkerSize', AM_data_markersize);

% amaxis(ax(2), [0 60 0 1500]);
  xlabel(ax(2), 'Time [ms]');
  ylabel(ax(2), 'MaxClients');
  set(h2, 'LineStyle', '-', 'Marker', 'x', 'MarkerSize', AM_data_markersize*1.5);

amprint('webserver-cpu-2.eps');
