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.mzph.cn/web/40523.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

图书馆数据仓库

目录 1.数据仓库的数据来源为业务数据库&#xff08;mysql&#xff09; 初始化脚本 init_book_result.sql 2.通过sqoop将mysql中的业务数据导入到大数据平台&#xff08;hive&#xff09; 导入mysql数据到hive中 3.通过hive进行数据计算和数据分析 形成数据报表 4.再通过sq…

【matlab】智能优化算法——求解目标函数

智能优化算法在求解目标函数方面发挥着重要作用&#xff0c;它通过迭代、筛选等方法来寻找目标函数的最优值&#xff08;极值&#xff09;。以下是关于智能优化算法求解目标函数的详细介绍&#xff1a; 一、智能优化算法概述 智能优化算法是一种搜索算法&#xff0c;旨在通过…

设置单实例Apache HTTP服务器

配置仓库 [rootlocalhost ~]# cd /etc/yum.repos.d/ [rootlocalhost yum.repos.d]# vi rpm.repo仓库代码&#xff1a; [BaseOS] nameBaseOS baseurl/mnt/BaseOS enabled1 gpgcheck0[AppStream] nameAppStream baseurl/mnt/AppStream enabled1 gpgcheck0挂载 [rootlocalhost …

2.4G无线收发芯片 XL2401D,SOP16封装,集成单片机,高性价比

XL2401D 芯片是工作在2.400~2.483GHz世界通用ISM频段&#xff0c;片内集成了九齐 NY8A054E单片机的SOC无线收发芯片。芯片集成射频收发机、频率收生器、晶体振荡器、调制解调器等功能模块&#xff0c;并且支持一对多组网和带ACK的通信模式。发射输出功率、工作频道以及通信数据…

网络基础:IS-IS协议

IS-IS&#xff08;Intermediate System to Intermediate System&#xff09;是一种链路状态路由协议&#xff0c;最初由 ISO&#xff08;International Organization for Standardization&#xff09;为 CLNS&#xff08;Connectionless Network Service&#xff09;网络设计。…

油猴脚本高级应用:拦截与修改网页Fetch请求实战指南

油猴脚本高级应用&#xff1a;拦截与修改网页Fetch请求实战指南 简介&#xff1a; 本文介绍了几个使用油猴&#xff08;Tampermonkey&#xff09;脚本拦截和修改网页 fetch 请求的案例。这些脚本可以在浏览器扩展油猴中运行&#xff0c;用于开发者调试网络请求或自定义页面行…

Vue 前端修改页面标题无需重新打包即可生效

在public文件夹下创建config.js文件 index.html页面修改 其他页面的标题都可以用window.title来引用就可以了&#xff01;

【雷丰阳-谷粒商城 】【分布式高级篇-微服务架构篇】【19】认证服务03—分布式下Session共享问题

持续学习&持续更新中… 守破离 【雷丰阳-谷粒商城 】【分布式高级篇-微服务架构篇】【19】分布式下Session共享问题 session原理分布式下session共享问题Session共享问题解决—session复制Session共享问题解决—客户端存储Session共享问题解决—hash一致性Session共享问题…

ASUS/华硕飞行堡垒8 FX506L FX706L系列 原厂win10系统 工厂文件 带F12 ASUS Recovery恢复

华硕工厂文件恢复系统 &#xff0c;安装结束后带隐藏分区&#xff0c;一键恢复&#xff0c;以及机器所有驱动软件。 系统版本&#xff1a;Windows10 原厂系统下载网址&#xff1a;http://www.bioxt.cn 需准备一个20G以上u盘进行恢复 请注意&#xff1a;仅支持以上型号专用…

域名、网页、HTTP概述

目录 域名 概念 域名空间结构 域名注册 网页 概念 网站 主页 域名 HTTP URL URN URI HTML 超链接 发布 HTML HTML的结构 静态网页 特点 动态网页 特点 Web HTTP HTTP方法 GET方法 POST方法 HTTP状态码 生产环境下常见的HTTP状态码 域名 概念 IP地…

基于.NET开源游戏框架MonoGame实现的开源项目合集

前言 今天分享一些基于.NET开源游戏框架MonoGame实现的开源项目合集。 MonoGame项目介绍 MonoGame是一个简单而强大的.NET框架&#xff0c;使用C#编程语言可以创建桌面PC、视频游戏机和移动设备游戏。它已成功用于创建《怒之铁拳4》、《食肉者》、《超凡蜘蛛侠》、《星露谷物…

【跟我学K8S】45天入门到熟练详细学习计划

目录 一、什么是K8S 核心功能 架构组件 使用场景 二、入门到熟练的学习计划 第一周&#xff1a;K8s基础和概念 第二周&#xff1a;核心对象和网络 第三周&#xff1a;进阶使用和管理 第四周&#xff1a;CI/CD集成和监控 第五周&#xff1a;实战模拟和案例分析 第六周…

XPointer 实例

XPointer 实例 1. 引言 XPointer 是一种用于定位 XML 文档中特定部分的语言。它是 XLink 的补充,允许用户在 XML 文档中创建链接,指向文档中的特定元素、属性或文本。XPointer 的强大之处在于其精确的定位能力,使得开发者能够创建更加丰富和动态的 XML 应用。 2. XPointe…

【Spring Boot】spring boot主启动类_内置服务

1、主启动类 1.1 定义与功能 Spring Boot的主启动类是一个特殊的Java类&#xff0c;用于启动Spring Boot应用程序。该类通常使用SpringBootApplication注解进行标注&#xff0c;这个注解是一个复合注解&#xff0c;包含SpringBootConfiguration、EnableAutoConfiguration和Co…

LRU Cache 双向链表以及STL list实现----面试常考

双向链表版本&#xff1a; #include <bits/stdc.h> using namespace std; struct Node{int key, value;Node* prev;Node* next;Node():key(0), value(0), prev(nullptr), next(nullptr){}Node(int k, int v):key(k), value(v), prev(nullptr), next(nullptr){} }; class…

【IT领域新生必看】Java中的对象创建魔法:小白也能掌握的五种方法

文章目录 引言为什么需要创建对象&#xff1f;创建对象的五种常见方式1. 使用 new 关键字示例&#xff1a; 2. 使用反射示例&#xff1a; 3. 使用克隆示例&#xff1a; 4. 使用序列化和反序列化示例&#xff1a; 5. 使用工厂方法示例&#xff1a; 选择合适的对象创建方式总结 引…

Spring容器Bean之XML配置方式

一、首先看applicationContext.xml里的配置项bean 我们采用xml配置文件的方式对bean进行声明和管理&#xff0c;每一个bean标签都代表着需要被创建的对象并通过property标签可以为该类注入其他依赖对象&#xff0c;通过这种方式Spring容器就可以成功知道我们需要创建那些bean实…

IPython代码块粘贴秘籍:效率与技巧的完美结合

标题&#xff1a;IPython代码块粘贴秘籍&#xff1a;效率与技巧的完美结合 在数据科学和Python编程的日常实践中&#xff0c;经常需要在IPython环境中快速有效地粘贴代码块。这个过程虽小&#xff0c;却对提升工作效率至关重要。本文将详细介绍如何在IPython中粘贴代码块&…

comsol随机材料参数赋值

comsol随机材料参数赋值 在comsol中定义外部matlab函数 在comsol中定义外部matlab函数 首选项&#xff0c;安全性&#xff0c;允许 材料中&#xff0c;将杨氏模量更改为变量函数 计算 应力有波动&#xff0c;可见赋值成功 也可以看到赋值的材料参数&#xff1a;

植物大战僵尸杂交版V2.1+修改器+融合版

植物大战僵尸杂交版v2.1 新增新植物&#xff0c;全新模式与玩法&#xff01; 内含窗口放大工具与修改器 主播同款游戏&#xff0c;下载使用即可&#xff01; 链接: https://pan.baidu.com/s/1znjbqgBSdqTJWZLBOhe5hA?pwdj6ra 提取码: j6ra