Skip to content
Snippets Groups Projects
Commit 67869ded authored by joalhelk's avatar joalhelk
Browse files

arduino server & added comments

parent 58cbf3ec
No related branches found
No related tags found
No related merge requests found
Showing
with 226 additions and 5 deletions
No preview for this file type
package com.joelhelkala.watcherGui.Nodes.Node;
import java.awt.LayoutManager;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
......@@ -10,6 +9,9 @@ import org.json.JSONObject;
import com.joelhelkala.watcherGui.Nodes.Node.NodeData.NodeData;
/*
* Class that handles node information
*/
public class Node {
private String description;
private String location;
......@@ -57,6 +59,7 @@ public class Node {
}
}
// get all of the measurements
public List<NodeData> getData() { return data; }
// Gets the temperature reading of the most recent measurement
......@@ -66,26 +69,28 @@ public class Node {
return data.getTemperature();
}
// Get the most recent humidity data
public Integer getRecentHumidity() {
NodeData data = findRecentData();
if(data == null) return 0;
return data.getHumidity();
}
// Get the most recent luminosity data
public Integer getRecentLuminosity() {
NodeData data = findRecentData();
if(data == null) return 0;
return data.getLuminosity();
}
// Get the date of the most recent measurement
public LocalDateTime getRecentDate() {
NodeData data = findRecentData();
if(data == null) return null;
return data.getTime();
}
// Get the newest data from a measurement
private NodeData findRecentData() {
if(data.size() == 0) return null;
NodeData newest = data.get(0);
......@@ -102,6 +107,7 @@ public class Node {
public Float getLatitude() { return latitude; }
public Float getLongitude() { return longitude; }
// Update the nodes measurements
public void updateData(JSONArray nodeData) {
data = new ArrayList<NodeData>();
if(nodeData.length() == 0) return;
......
......@@ -2,12 +2,16 @@ package com.joelhelkala.watcherGui.Nodes.Node.NodeData;
import java.time.LocalDateTime;
/*
* Helper class for nodeData
*/
public class NodeData {
private final LocalDateTime measured_at;
private final Integer temperature;
private final Integer humidity;
private final Integer luminosity;
// Default constructor
public NodeData() {
this.measured_at = null;
this.temperature = null;
......@@ -15,6 +19,7 @@ public class NodeData {
this.luminosity = null;
}
// Constructor with data
public NodeData(LocalDateTime measured_at, Integer temperature, Integer humidity, Integer luminosity) {
this.measured_at = measured_at;
this.temperature = temperature;
......@@ -22,6 +27,7 @@ public class NodeData {
this.luminosity = luminosity;
}
// GETTERS
public LocalDateTime getTime() {
return measured_at;
}
......
......@@ -6,7 +6,11 @@ import java.util.List;
import com.joelhelkala.watcherGui.Nodes.Node.Node;
import com.joelhelkala.watcherGui.httpRequests.HttpRequests;
/*
* Class to handle nodes
*/
public class Nodes {
// list of the nodes
private static List<Node> nodes = new ArrayList<Node>();
// Add a list of nodes
......@@ -21,18 +25,22 @@ public class Nodes {
nodes.add(node);
}
// get the amount of nodes
public static int size() {
return nodes.size();
}
// get the node at given index
public static Node get(int index) {
return nodes.get(index);
}
// get all of the nodes
public static List<Node> getAll() {
return nodes;
}
// get a node which matches the location given
public static Node findByLocation(String location) {
for(Node n : nodes) {
if(n.getLocation() == location) return n;
......@@ -40,6 +48,7 @@ public class Nodes {
return null;
}
// reset nodes and get updated ones from server
public static void updateNodes() {
nodes.clear();
AddNodes(HttpRequests.getNodes());
......
......@@ -23,6 +23,7 @@ public class RegisterPage implements ActionListener, KeyListener {
private JButton cancelButton;
private JButton confirmButton;
// Constructor
RegisterPage(){
welcomeLabel.setBounds(122,32,200,35);
welcomeLabel.setFont(new Font(null,Font.PLAIN,25));
......@@ -100,6 +101,9 @@ public class RegisterPage implements ActionListener, KeyListener {
}
/*
* Check if the cancel or confirm button has been pressed
*/
public void actionPerformed(ActionEvent e) {
if(e.getSource() == cancelButton) {
frame.dispose();
......@@ -119,6 +123,9 @@ public class RegisterPage implements ActionListener, KeyListener {
}
}
/*
* Validate a given email
*/
private boolean validateEmail(String email) {
// TODO: Create regex for email verification
if (email.length() > 0) return true;
......@@ -141,6 +148,10 @@ public class RegisterPage implements ActionListener, KeyListener {
return true;
}
/*
* When a key is released then check if form is valid and
* set the confirm button as enabled if it is
*/
public void keyReleased(KeyEvent e) {
if(validateForm()) confirmButton.setEnabled(true);
else confirmButton.setEnabled(false);
......
......@@ -49,6 +49,7 @@ public class WelcomePage implements MouseListener, ActionListener {
private static NodeDataFrame nodeDataFrame = new NodeDataFrame(leftPanelWidth, topPanelHeight, width-leftPanelWidth, height-topPanelHeight-bottomPanelHeight);
private static NodeSettingsFrame nodeSettingFrame = new NodeSettingsFrame(width-leftPanelWidth, height-topPanelHeight-bottomPanelHeight);
// Constructor
public WelcomePage(){
Nodes.updateNodes();
......@@ -233,12 +234,14 @@ public class WelcomePage implements MouseListener, ActionListener {
frame.setVisible(true);
}
// When mouse is hovering on a navbar element then change the color
@Override
public void mouseEntered(MouseEvent arg0) {
Object target = arg0.getSource();
((JComponent) target).setBackground(darkwhite);
}
// When mouse leaves a navbar element then reset the color unless it is the currently chosen tab
@Override
public void mouseExited(MouseEvent arg0) {
Object target = arg0.getSource();
......@@ -342,6 +345,9 @@ public class WelcomePage implements MouseListener, ActionListener {
}
/*
* A dialog that reports of a timeout and logs the user out
*/
public static void TimedOutSession() {
String message = "\"The session has timed out.\"\n"
+ "You will be logged out...";
......
......@@ -8,9 +8,13 @@ import javax.swing.SwingConstants;
import java.awt.BorderLayout;
/*
* A tab for friends
*/
public class FriendsFrame extends JPanel {
private static final Color gray = new Color(45, 45, 45);
// Constructor
public FriendsFrame(int x, int y, int width, int height) {
setLayout(new BorderLayout());
setBounds(x,y,width,height);
......
......@@ -13,6 +13,9 @@ import com.joelhelkala.watcherGui.frames.panels.ProgressBarCirclePanel;
import com.joelhelkala.watcherGui.frames.panels.TemperaturePanel;
import com.joelhelkala.watcherGui.httpRequests.HttpRequests;
/*
* A tab for data visualization
*/
public class NodeDataFrame extends JPanel {
private static final int cardWidth = 300;
......@@ -26,6 +29,7 @@ public class NodeDataFrame extends JPanel {
private LuminosityPanel lumiCard;
private LineChartPanel chartCard;
// Constructor
public NodeDataFrame(int x, int y, int width, int height) {
setLayout(null);
setBounds(x,y,width,height);
......
......@@ -20,6 +20,9 @@ import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.event.*;
/*
* A tab for updating nodes
*/
public class NodeSettingsFrame extends JPanel implements ActionListener{
private static final Color gray = new Color(45, 45, 45);
private JTextField descField = new JTextField();
......
......@@ -264,6 +264,7 @@ public class HttpRequests {
int status = con.getResponseCode();
con.disconnect();
if(status < 300) success = true;
// if status code is 403 (unauthorized) then session has expired and logout
else if (status == 403) {
WelcomePage.TimedOutSession();
// Set success to true so error dialog wont be shown
......
/*
Repeating WiFi Web Client
This sketch connects to a a web server and makes a request
using a WiFi equipped Arduino board.
created 23 April 2012
modified 31 May 2012
by Tom Igoe
modified 13 Jan 2014
by Federico Vanzati
http://www.arduino.cc/en/Tutorial/WifiWebClientRepeating
This code is in the public domain.
*/
#include <SPI.h>
#include <WiFiNINA.h>
#include <ArduinoHttpClient.h>
#include <ArduinoJson.h>
#include "arduino_secrets.h"
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#include "Adafruit_TSL2591.h"
// Initialize sensors
Adafruit_BME280 bme; // BME sensor which has pressure, humidity and temperature
Adafruit_TSL2591 tsl = Adafruit_TSL2591(2591); // Luminosity sensor
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
char ssid[] = SECRET_SSID; // your network SSID (name)
char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0; // your network key index number (needed only for WEP)
int status = WL_IDLE_STATUS;
int temp, humidity, luminosity;
boolean api_success = false;
// server address:
char server[] = "192.168.0.8";
IPAddress server_ip(192,168,0,8);
int port = 8080;
// Initialize the WiFi client library
WiFiClient client;
HttpClient http = HttpClient(client, server, port);
unsigned long lastConnectionTime = 0, lastConnectionTime2 = 0, lastMovementTime = 0; // last time you connected to the server, in milliseconds
const unsigned long postingInterval = 60L * 30L * 1000L; // delay (1 800 000 ms = 30 min) between updates, in milliseconds
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// Initialize pins
bme.begin(0x76);
tsl.begin();
tsl.setGain(TSL2591_GAIN_MED);
tsl.setTiming(TSL2591_INTEGRATIONTIME_300MS);
// check for the WiFi module:
if (WiFi.status() == WL_NO_MODULE) {
Serial.println("Communication with WiFi module failed!");
// don't continue
while (true);
}
// attempt to connect to WiFi network:
while (status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
// you're connected now, so print out the status:
printWifiStatus();
}
// MAIN LOOP
void loop() {
// if there's incoming data from the net connection.
// send it out the serial port. This is for debugging
// purposes only:
while (client.available()) {
char c = client.read();
Serial.write(c);
}
// Send the data
// If 30 minutes has been passed since last posting, then take measurements and post again
if (millis() - lastConnectionTime > postingInterval) {
temp = bme.readTemperature();
humidity = bme.readHumidity();
luminosity = tsl.getLuminosity(TSL2591_VISIBLE);
httpRequest();
}
}
// Lähetetään pilveen sensori1:lle sensoreiden tiedot
void httpRequest() {
// close any connection before send a new request.
// This will free the socket on the NINA module
Serial.println("making POST request");
String contentType = "application/x-www-form-urlencoded";
String postData ="temperature=";
postData += temp;
postData += "&humidity=";
postData += humidity;
postData += "&luminosity=";
postData += luminosity;
postData += "&parent_id=";
postData += 1;
http.post("/api/v1/nodeData", contentType, postData);
// read the status code and body of the response
int statusCode = http.responseStatusCode();
String response = http.responseBody();
Serial.print("Status code: ");
Serial.println(statusCode);
Serial.print("Response: ");
Serial.println(response);
// note the time that the connection was made:
lastConnectionTime = millis();
}
// Tulostetaan wifin tiedot
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your board's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}
File added
......@@ -3,6 +3,7 @@ package com.joelhelkala.watcherServer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
// MAIN
@SpringBootApplication
public class WatcherServerApplication {
......
......@@ -19,8 +19,15 @@ import java.util.Collections;
@NoArgsConstructor
@Entity
@Table
/*
AppUser is a class for basic user which has two roles (user,admin)
User has locked and enabled booleans, which are part of the Spring Boot Security
When the user has made a GET request on given endpoint with token, the user will be
enabled and can log in to the system.
*/
public class AppUser implements UserDetails {
// Database information
@SequenceGenerator(
name="person_sequence",
sequenceName = "person_sequence",
......@@ -64,6 +71,7 @@ public class AppUser implements UserDetails {
this.email = email;
}
// Returns the Spring Boot Security grantedAuthority entity from users role
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
SimpleGrantedAuthority authority = new SimpleGrantedAuthority(role.name());
......@@ -80,6 +88,7 @@ public class AppUser implements UserDetails {
return email;
}
// BELOW IS SPRING BOOT SECURITY FUNCTIONS FROM USERDETAILS
@Override
public boolean isAccountNonExpired() {
return true;
......
......@@ -5,6 +5,7 @@ import org.springframework.web.bind.annotation.*;
import java.util.List;
// Class for creating and handling AppUser endpoints
@RestController
@RequestMapping(path = "api/v1/appuser")
public class AppUserController {
......@@ -29,14 +30,12 @@ public class AppUserController {
}
// Endpoint to delete a user with given id
// TODO: perhaps change to email?
@DeleteMapping(path = "{personId}")
public void deletePerson(@PathVariable("personId") Long id) {
userService.deleteUser(id);
}
// Endpoint to update a user with given id
// TODO: perhaps change to email?
@PutMapping(path = "{personId}")
public void updateUser(@PathVariable("personId") Long id,
@RequestParam(required = false) String name,
......
......@@ -8,6 +8,7 @@ import org.springframework.stereotype.Repository;
import javax.transaction.Transactional;
import java.util.Optional;
// Jpa Interface to handle database manipulation
@Repository
public interface AppUserRepository extends JpaRepository<AppUser, Long> {
......
......@@ -13,6 +13,7 @@ import org.springframework.stereotype.Service;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
// Class for handling the sending of a email
@Service
@AllArgsConstructor
public class EmailService implements EmailSender {
......
......@@ -4,18 +4,21 @@ import org.springframework.http.HttpStatus;
import java.time.ZonedDateTime;
// Custom exception
public class ApiException {
private final String message;
private final HttpStatus httpStatus;
private final ZonedDateTime timestamp;
// Constructor
public ApiException(String message, HttpStatus httpStatus, ZonedDateTime timestamp) {
this.message = message;
this.httpStatus = httpStatus;
this.timestamp = timestamp;
}
// getters
public String getMessage() {
return message;
}
......
......@@ -8,6 +8,7 @@ import org.springframework.web.bind.annotation.ExceptionHandler;
import java.time.ZoneId;
import java.time.ZonedDateTime;
// Class that creates a ResponseEntity exception
@ControllerAdvice
public class ApiExceptionHandler {
......
......@@ -22,6 +22,7 @@ import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
// Class that handles the filtering of endpoints based on authorization of the user
@Slf4j
public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
private final AuthenticationManager authenticationManager;
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment