% Store the channel ID for the sensor channel.
channelID = 1281249;

% Provide the ThingSpeak alerts API key.  All alerts API keys start with TAK.
alertApiKey = 'TAKJ0ZPEPG8UU1D5N3PWR';

% Set the address for the HTTTP call
alertUrl="https://api.thingspeak.com/alerts/send";

% webwrite uses weboptions to add required headers.  Alerts needs a ThingSpeak-Alerts-API-Key header.
options = weboptions("HeaderFields", ["ThingSpeak-Alerts-API-Key", alertApiKey ]);

% Set the email subject.
alertSubject = sprintf("warning dude!");

% Read the recent data.
lightData = thingSpeakRead(channelID,'ReadKey','9XCFL555DGOYUBX3','NumDays',30,'Fields',1);

% Check to make sure the data was read correctly from the channel.
if isempty(lightData)
    alertBody = ' No data read . ';      
else
    
    % Get the most recent point in the array of moisture data.
    lastValue = lightData(end); 
    disp(lastValue)

    % Set the outgoing message
    if (lastValue<=2000)
        alertBody = ' it s geeting dark! ';
    else
        alertBody = ' its ok. ';
    end
end
 
 % Catch errors so the MATLAB code does not disable a TimeControl if it fails
try
    webwrite(alertUrl , "body", alertBody, "subject", alertSubject, options);
catch someException
    fprintf("Failed to send alert: %s\n", someException.message);
end
