Smart Home Control System

Smart Home Control System

● Development background: curriculum design

● Development time: 2021-06-21 ~ 2021-07-02

● Item description:

It is used to monitor the home environment, using SpringBoot + Mybatis + Java + JavaScrpit + CSS + Html to write the webpage and the back-end part, but the sensor data is simulated by the Java program and transmitted to the server.

● Job content: I am responsible for the design and development of the entire project in this project.


● page display

insert image description here


overall design

The system adopts the java program to upload the sensor data simulated to the cloud server. On the cloud server, the service program written using the Spring framework receives the data and saves it to the server database. The server also provides real-time display of data and real-time control services of some equipment. Users can access the webpage of the cloud server on the PC side to obtain real-time data and control some equipment services. The flow chart is as follows:
insert image description here

detailed design


● Simulated sensor data

First, use java's Math.random() method to randomly generate data. This method will generate a decimal between [0,1), and subtracting 0.5 from this number will result in a value between [-0.5,+0.5). In this way, fluctuations in the data can be simulated. The random() - offset in the source code can further reduce the fluctuation range of the data, making it more stable to simulate the data.

//偏移值作用类似于0.5 但是为了更逼真的模拟,限制一下波动范围
//波动范围 [-0.4,0.4)
static double offset = 0.4; 
public static double random() {
    
    
    return Math.random() * 0.8;//缩小生成随机数的范围
}

//数据生成的函数
public static void generatStart() {
    
    
	//新建线程单独生成数据
	(new Thread(() -> {
    
    
		while (true) {
    
    
		//定义数据的趋向稳定波动范围在指定值为centralAirConditioningControler的±2个单位之内
		double scope = 2;
		//获取当前传感器温度 和 控制温度(控制者期望到达的温度) 的差值
		double temX = sd.centralAirConditioningControler - sd.airTemperatureInSide;
		//如果差值大于 控制温度的可控波动范围的±2
		if (temX > scope)
		    //数据直接 + random() 即 数据 + [0,0.8)
		    sd.airTemperatureInSide = dataFormater(sd.airTemperatureInSide + random(), 1);
		if (temX < - scope)
		    sd.airTemperatureInSide = dataFormater(sd.airTemperatureInSide - random(), 1);
		//如果数据在指定的范围内则进行随机加减 等价于 ‘数据’+ [-0.4 , 0.4)
		if (temX >= - scope && temX <= scope)
		    sd.airTemperatureInSide = dataFormater(sd.airTemperatureInSide + random() - offset, 1);
//.....省略代码

The control of temperature fluctuation is realized here. For example, when the user sends a control command from the browser, centralAirConditioningControler will be designated as the temperature specified by the user. At this time, the temperature will continue to approach the specified temperature, and finally stay at the target temperature ± 2 units
Types of transmitted data within :

double airTemperatureOutSide;//室外温度
double airTemperatureInSide;//室内温度
double humidity;//湿度
double internetSpeed;//网速
double lightingIntensity;//灯光亮度
double solarBattery;//太阳能
double waterTemperature;//水温
double powerConsumption;//功率
int deviceNumber;//设备数量
double waterTemperatureController;//水温调节
double lightingControler;//亮度调节
double centralAirConditioningControler;//中央空调控制




● Data transfer protocol

Use the Http protocol method = HttpMethod.POST; to convert the data into JSON string format and send it to the server, and then wait for the server to return the control data set.

//服务器地址
String url = "http://**.**.**.***:8080/student4/json/data";
//post请求
HttpMethod method = HttpMethod.POST;
//发送的json数据
String json = JSON.toJSONString(sd);
//发送http请求并返回结果
String result = HttpRestClient(url, method, json);
//接收反馈数据用于控制设备的模拟数据
SensorReturn sr = JSONObject.parseObject(result,SensorReturn.class);




● Data reception and storage

The server side uses the controller of the spring framework to receive json data, and after parsing the json string, call the SQL statement to insert the data into the database for storage

	@ResponseBody//访问/json/data来传输数据
    @RequestMapping(value = "/json/data", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public String getByJSON(@RequestBody JSONObject jsonParam) {
    
    
	    //将json数据转化成java对象
        SensorData sd = jsonParam.toJavaObject(SensorData.class);
        //调用mapper中的sql语句
		homeService.insertMsg(sd);
        return JSON.toJSONString(sr).toString();
    }
    
//将数据插入数据库
<insert id="insertMsg">
        insert into smart_home(airTemperatureOutSide,airTemperatureInSide, humidity,internetSpeed,lightingIntensity,solarBattery,waterTemperature,
powerConsumption,deviceNumber,waterTemperatureController,lightingControler,centralAirConditioningControler)values(#{
    
    airTemperatureOutSide},#{
    
    airTemperatureInSide},#{
    
     humidity},#{
    
    internetSpeed},#{
    
    lightingIntensity},#{
    
    solarBattery},#{
    
    waterTemperature},#{
    
    
powerConsumption},#{
    
    deviceNumber},#{
    
    waterTemperatureController},#{
    
    lightingControler},#{
    
    centralAirConditioningControler}
        )
</insert>




● Query display of data

Browser web access /mastercontrol path to get the latest data and control panel

@GetMapping("/mastercontrol")
    public String mastercontrol(Model model) {
    
    
        //查询最近的传感器数据
        SensorData nearMsg = homeService.getNearMsg();
        //将数据放入Attribute 以方便 js 访问数据
        model.addAttribute("sensor", nearMsg);
        model.addAttribute("sr", sr);
        //返回页面
        return "mastercontrol";
    }

In the webpage js, use the timed task to continuously access the controller to refresh the data

	setInterval(function () {
    
    
        refresh();//刷新数据
    }, 200);  //200ms反复执行函数本身
    
    function refresh(){
    
    
		//发送请求刷新获得返回的数据并刷新指定标签
 	    $.ajax({
    
    
            url: basePath + '/index/refresh',
            type: 'post',
            dataType: 'text',
            data: {
    
    },
            cache: false,
            async: true,
            success: function (data) {
    
    
                $("#statusBar").empty();
                $("#statusBar").append(data);
            }
        });
        //....................省略代码
	}

Embed the obtained data into the attributes of html and display it

<br/> <span class="status_data" th:text="${sensor.airTemperatureOutSide}"></span>

insert image description here





● User control over device

insert image description here

Obtain the data entered by the user in the browser and store the data in the background by accessing the controller, and send the stored control data set to the device every time the sensor sends data to the server

$(function () {
    
    
	//监听用户输入数据的动作
   $("#range_waterTemperature").on("input", function () {
    
    
	//获取用户输入的数据
        var percent = $("#range_waterTemperature").val();
		//将数据打包为json发给controller
        $.ajax({
    
    
            url: basePath + '/waterTemperatureControllerReturn',
            type: 'post',
            contentType: "application/json",
            data: JSON.stringify(percent),
            success: function (data) {
    
    
                console.log(data)
            }
        });
        cwSvgProgress.draw($("#cw_svg_waterTemperature"), percent / 100, '.path_waterTemperature');
    });
    cwSvgProgress.draw($('#cw_svg_waterTemperature'), $("#range_waterTemperature").val()/100, '.path_waterTemperature');
    cwSvgProgress.draw($('#circleBg_waterTemperature'), 1, '.circleBg_path_waterTemperature');
});
 	@ResponseBody
    @RequestMapping("/waterTemperatureControllerReturn")
    public String waterTemperatureControllerReturn( @RequestBody Double percent) {
    
    
		//将数据存在java对象中,等待发送
        sr.waterTemperatureControllerReturn = percent;
        return "null";
    }
	@ResponseBody//访问/json/data来传输数据
    @RequestMapping(value = "/json/data", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public String getByJSON(@RequestBody JSONObject jsonParam) {
    
    
	    //将json数据转化成java对象
        SensorData sd = jsonParam.toJavaObject(SensorData.class);
        //调用mapper中的sql语句
		homeService.insertMsg(sd);
		//将数据回传给设备
        return JSON.toJSONString(sr).toString();
    }





Debugging and testing

Use IntelliJ IDEA IDE to build and debug the sensor simulation program and the war package to be deployed to the tomcat on the server, use Navicat to connect to the server MySQL database and deploy the database table on the server database, use Google chrome and Microsoft edge for front-end interaction Adapter to adapt and debug the front-end interface. Use Xshell and Xftp to connect to the cloud server and upload files to the server

Guess you like

Origin blog.csdn.net/qq_44965927/article/details/118487009