Use MATLAB to interact with a web API to dynamically collect weather information
ID: 3868571 • Letter: U
Question
Use MATLAB to interact with a web API to dynamically collect weather information from a Natick, MA weather station and display it to the user. The program will ask the user if they want to plot temperature, humidity, rainfall or pressure. Then the program will ask the user for the number of data points. The program will then produce a plot of the selected weather data from the Natick, MA weather station. In order for you to accomplish this task, your code will need to do a couple of things:
1. Validate the user input so that the user can only select certain options: • weather data types: temperature, humidity, pressure or rainfall • Number of data points: maximum of 8000
2. Call the ThingSpeak web API to import the data from the weather station.
3. Clean up the data received from the ThingSpeak web API and produce a simple 1D matrix which contains the data points in one column or one row.
4. Build a plot that displays the data the user asked for. The plot should contain data point number the x-axis and the weather data on the y-axis (with units) along with a descriptive title.
You will accomplish this in a group. Each group member will be responsible for creating one of four functions:
1. user_input.m A function to gather user input and validate it. The input of this function will be null (), as the requests for user input will come from within the body of the function. Include error checking as part of the function. The output of the function will be a 1D matrix used by the API function below.
2. call_API.m A function to call the ThingSpeak Web API to retrieve the desired weather data. See http://www.mathworks.com/help/thingspeak/get-channel-field-feed.html and MATLAB’s webread() function. An example API call is: data = webread('https://api.thingspeak.com/channels/12397/fields/4.json?results=20') Only the desired weather data type and number of data points should be retrieved. Note the input for this function will come from the user input function above and the output will be sent to the cleanup function below.
3. clean_data.m A function to clean up the data and simplify it to a 1D matrix. See the MATLAB structure array data types and Chapter 11 in the textbook regarding indexing and pulling data out of structure arrays. Try using: data = webread('https://api.thingspeak.com/channels/12397/fields/4.json?results=20') to bring in a sample data set. Note the input of this function comes from the web API function above and the output needs to be a 1D matrix that will be used by the plotting function below.
4. plot_data.m A function to plot the data. Data point number on the x-axis and the weather data on the y-axis. Axis labeled with units. Construct the title and y-axis labels dynamically as these will change based what the user selects. Note the input of this function will be a 1D matrix from the cleanup function above as well as some of the user input gathered by the user input function. The output of this function will be a null output [ ], but within the body of the function, the plot will be called.
Explanation / Answer
% Channel ID to read data from readChannelID = 87179; % Specify date range dateRange = [datetime('March 7, 2016'),datetime('March 13, 2016')]; % Read data including the timestamp, and channel information. [data,time,channelInfo] = thingSpeakRead(readChannelID,'Fields',1:7,... 'DateRange',dateRange); % Create variables to store different sorts of data temperatureData = data(:,1); humidityData = data(:,2); pressureData = data(:,3); rainData = data(:,4); windSpeedData = data(:,5); windGustData = data(:,6); windDirectionData = data(:,7); % Create a figure to display plots figure % Temperature histogram subplot(2,3,1) % Create 2-by-3 axis on the same figure, and work on the first axis histogram(temperatureData); title(channelInfo.FieldDescriptions{1}); grid on % Humidity histogram subplot(2,3,2) histogram(humidityData); title(channelInfo.FieldDescriptions{2}); grid on % Pressure histogram subplot(2,3,3) histogram(pressureData); title(channelInfo.FieldDescriptions{3}); grid on % Rain fall histogram subplot(2,3,4) histogram(rainData); title(channelInfo.FieldDescriptions{4}); grid on % WindSpeed histogram subplot(2,3,5) histogram(windSpeedData); title(channelInfo.FieldDescriptions{5}); grid on % Wind Direction histogram rad = windDirectionData*pi/180; % Convert to radians rad = -rad+pi/2; % Adjust the wind direction data to match map compass, such that North is equal to 0 degree subplot(2,3,6) rose(rad,12) % Plot the wind direction histogram in a polar axis title(channelInfo.FieldDescriptions{7}) ax = gca; ax.View = [-90 90]; % Rotate axis 90 degrees counterclock-wise such that North is equal to 0 degree % Remove missing data from the temperature variable, in order to perform % the fitting methods idx = ~isnan(temperatureData); rawTemp = temperatureData(idx); newTime = time(idx); % Smooth the raw temperature data with local 60-point mean values smoothTemp = movmean(temperatureData(idx),60); % Fit the data for a trend line [p,~,mu]= polyfit(datenum(newTime),rawTemp,1); trend = polyval(p,datenum(newTime),[],mu); % Optional: fit the data by using the sum of eight sine functions % To use the fit function, the Curve Fitting Toolbox is required. % It can be downloaded here: http://www.mathworks.com/products/curvefitting/ f = fit(datenum(newTime),rawTemp,'sin8'); % Plot the raw data, smooth data, trend and fitting curve figure hold on plot(newTime,rawTemp,'b') % Plot the raw temperature plot(newTime,smoothTemp,'g','LineWidth',1.5) % Plot the smoothing curve plot(newTime,trend,'m','LineWidth',2) % Plot the trend line plot(f) % Plot the fitting curve hold off xlim([datenum(time(1)) datenum(time(end))]) % Adjust the x-axis to properly display the curves xlabel('Date') ylabel('Temperature (F)') legend({'Raw Data','Smooth Data','Trend','Fitting Curve'},'Location','NE') % Remove missing data idx = ~isnan(temperatureData); rawTemp = temperatureData(idx); newTime = time(idx); % Plot temperature for each day. figure hold on % Use dateshift and findgroups functions to bin the temperature data in % terms of individual day timeShift = dateshift(newTime,'start','day'); % Shift hour, minute, and second to the start of each day, i.e. 00:00:00 dayGroup = findgroups(timeShift); % Group the shifted time in terms of day splitapply(@plot,second(newTime,'secondofday')/3600,rawTemp,dayGroup); % Apply the plot function to the temperature for each day by using the group defined above % Compute the absolute Max, Min, and Mean for each hour hourGroup = findgroups(hour(newTime)); % Create a vector of grouping number for each hour tMax = splitapply(@max,rawTemp,hourGroup); % Calculate the max for each hour tMin = splitapply(@min,rawTemp,hourGroup); % Calculate the min for each hour tMean = splitapply(@mean,rawTemp,hourGroup); % Calculate the mean for each hour % Prepare x and y data for the average and the variation area xHalf = [0,repelem(1:23,2),24]; % x coordinate at the end points for each interval (each hour) x = [xHalf, fliplr(xHalf)]; % x coordinate for variation area (including both bottom and top profiles) tMax = repelem(tMax,2); % y coordinate for max per hour tMin = repelem(tMin,2); % y coordinate for min per hour tMean = repelem(tMean,2);% y coordinate for mean per hour y = [tMin; flipud(tMax)]; % y coordinate for variation area (bottom and top) % Plot Statistics plot([0,24], [max(tMax),max(tMax)],'.--k', 'LineWidth',1.5) % Plot global Max as a horizontal line plot([0,24], [min(tMin),min(tMin)],'.--k', 'LineWidth',1.5) % Plot global Min as a horizontal line h1 = fill(x,y, 'b', 'LineStyle', 'none', 'FaceAlpha', 0.1); % Highlight the variation area per hour h2 = plot(xHalf,tMean,'--','LineWidth',2); % Plot average per hour hold off title('Daily temperature over the past week') ylabel('Temperature (F)') xlabel('Day Time') axis tight % Adjust axis to fit the plot ylim([20 80]) % Adjust to allow space on the top and at the bottom of the axis ax = gca; % Get the current axis object ax.XTick = 1:24; % Change the X-Tick to 24 hours legend([h1,h2],'Variation per hour','Average per hour')
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.