Java 家庭物联网

家庭物联网系统的代码和说明,包括用户认证、设备控制、数据监控、通知和警报、日志记录以及WebSocket实时更新功能。

### 项目结构

```plaintext
home-iot-system
├── backend
│   └── src
│       └── main
│           └── java
│               └── com
│                   └── example
│                       └── homeiot
│                           ├── config
│                           ├── controller
│                           ├── model
│                           ├── repository
│                           ├── service
│                           ├── websocket
│                           └── HomeIotApplication.java
├── frontend
│   ├── public
│   └── src
│       ├── components
│       ├── pages
│       ├── services
│       └── App.js
├── pom.xml
└── package.json
```

### 后端(Spring Boot)

#### `pom.xml`

```xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://www.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>home-iot-system</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
```

#### `HomeIotApplication.java`

```java
package com.example.homeiot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class HomeIotApplication {
    public static void main(String[] args) {
        SpringApplication.run(HomeIotApplication.class, args);
    }
}
```

#### 用户认证和角色管理

##### `SecurityConfig.java`

```java
package com.example.homeiot.config;

import com.example.homeiot.service.UserService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private final UserService userService;

    public SecurityConfig(UserService userService) {
        this.userService = userService;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .authorizeRequests()
                .antMatchers("/api/**").authenticated()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest().permitAll()
                .and()
            .formLogin()
                .and()
            .httpBasic();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
```

##### `Role.java`

```java
package com.example.homeiot.model;

import javax.persistence.*;
import java.util.Set;

@Entity
public class Role {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;

    @ManyToMany(mappedBy = "roles")
    private Set<User> users;

    // getters and setters
}
```

##### `User.java`

```java
package com.example.homeiot.model;

import javax.persistence.*;
import java.util.Set;

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String username;
    private String password;

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(
      name = "user_role", 
      joinColumns = @JoinColumn(name = "user_id"), 
      inverseJoinColumns = @JoinColumn(name = "role_id"))
    private Set<Role> roles;

    // getters and setters
}
```

##### `UserRepository.java`

```java
package com.example.homeiot.repository;

import com.example.homeiot.model.User;
import org.springframework.data.repository.CrudRepository;

public interface UserRepository extends CrudRepository<User, Long> {
    User findByUsername(String username);
}
```

##### `RoleRepository.java`

```java
package com.example.homeiot.repository;

import com.example.homeiot.model.Role;
import org.springframework.data.repository.CrudRepository;

public interface RoleRepository extends CrudRepository<Role, Long> {
}
```

##### `UserService.java`

```java
package com.example.homeiot.service;

import com.example.homeiot.model.User;
import com.example.homeiot.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

@Service
public class UserService implements UserDetailsService {
    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    public User save(User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        return userRepository.save(user);
    }

    public User findByUsername(String username) {
        return userRepository.findByUsername(username);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("User not found");
        }
        return org.springframework.security.core.userdetails.User
                .withUsername(username)
                .password(user.getPassword())
                .authorities(user.getRoles().stream()
                        .map(role -> "ROLE_" + role.getName().toUpperCase())
                        .toArray(String[]::new))
                .build();
    }
}
```

#### 设备数据监控和日志记录

##### `Device.java`

```java
package com.example.homeiot.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.time.LocalDateTime;

@Entity
public class Device {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;
    private String status;
    private String data;
    private LocalDateTime lastUpdated;

    // getters and setters
}
```

##### `DeviceLog.java`

```java
package com.example.homeiot.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.time.LocalDateTime;

@Entity
public class DeviceLog {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private Long deviceId;
    private String status;
    private String data;
    private LocalDateTime timestamp;

    // getters and setters
}
```

##### `DeviceLogRepository.java`

```java
package com.example.homeiot.repository;

import com.example.homeiot.model.DeviceLog;
import org.springframework.data.repository.CrudRepository;

import java.util.List;

public interface DeviceLogRepository extends CrudRepository<DeviceLog, Long> {
    List<DeviceLog> findByDeviceId(Long deviceId);
}
```

##### `DeviceRepository.java`

```java
package com.example.homeiot.repository;

import com.example.homeiot.model.Device;
import org.springframework.data.repository.CrudRepository;

public interface DeviceRepository extends CrudRepository<Device, Long> {
}
```

##### `DeviceService.java`

```java
package com.example.homeiot.service;

import com.example.homeiot.model.Device;
import com.example.homeiot.model.DeviceLog;
import com.example.homeiot.repository.DeviceLogRepository;
import com.example.homeiot.repository.DeviceRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeviceService {
    @Autowired
    private DeviceRepository deviceRepository;

    @Autowired
    private DeviceLogRepository deviceLogRepository;

    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    public List<Device> getAllDevices() {
        return (List<Device>) deviceRepository.findAll();
    }

    public Device addDevice(Device device) {
        device.setLastUpdated(LocalDateTime.now());
        return deviceRepository.save(device);
    }

    public Device updateDeviceStatus(Long id, String status) {
        Device device = deviceRepository.findById(id).orElseThrow(() -> new RuntimeException("Device not found"));
        device.setStatus(status);
        device.setLastUpdated(LocalDateTime.now());
        deviceRepository.save(device);

        DeviceLog log = new DeviceLog();
        log.setDeviceId(id);
        log.setStatus(status);
        log.setTimestamp(LocalDateTime.now());
        deviceLogRepository.save(log);

        messagingTemplate.convertAndSend("/topic/devices", device);

        return device;
    }

    public List<DeviceLog> getDeviceLogs(Long deviceId) {
        return deviceLogRepository.findByDeviceId(deviceId);
    }
}
```

##### `DeviceController.java`

```java
package com.example.homeiot.controller;

import com.example.homeiot.model.Device;
import com.example.homeiot.model.DeviceLog;
import com.example.homeiot.service.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/devices")
public class DeviceController {
    @Autowired
    private DeviceService deviceService;

    @GetMapping
    public List<Device> getAllDevices() {
        return deviceService.getAllDevices();
    }

    @PostMapping
    public Device addDevice(@RequestBody Device device) {
        return deviceService.addDevice(device);
    }

    @PutMapping("/{id}/status")
    public Device updateDeviceStatus(@PathVariable Long id, @RequestParam String status) {
        return deviceService.updateDeviceStatus(id, status);
    }

    @GetMapping("/{id}/logs")
    public List<DeviceLog> getDeviceLogs(@PathVariable Long id) {
        return deviceService.getDeviceLogs(id);
    }

    @MessageMapping("/changeStatus")
    @SendTo("/topic/devices")
    public Device changeDeviceStatus(Device device) {
        return deviceService.updateDeviceStatus(device.getId(), device.getStatus());
    }
}
```

#### WebSocket 实时更新

##### `WebSocketConfig.java`

```java
package com.example.homeiot.websocket;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws").withSockJS();
    }
}
```

### 前端(React)

#### `package.json`

```json
{
  "name": "home-iot-frontend",
  "version": "1.0.0",
  "dependencies": {
    "axios": "^0.21.1",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-router-dom": "^5.2.0",
    "react-scripts": "4.0.3",
    "sockjs-client": "^1.5.0",
    "@stomp/stompjs": "^6.1.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  }
}
```

#### `App.js`

```jsx
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import SockJS from 'sockjs-client';
import { Stomp } from '@stomp/stompjs';

function App() {
  const [devices, setDevices] = useState([]);
  const [deviceName, setDeviceName] = useState('');
  const [client, setClient] = useState(null);

  useEffect(() => {
    fetchDevices();
    connectWebSocket();
  }, []);

  const fetchDevices = () => {
    axios.get('/api/devices')
      .then(response => setDevices(response.data))
      .catch(error => console.error('Error fetching devices:', error));
  };

  const addDevice = () => {
    axios.post('/api/devices', { name: deviceName, status: 'off' })
      .then(response => {
        setDevices([...devices, response.data]);
        setDeviceName('');
      })
      .catch(error => console.error('Error adding device:', error));
  };

  const updateDeviceStatus = (deviceId, status) => {
    axios.put(`/api/devices/${deviceId}/status`, null, { params: { status } })
      .then(response => {
        const updatedDevices = devices.map(device => device.id === deviceId ? response.data : device);
        setDevices(updatedDevices);
      })
      .catch(error => console.error('Error updating device status:', error));
  };

  const connectWebSocket = () => {
    const socket = new SockJS('/ws');
    const stompClient = Stomp.over(socket);
    stompClient.connect({}, frame => {
      console.log('Connected: ' + frame);
      stompClient.subscribe('/topic/devices', message => {
        const updatedDevice = JSON.parse(message.body);
        setDevices(prevDevices =>
          prevDevices.map(device => device.id === updatedDevice.id ? updatedDevice : device)
        );
      });
    });
    setClient(stompClient);
  };

  return (
    <div>
      <h1>Home IoT System</h1>
      <input
        type="text"
        value={deviceName}
        onChange={e => setDeviceName(e.target.value)}
        placeholder="Enter device name"
      />
      <button onClick={addDevice}>Add Device</button>
      <ul>
        {devices.map(device => (
          <li key={device.id}>
            {device.name} - {device.status}
            <button onClick={() => updateDeviceStatus(device.id, device.status === 'off' ? 'on' : 'off')}>
              Toggle Status
            </button>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default App;
```

系统具备了用户认证、角色管理、设备数据监控、日志记录、通知和警报、以及WebSocket实时更新功能。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/774854.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

SpringBoot实战:轻松实现XSS攻击防御(注解和过滤器)

文章目录 引言一、XSS攻击概述1.1 XSS攻击的定义1.2 XSS攻击的类型1.3 XSS攻击的攻击原理及示例 二、Spring Boot中的XSS防御手段2.1 使用注解进行XSS防御2.1.1 引入相关依赖2.1.2 使用XSS注解进行参数校验2.1.3 实现自定义注解处理器2.1.4 使用注解 2.2 使用过滤器进行XSS防御…

现在这个行情怎么理解股票期权?一个守住底线的工具!

今天带你了解现在这个行情怎么理解股票期权&#xff1f;一个守住底线的工具&#xff01;股票期权是一种金融衍生品&#xff0c;给予持有者在未来特定时间以特定价格购买或出售股票的权利。 行情看down可以买入看跌期权&#xff0c;看跌期权的买方是因为预计行情的价格会在近期…

imx6ull/linux应用编程学习(11)CAN应用编程基础

关于裸机的can通信&#xff0c;会在其他文章发&#xff0c;这里主要讲讲linux上的can通信。 与I2C,SPI等同步通讯方式不同&#xff0c;CAN通讯是异步通讯&#xff0c;也就是没有时钟信号线来保持信号接收同步&#xff0c;也就是所说的半双工&#xff0c;无法同时发送与接收&…

【python】PyQt5控件尺寸大小位置,内容边距等API调用方法实战解析

✨✨ 欢迎大家来到景天科技苑✨✨ &#x1f388;&#x1f388; 养成好习惯&#xff0c;先赞后看哦~&#x1f388;&#x1f388; &#x1f3c6; 作者简介&#xff1a;景天科技苑 &#x1f3c6;《头衔》&#xff1a;大厂架构师&#xff0c;华为云开发者社区专家博主&#xff0c;…

小(微)间距P1.538COB渠道现货销售将加速全面升级替换SMD产品。

COB&#xff08;Chip on Board&#xff09;技术&#xff0c;如一颗璀璨的星辰&#xff0c;在上世纪60年代的科技夜空中悄然升起。它巧妙地将LED芯片镶嵌在PCB电路板的怀抱中&#xff0c;再用特种树脂为其披上一层坚韧的外衣&#xff0c;宛如一位精心雕琢的艺术家在创作一幅完美…

【Python机器学习】处理文本数据——用tf-idf缩放数据

为了按照我们预计的特征信息量大小来缩放特征&#xff0c;而不是舍弃那些认为不重要的特征&#xff0c;最常见的一种做法就是使用词频-逆向文档频率&#xff08;tf-idf&#xff09;。这一方法对某个特定文档中经常出现的术语给与很高的权重&#xff0c;但是堆在语料库的许多文档…

【UE5.1】Chaos物理系统基础——04 事件驱动粒子效果

目录 效果 步骤 一、炸开时的烟雾效果 二、炸开时的碎片效果 效果 步骤 一、炸开时的烟雾效果 1. 选中场景中的几何体集&#xff0c;勾选“通知中断”&#xff0c;这样当几何体集解体时就能产生一个事件&#xff1b;勾选“通知碰撞”&#xff0c;当几何体集检测到碰撞也能…

Java+前后端分离架构+ MySQL8.0.36产科信息管理系统 产科电子病历系统源码

Java前后端分离架构 MySQL8.0.36产科信息管理系统 产科电子病历系统源码 产科信息管理系统—住院管理 数字化产科住院管理是现代医院管理中的重要组成部分&#xff0c;它利用数字化技术优化住院流程&#xff0c;提升医疗服务质量和效率。以下是对数字化产科住院管理的详细阐述…

华火电燃喷火单灶再荣获中国质量认证中心 CQC 权威证书,引领行业新高度

近日&#xff0c;华火传来了一则令整个行业瞩目的重大喜讯&#xff1a;其电燃喷火单灶“再度”成功荣获中国质量认证中心&#xff08;CQC&#xff09;权威证书。这一里重大程碑式的成就&#xff0c;不仅是对华火产品卓越品质的高度认可&#xff0c;更是华火在品牌发展道路上的一…

网安小贴士(8)IPv4与IPv6

一、前言 IPv4和IPv6都是互联网协议&#xff08;IP&#xff09;的版本&#xff0c;它们用于在互联网上标识和定位设备。 二、定义 IPv4&#xff08;互联网协议第四版&#xff09;&#xff1a; IPv4是互联网协议的第一个广泛使用的版本&#xff0c;最初在1981年被标准化为RFC 7…

单位立方体各个面上的法向量,向量场以及每个面上的通量

单位立方体各个面上的法向量&#xff0c;向量场 F ( x , y , z ) \mathbf{F} (x, y, z) F(x,y,z) 以及每个面上的通量 flyfish 假设我们有一个单位立方体&#xff0c;向量场 F ( x , y , z ) \mathbf{F} (x, y, z) F(x,y,z) 在该立方体上。 法向量 &#xff1a;单位立方…

中霖教育:二建报名成功后怎么审核?

【中霖教育怎么样】【中霖教育靠谱吗】 在成功完成二级建造师资格考试的报名流程后&#xff0c;需要准备后续的审核阶段&#xff0c;审核是否通过关乎考生是否能顺利参加考试&#xff0c;审核的方式包括&#xff1a;现场审核、网络审核以及考试后的审核。 某些地区会要求考生…

空间数据获取与预处理指南:生产与科研应用

1.空间数据简介 2.免费的国外GIS数据下载方法 3.免费的国内GIS数据下载方法 4.遥感云平台数据的获取方法 5.专题数据的获取及预处理示例 (1)行政区划数据 (2)气象数据 (3)土壤数据 (4)遥感产品数据 (5)统计数据 (6)…… 原文链接https://mp.weixin.qq.com/s?__bizMz…

实验三 图像增强—灰度变换

一、实验目的&#xff1a; 1、了解图像增强的目的及意义&#xff0c;加深对图像增强的感性认识&#xff0c;巩固所学理论知识。 2、学会对图像直方图的分析。 3、掌握直接灰度变换的图像增强方法。 二、实验原理及知识点 术语‘空间域’指的是图像平面本身&#xff0c;在空…

【MySQL系列】隐式转换

&#x1f49d;&#x1f49d;&#x1f49d;欢迎来到我的博客&#xff0c;很高兴能够在这里和您见面&#xff01;希望您在这里可以感受到一份轻松愉快的氛围&#xff0c;不仅可以获得有趣的内容和知识&#xff0c;也可以畅所欲言、分享您的想法和见解。 推荐:kwan 的首页,持续学…

构建Android studio版的CarSystemUI工程时因为包名一致导致BuildConfig问题

项目场景&#xff1a; 公司计划开发杰发AC8025-Android 12版本车载平台&#xff0c;前期预研需要构建Android studio版的CarSystemUI工程 问题描述 AAOS车载项目里面的CarSystemUI源码默认无Android studio版本&#xff0c;为了后期快速开发调试需要构建Android studio能直接…

python多线程与多进程开发实践及填坑记(1)

1. 需求分析 1.1. 概述 基于Flask、Pika、Multiprocessing、Thread搭建一个架构&#xff0c;完成多线程、多进程工作。具体需求如下&#xff1a; 并行计算任务&#xff1a;使用multiprocessing模块实现并行计算任务&#xff0c;提高计算效率、计算能力。消息侦听任务&#x…

大厂都在加急招人的大模型LLM,到底怎么学?

大模型如何入坑&#xff1f; 想要完全了解大模型&#xff0c;你首先要了解市面上的LLM大模型现状&#xff0c;学习Python语言、Prompt提示工程&#xff0c;然后深入理解Function Calling、RAG、LangChain 、Agents等 很多人不知道想要自学大模型&#xff0c;要按什么路线学&a…

电脑刚删除的文件怎么恢复?可使用这几种恢复方法!

在日常生活和工作中&#xff0c;我们时常会在电脑上进行各种文件操作&#xff0c;包括删除不需要的文件。然而&#xff0c;有时候我们可能会误删一些重要的文件&#xff0c;或者在删除后立刻意识到这些文件的重要性。 那么&#xff0c;电脑刚删除的东西怎么恢复呢&#xff1f;本…

神领物流项目第一天

文章目录 聚焦快递领域首先第一个是验证码模块流程登录接口权限管家 聚焦快递领域 首先第一个是验证码模块流程 首先生成验证码的流程 可以使用工具类去生成验证码 LineCaptcha lineCaptcha CaptchaUtil.createLineCaptcha(160, 60, 4, 26);// 获取值然后存入redis中 strin…