configParamSps200

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>Learn LMS - Configure SPS200</title>
		<style type="text/css">
		#container {
			width: 100%;
			height: 100%;
			margin: auto;
			background-image: url(${pageContext.request.contextPath}/img/BG1.jpg);
		}
		
		#title {
			/*border:1px solid red;*/
			width: 50%;
			color: #15a2b3;
			font-size: 24px;
			font-weight: bold;
			display: flex;
			justify-content: center;
			margin: 0 auto;
			padding-top:5%;
			padding-bottom:1%;
		}
		html,body{
			margin: 0px;
			padding: 0px;
			/* background-image: url(${pageContext.request.contextPath}/img/BG1.jpg); */
		}
		body{
		   background-image: url(${pageContext.request.contextPath}/img/BG1.jpg);
		}
	       /* DIM Level */
	      .slide_father{
	        width: 559px;
	        height: 68px;
	        background-color: #E4E5E5;
	        margin: 0 auto;
	        position: relative;
	        border-radius: 29px;
	        box-shadow: 6px 6px 5px #888888;
	      }
	      .slide_son1{
	        width: 512px;
	        height: 40px;
	        background-color: #B3B2B3;
	        position: absolute;
	        left: 50%;
	        top: 14px;
	        margin-left: -256px;
	        border-radius: 22px;
	        box-shadow: 9px 9px 9px #999 inset;
	      }
	      .slide_son2{
	        width: 482px;
	        height: 16px;
	        FILTER: progid:DXImageTransform.Microsoft.Gradient(gradientType=0, startColorStr=#AC07BD, endColorStr=#f6f6f8); /*IE 6 7 8*/
	        background: -moz-linear-gradient(right, #545655 40%, #ffffff 100%);
	        background: -ms-linear-gradient(right, #545655, #ffffff);
	        background: -webkit-linear-gradient(right, #545655 40%,#ffffff 100%);
	        position: absolute;
	        left: 50%;
	        top: 26px;
	        margin-left: -241px;
	        border-radius: 12px;
	        /*box-shadow: -8px -8px 5px #888888;*/
	        box-shadow:8px 8px 8px #999 inset; 
	      }
	      .slide_ball{
	        width: 22px;
	        height: 22px;
	        background-color: #45A265;
	        background: radial-gradient(circle,SeaGreen,DarkGreen,Green);
	        background: -ms-radial-gradient(circle,SeaGreen,DarkGreen,Green); 
	        border-radius: 50%;
	        position: absolute;
	        left: 29px;
	        top: 22px;   
	        box-shadow: 4px 4px 4px #888888;    
	      }
	      .comment_father{
	        margin: 0 auto;
	        width: 500px;
	        height: 26px;
	        /*border: 1px solid red;*/
	      }
	      .comment_son1{
	        /*margin-left: 20px;*/
	        /*width: 742px;*/
	        height: 12px;
	        /*border: 1px solid green;*/
	      }
	      /* ul,li{
	        margin: 0;
	        padding: 0;
	        list-style: none;
	      } */
	      .comment_father ul,.comment_ps_father ul{
	        margin: 0;
	        padding: 0;
	        list-style: none;
	      }
	      .comment_son1 ul li{
	        float: left;
	        padding-right: 29px;
	        font-size: 12px;
	        line-height: 12px;
	        color: #28383A;
	      }
	      .comment_son1 ul li:first-child{
	        padding-left: 10px;
	      }
	      .comment_son1 ul li:last-child{
	        padding-right: 0;
	      }
	      .comment_son2{
	        margin-left: 5px;
	        height: 12px;
	        /*border: 1px solid blue;*/
	      }
	      .comment_son2 ul li{
	        float: left;
	        padding-right: 49px;
	        font-size: 12px;
	        line-height: 12px;
	        color: #28383A;
	      }
	      .comment_son2 ul li:first-child{
	        padding-left: 10px;
	      }
	      .comment_son2 ul li:last-child{
	        padding-right: 0;
	      }
	      .slide_title{
	        color: #080;
	        padding-left: 15%;
	        position: absolute;
	        margin: auto;
	      }
	      .dimLevel{
	          position: absolute;
	          font-size: 18px;
	          color: #f10215;
	          top: 20px;
	          left: 580px;
	      }      
	      
	  
	      /* Schedule */
	      .schedule{
	    	padding-left: 15%;
	        height: 50px;
	        /*border: 1px solid red;*/
	      }
	      .sche_checkbox{
	        height: 30px;
	        line-height: 50px;
	        color: #686969;
	        font-size: 18px;
	      }
	      .sche_checkbox input {
	        vertical-align: -2px;
	      }
	     /* lightIntensity */
	     .lightIntensity{
	       padding-left: 15%;
	       height: 50px;
	       color: #686969;
	       /* border: 1px solid red; */
	     }
	     .title_lightIntensity{
		       height: 30px;
		       float: left;
		       color: #686969;
		       font-size: 18px;
		       /*border: 1px solid #ccc;*/
		     }
		     .s_lightIntensity{
				float: left;
		       /*用div的样式代替select的样式*/
		       width: 130px;
		       height: 30px;
		       position: relative;
		     }
	     .s_lightIntensity select{
	        width: 100%;
	        height: 2.2em;
	        padding: 0.0em 0.4em 0.0em 0.4em;
	        vertical-align : middle;
	        border: 1px solid #626462;
	        -moz-border-radius: 0.2em;
	        -webkit-border-radius: 0.2em;
	        border-radius: 0.2em;
	        -webkit-appearance: none;
	        -moz-appearance: none;
	        appearance: none;
	        /* background: #F4F4F6; */
	        font-size: 14px;
	        color: #8D8E92;
	        cursor: pointer;
	        /* background: url(select_arrow.png) no-repeat right; */
	        background: #F4F4F6 url(${pageContext.request.contextPath}/img/select_arrow.png) no-repeat right;
	     }
	     .s_lightIntensity select option:hover { 
	         background-color: #f80; 
	         color: #FFB6C1; 
	     }
	     
	     /* Month */
	      .winter_month{
	        width: 50%;
	        /*text-align: center; */
	        font-size: 18px;
	        color: #686969;
	        /*border: 1px solid green;*/
	      }
	      .winter_month input{
	        width: 60px;
	        height: 30px;
	        border: 1px solid #D7D8DA;
	        font-size: 18px;
	        text-indent: 1.5em;
	      }
	      .summer_month{
	        width: 50%;
	        /*margin-left: 29px;*/
	        font-size: 18px;
	        color: #686969;
	        /*border: 1px solid blue;*/
	      }
	      .summer_month input{
	        width: 60px;
	        height: 30px;
	        border: 1px solid #D7D8DA;
	        font-size: 18px;
	        text-indent: 1.5em;
	      }
	      .wm_number,.sm_number,.ws_number,.we_number{
	        font-size: 12px;
	        color: #f10215;
	      }
	      .winter_start{
	        width: 322px;
	        float: left;
	        font-size: 18px;
	        color: #686969;
	        /*border: 1px solid green;*/
	      }
	      .winter_start input{
	        width: 140px;
	        height: 30px;
	        border: 0 none; 
	        outline-style: none;
	        border: 1px solid #D7D8DA;
	        font-size: 18px;
	        text-indent: 0.5em;
	      }
	      .winter_end{
	        width: 342px;
	        float: left;
	        font-size: 18px;
	        color: #686969;
	        /*border: 1px solid blue;*/
	      }
	      .winter_end input{
	        width: 140px;
	        height: 30px;
	        border: 0 none; 
	        outline-style: none;
	        border: 1px solid #D7D8DA;
	        font-size: 18px;
	        text-indent: 0.5em;
	      }
	      .summer_start{
	        width: 342px;
	        float: left;
	        font-size: 18px;
	        color: #686969;
	        /*border: 1px solid green;*/
	      }
	      .summer_start input{
	        width: 140px;
	        height: 30px;
	        border: 0 none; 
	        outline-style: none;
	        border: 1px solid #D7D8DA;
	        font-size: 18px;
	        text-indent: 0.5em;
	      }
	      .summer_end {
	        width: 342px;
	        float: left;
	        font-size: 18px;
	        color: #686969;
	        /*border: 1px solid blue;*/
	      }
	      .summer_end input{
	        width: 140px;
	        height: 30px;
	        border: 0 none; 
	        outline-style: none;
	        border: 1px solid #D7D8DA;
	        font-size: 18px;
	        text-indent: 0.5em;
	      }
	        /* area_block_floor_light_info */
	        .area_block{
	          margin: 0 auto;
	          width: 40%;
	          height: 300px;
	          border: 1px solid #D7D8DA;
	          overflow: auto;
	        }
	        
	        /* button */
	          .config_btn{
	          margin: 20px auto;
	          /* width:400px;
	          height:100px; */
	          text-align: center;
	          color: green;
	        }
	        .config_btn button{
	          width: 10%;
	          color: green;
	          cursor: pointer;
	        }
	        .feedback{
	          margin: 0 auto 20px;
	          /* width: 400px;
	          height: 400px; */
	          /*border: 1px solid red;*/        
	        }
	        .feedback .info{
	          text-align: center;
	          height: 40px;
	          line-height: 40px;
	          color: #f10215;
	          /*border: 1px solid green;*/
	        }   
	        .t_title{
	          margin: 0 auto;
	          height: 40px;
	          line-height: 40px;
	          text-align: center;
	          font-weight: 500;
	          color: #f10215;
	          border:1px solid #D7D8DA;
	          width:50%;
	          border-bottom: none;
	        }   
	        .show_table{
	          margin: 0 auto;
	          width: 50%;
	          height: 150px;
	          /*border: 1px solid #D7D8DA;*/
	          overflow: auto;
	          border-top: none;
	        }
	        .show_table table{
	          /*border: 1px solid #686969;*/
	          border-collapse: collapse;
	          text-align: center;
	          color: #686969;
	          font-weight: 500;
	          width: 100%;
	          margin: 0;
	          border-spacing: 0;
	        }
	        .show_table td{
	          border: 1px solid #D7D8DA;
	          width: 25%;
	          height: 40px;
	          line-height: 40px;
	          padding: 0;
	        }
	        .show_table td.t_td{
	          font-size: 14px;
	        }
	        .show_table td.t_td.light span{
	          color: #f10215;
	        }
	        .resubmit{
	          margin: 0 auto 30px;
	          text-align: center;
	          color: green;
	        }
	        .resubmit button{
	          width: 10%;
	          color: green;
	          cursor: pointer;
	        }
	        
	      /* Configure Device Time */
	      .deviceTime{
	        width: 75%;
	        margin: 0 auto;
	        height: 50px;
	        /*border: 1px solid red;*/
	      }
	      .deviceTime_checkbox{
	        margin-left: 26px;
	        height: 50px;
	        float: left;
	        line-height: 50px;
	        color: #686969;
	        font-size: 18px;
	      }
	      .deviceTime_checkbox input {
	        vertical-align: -2px;
	      }
	    	#bottom {
			width: 100%;
			text-align: center;
			font-size: 15px;
		}
	</style>
	
		<link rel="stylesheet" href="${pageContext.request.contextPath}/css/bootstrap.min.css">
		<link rel="stylesheet" href="${pageContext.request.contextPath}/css/font-awesome.min.css">
	    <link rel="stylesheet" href="${pageContext.request.contextPath}/css/jquery.mCustomScrollbar.min.css">
		<link rel="stylesheet" href="${pageContext.request.contextPath}/css/style2.css">
		<link rel="stylesheet" href="${pageContext.request.contextPath}/js/ztree/zTreeStyle.css" type="text/css">
		
		<script src="${pageContext.request.contextPath}/js/jquery-3.3.1.min.js"></script>
		<script src="${pageContext.request.contextPath}/js/solid.js"></script>
		<script src="${pageContext.request.contextPath}/js/fontawesome.js"></script>
		<script src="${pageContext.request.contextPath}/js/jquery.mCustomScrollbar.concat.min.js"></script>
	  	<script src="${pageContext.request.contextPath}/js/popper.min.js"></script>
		<script src="${pageContext.request.contextPath}/js/bootstrap.min.js"></script>	
		<script src="${pageContext.request.contextPath}/js/ztree/jquery.ztree.all-3.5.js"></script>	
		<script src="${pageContext.request.contextPath}/js/mqttws31.js"></script>
	
		<script type="text/javascript">
		    $(document).ready(function () {
		        $("#sidebar").mCustomScrollbar({
		            theme: "minimal"
		        });
		
		        $('#sidebarCollapse').on('click', function () {
		            $('#sidebar, #content').toggleClass('active');
		            $('.collapse.in').toggleClass('in');
		            $('a[aria-expanded=true]').attr('aria-expanded', 'false');
		        });
		        
		        var clientName = "lms_server" + new Date().getTime();
				//Using the HiveMQ public Broker, with a random client Id
				 var client = new Messaging.Client("localhost", 9001, clientName);

				 //Gets  called if the websocket/mqtt connection gets disconnected for any reason
				 client.onConnectionLost = function (responseObject) {
				     //Depending on your scenario you could implement a reconnect logic here
				     alert("connection lost: " + responseObject.errorMessage);
				 };

				 //Gets called whenever you receive a message for your subscriptions
				 client.onMessageArrived = function (message) {
				     //Do something with the push message you received
				     $('#messages').append('<span>Topic: ' + message.destinationName + '  | ' + message.payloadString + '</span><br/>');
				 };

				//Connect Options
				 var options = {
				     timeout: 3,
				     userName: clientName,
				     password: clientName,
				     //Gets Called if the connection has sucessfully been established
				     onSuccess: function () {
				    	 /*var msg = "Hello from LMS"
				    	 var topic = "${topic}"
				         alert("Topic: " + topic + ", Msg: ");
		    	  		 publish(msg, topic, 1);
		    	  		 client.disconnect();*/
				     },
				     //Gets Called if the connection could not be established
				     onFailure: function (message) {
				         alert("Connection failed: " + message.errorMessage);
				     }
				 };

				 //Creates a new Messaging.Message Object and sends it to the HiveMQ MQTT Broker
				 var publish = function (payload, topic, qos) {
				     //Send your message (also possible to serialize it as JSON or protobuf or just use a string, no limitations)
				     var message = new Messaging.Message(payload);
				     message.destinationName = topic;
				     message.qos = qos;
				     client.send(message);
					 console.info("mqtt msg: " + message);
				 }
				 
 	  			client.connect(options);
 	  			
 	  			$("#config_param").on("click",function(){
					var flag = true;
					//1.eventID(这个是作为唯一标识)
					var myData = new Date(); 
					var eventId = myData.getTime();//当前时间的毫秒数	
					//console.log(eventID);
					
					var treeObj = $.fn.zTree.getZTreeObj("ztree2");
					var list = treeObj.getCheckedNodes(true); //获取选中的节点,如果只有部分子节点被选中了,父节点也会被选中,过滤掉父节点
					if (list && list.length > 0) {
		                // 清空原数据
		                var array = new Array();
	                    var blockTopics = new Array();
		                for (var i = 0; i < list.length; i++) {
		                	if(list[i].level!=0){		                    		
		                        // 过滤父节点,nodes[i].getCheckStatus().half===true表示是半选中
		                        if (list[i].getCheckStatus().half != true && list[i].getParentNode().checked==true 
		                        		&& list[i].getParentNode().getCheckStatus().half!=false) {
		                        	array.push(list[i]);
		                        	blockTopics.push(list[i].topic);

		                        }
		                	}else if(list[i].level==0){
		                		// 过滤父节点,nodes[i].getCheckStatus().half===true表示是半选中
		                        if (list[i].getCheckStatus().half != true) {
		                        	array.push(list[i]);
		                        	blockTopics.push(list[i].topic);

		                        }
		                	}
		                };
		            }
					// console.log("array:",array);
					
					var jsonArray = new Array();
					var jsonId = [];				        
					if(array==undefined){
						flag = false;
						alert('Please select the lights you need config!');
						return;
					}else{
				        for (var i = 0; i < array.length; i++) {
				        	var j = {};
				        	var id = array[i].id;
				        	j.topic = array[i].topic;
				        	//console.log("id",id);
				        	if(id.indexOf("community")!=-1){
				        		//j.whatId = "1";				//EDIT FOR SENDING TO DONGLE 100519
				        		//j.idValue = id.substring(9);
				        		j.whatId = 1;
				        		j.idValues = [parseInt(id.substring(9))];				        		
				        		//console.log("community");
				        	}else if(id.indexOf("block")!=-1){
				        		//j.whatId = "2";
				        		//j.idValue = id.substring(5);
				        		j.whatId = 2;
				        		j.idValues = [parseInt(id.substring(5))];
				        		//console.log("block");
				        	}else if(id.indexOf("floor")!=-1){
				        		//j.whatId = "3";
				        		//j.idValue = id.substring(5);
				        		j.whatId = 3;
					        	var floorNO = array[i].floorNO;
					        	j.idValues = [parseInt(floorNO)];
				        		//j.idValues = [parseInt(id.substring(5))];
				        		//console.log("floor");
				        	}else if(id.indexOf("light")!=-1){
				        		//j.whatId = "4";
				        		//j.idValue = id.substring(5);
				        		j.whatId = 4;
					        	var lightSN = array[i].lightSN;
					        	j.idValues = [parseInt(lightSN)];
				        		//j.idValues = [parseInt(id.substring(5))];
				        		//console.log("light");
				        	}
				        	jsonId.push(j);
				        	jsonArray.push(jsonId);
				        }
						
					}
			        // console.log(jsonID);
			        //2.PIR
			        var pirObj = $("#pirEnable").get(0);		        
			        if(pirObj.checked){
			        	var pir = 1;
			        }else{
			        	var pir = 0;
			        }
			        
			        //4.dimLvl
			        var dimLevel = $('.dimLevel').text().trim();
			        dimLevel = parseInt(dimLevel);
			        // console.log(dimLevel);
			        
			        //9.RTC
			        var rtcObj = $("#rtc").get(0);
			        if(rtcObj.checked){
			        	var rtc = 1;
			        }else{
			        	var rtc = 0;
			        }
			        // console.log("RTC",rtc);
			        
			        //10.wintermonth
			        var wintermonth = $("#wintermonth").val().trim();
			        wintermonth = parseInt(wintermonth);
			        // console.log(wintermonth);
			        
			        //11.summermonth
			        var summermonth = $("#summermonth").val().trim();
			        summermonth = parseInt(summermonth);
			        
			        function getStrTime(time){
			        	var array = time.split(':');
			        	var hour = array[0];
			        	var minute = array[1];
			        	strTime = hour + minute;
			        	return strTime;		        	
			        }
			        
			        //12.deviceTime
			        var deviceTimeObj = $("#deviceTime").get(0);
			        if(deviceTimeObj.checked){
			        	var deviceTime = 1;
			        }else{
			        	var deviceTime = 0;
			        }
			        console.log("deviceTime",deviceTime);
			        
			        //12.WT
			        var wst = $("#winterstart").val().trim();
			        wst = getStrTime(wst);
			        //console.log("wst",wst);	
			        var wet = $("#winterend").val().trim();
			        wet = getStrTime(wet);
			        var wt = wst + wet;
			        //console.log("WT",wt);
			        
			        //14.ST
			        var sst = $("#summerstart").val().trim();
			        sst = getStrTime(sst);
			        //console.log("sst",sst);
			        var set = $("#summerend").val().trim();
			        set = getStrTime(set);
			        //console.log("set",set);
			        var st = sst + set;
			        //console.log("ST",st);
			        
			        //15.userId
			        var userId = ${currentUser.userId};
			        //console.log("userId",userId);
			        
			        //16.lightIntensity
			        var lightIntensity = $("#lightIntensity option:selected").val().trim();
			        lightIntensity = parseInt(lightIntensity);
			        console.log(lightIntensity);
			        
					var ws;
					//这里的SPS100项目路径一定要带上,否则找不到。
					var protocal = '<%=SchemeValue%>'=='http'?"ws://":"wss://";
					console.info("protocal:" + protocal);
					<%-- var target = "wss://"+ '<%=websocketPath%>' + "websocket/smartControl"; --%>
					var target = protocal+ '<%=websocketPath%>' + "websocket/smartControl";
					console.log("target:" + target);
					if ('WebSocket' in window) {
						 ws = new WebSocket(target);
					 } else if ('MozWebSocket' in window) {
						 ws = new MozWebSocket(target);
					 } else {
						 alert('WebSocket is not supported by this browser.');
						 return;
					}
					
					ws.onopen = function(){
						sendMessage();
					};

					function sendMessage(){
						//把json对象转成String
						var str = JSON.stringify(params);
						//console.info("params" + str);
						//这里先演示传入一个字符串,后面会从数据库查询数,然后封装成一个json字符串对象传给后台广播给C程序
						var r = confirm('Submit the config parameters?');
							if(r == true){
								/*ws.send(str);
								ws.close();
								//发送之后提示Ready to send data....							
								$(".info").html("Ready to send data to server....");
								//每次发送一周都要清空错误数据
								$("#table tr").eq(0).siblings().remove();
								//提交的时候禁用按钮
								document.getElementById('config_param').disabled = true;
								document.getElementById('resubmit').disabled = true;*/
								
								for (var i=0;i < blockTopics.length;i++){	
									for (var j = 0; j < jsonArray.length; j++) {
										if (jsonArray[0][j].topic == blockTopics[i]){
								        	delete jsonArray[0][j]['topic'];
								        	
								        	var params = {
									        		eventId:eventId,
									        		messageCode:4,
									        		jsonId:[jsonArray[0][j]],
									        		pir:pir,
									        		dimLvl:dimLevel,
									        		rtc:rtc,
									        		wm:wintermonth,
									        		sm:summermonth,
									        		wt:wt,
									        		st:st,
									        		deviceTime:deviceTime,
									        		lightIntensity:lightIntensity,
									        		userId:userId
									        };
											
											console.log(params);
											console.log("This one sent to: " + blockTopics[i]);
											var msg = JSON.stringify(params);
										    var topic = blockTopics[i];
										    //alert("Topic: " + topic + ", Msg: " + msg);
								    	    publish(msg, topic, 1);
										}
							        }
								}
							}else{
					    	    alert("Cancelled!");
							}
						
						//这里是回调函数,websocket广播的json数据就是发送到这里
						//应该在外面定义一个count统计变量,否则每次进来都会被初始化成0
						var count = 0;
						ws.onmessage = function(message){
							eval("var msg = " + message.data + ";");
							//console.info("msg",msg);
							if(undefined!=msg.eventId && undefined!=msg.messageCode && eventId==msg.eventId){
								console.log(msg.flag);
								if(msg.flag!=undefined && msg.flag==1){
									$(".info").html("The data is all assembled.....");
								}else if(msg.flag!=undefined && msg.flag==2){
									//这个其实如果是响应很快的话这个其实是不会执行的,但是实际上实惠执行的,因为处理总需要时间,而且C程序返回传输也需要时间
									$(".info").html("All data was successfully sent....");
								}
								//(在这里可以做填充表格数据的代码)
								//只有eventId一致并且code是100才是C程序响应给SPS100的
								//console.log("eventId",eventId);
								//console.log("msg.eventId",msg.eventId);
								//console.log("count",count);
								//console.log("msg.count",msg.count);
								if(msg.messageCode==104){
									count++;
									console.log("count",count);
									//这里就需要添加表格
									console.log('lightId',msg.lightId);	
									if(msg.lightId!=undefined && msg.infoList!=undefined){									
										var infoList = msg.infoList;
										console.log("infoList",infoList);
										//遍历并添加表格
										//遍历数组 for循环
										for(var i=0;i<infoList.length;i++){									
											var lightId = infoList[i].lightId;
											var lightName = infoList[i].lightName;
											var floorName = infoList[i].floorName;
											var blockName = infoList[i].blockName;
											var communityName = infoList[i].communityName;
											$("#table").append("<tr><td class=\"t_td light\"><span id=\""+lightId+"\">"+lightName+"</span></td><td class=\"t_td\">"+floorName+"</td><td class=\"t_td\">"+blockName+"</td><td class=\"t_td\">"+communityName+"</td></tr>");
										}
									}
								}
								//只有次数一致才能关闭连接,因为如果客户端为0也会断开
								if(msg.count!=0 && msg.count==count){	
									$(".info").html("All lights are fully configured!....");
									//关闭连接之前可以通知,如果infoList为0,说明没有失败的灯,这个时候可以告诉全部配置成功
								 	var spanObjs = $("#table span");
								 	//如果没有lihgt的列表,说明是没有配置失败
							     	if(spanObjs.length==0){
							    	 	$(".info").html("All configured successfully!");
							     	}else{
							     		$(".info").html("Some lights configured failed!");
							     	}
								 	//如果全部处理完毕两个按钮都要解禁
								 	document.getElementById('config_param').disabled = false;
									document.getElementById('resubmit').disabled = false;
									ws.close(); //关闭TCP连接
								}
								//如果msg.count为0说明C程序是没有block连接上websocket服务
								if(msg.count==0){
									$(".info").html("No device connect the websocket service....");
									//如果客户端没有连接两个按钮要解禁
									document.getElementById('config_param').disabled = false;
									document.getElementById('resubmit').disabled = false;
									ws.close();
								}
							}
						};
						
					}
				});
		    });
		    
		 	// DIM Level 
		    $(function(){
			      var $slide = $(".slide_father");
			      var $bar = $(".slide_son2");
			      var $ball = $(".slide_ball");
			      var $dimLevel = $(".dimLevel");
			      var ballLeft = $ball.position().left;
			      var startX = 29;
			      var width = $bar.width();
			
			      // 跃进功能
			      $bar.on('click',function(e){
			          // 获取点击的位置和进度条宽度的比例
			          // 通过比例去计算播放时间
			          // e.offsetX e.offsetY 当前点击的地方 距离坐标的左边和上边的坐标
			          //相对于当前元素的
			          var barX = e.offsetX + 20;
			          if(barX>=482){
			            barX = 482;
			          }
			          $ball.css("left",barX);
			          ballLeft = $ball.position().left;
			          if(ballLeft>=482){
			              ballLeft = 482;
			          }
			          //这里加10是因为从10%开始标识的
			          var ratio = Math.floor(((ballLeft-50)/width)*100+10);
			          if(ratio<=10){
			            ratio = 10;
			          }else if(ratio>=100){
			            ratio = 100;
			          }
			          $('.dimLevel').html(ratio);
			      });
			      
			      //滑动:进度条拖拽
			      var ball = $ball.get(0); 
			      var slide = $slide.get(0);
			      var bar = $bar.get(0);
			      ball.onmousedown = function(){
			          // console.log(bar.offsetWidth);
			          document.onmousemove = function(e){
			              var leftv = e.clientX - bar.offsetLeft - slide.offsetLeft - 250;
			              if(leftv<=0){
			                  leftv = 0;
			              }else if(leftv>=482){
			                leftv = 482;
			              }
			              var ratio2 = Math.floor(((leftv-25)/width)*100+10);
			              // console.log('ratio2',ratio2); 
			              leftv = leftv + 29;              
			              ball.style.left = leftv + 'px';
			              if(ratio2<=10){
			                ratio2 = 10;
			              }else if(ratio2>=100){
			                ratio2 = 100;
			              }
			              $('.dimLevel').html(ratio2);
			          };
			          document.onmouseup = function(){
			              document.onmousemove = null;
			              document.onmouseup = null;
			          };
			      };
			
			    });
		    
			      //Winter Month && Summer Month
			      $(function(){
			          var $wintermonth = $("#wintermonth");
			          var flag = false;
			          $wintermonth.on('blur',function(){            
			            var wintermonth = $wintermonth.val();
			            if(wintermonth<1 || wintermonth>12){
			              flag = false;
			              $(".wm_number").html('Invalid Number');
			              alert('Winter Month Number should between 1 and 12!');
			            }else{
			              flag = true;
			              $(".wm_number").html('');
			            }
			            if(flag){              
			              if(!/^\d+$/.test(wintermonth)){
			                $(".wm_number").html('Invalid Number');
			                alert('This number must be integer!');
			              }else{
			                $(".wm_number").html('');
			              }
			            }
			          });
			
			          var $summermonth = $("#summermonth");
			          var flag = false;
			          $summermonth.on('blur',function(){            
			            var summermonth = $summermonth.val();
			            if(summermonth<1 || summermonth>12){
			              flag = false;
			              $(".sm_number").html('Invalid Number');
			              alert('Summer Month Number should between 1 and 12!');
			            }else{
			              flag = true;
			              $(".sm_number").html('');
			            }
			            if(flag){              
			              if(!/^\d+$/.test(summermonth)){
			                $(".sm_number").html('Invalid Number');
			                alert('This number must be integer!');
			              }else{
			                $(".sm_number").html('');
			              }
			            }
			          });
			      });
			     /* ztree实现层级area_block_floor_light_info */
			     $(function(){
			    	 	//初始化输入框的值
			    	 	$("#winterstart").val("08:00");
			    	 	$("#winterend").val("17:30");
			    	 	$("#summerstart").val("07:00");
			    	 	$("#summerend").val("19:00");
						var setting2 = {
								data: {
									simpleData: {
										enable: true //使用简单json数据构造ztree节点
									}
								},
								check: {
								    enable: true
								},
								view: {
									fontCss : {color:"#000"}
								},
								callback:{
									onCheck: zTreeOnCheck
								}
						};
						setting2.check.chkboxType = { "Y" : "ps", "N" : "ps" };
						//发送ajax请求,获取json数据
						//jquery提供的ajax方法:ajax,post,get,load,getJSON,getScript		
						//var url = "${pageContext.request.contextPath}/json/menu.json";
						var url = "${pageContext.request.contextPath}/showSPS200ZtreeMenu.action";
						$.post(url,{},function(data){
							//console.log('data',data);
						 //调用API初始化ztree
						 $.fn.zTree.init($("#ztree2"), setting2, data);						
						},'json');				
			     });
				function zTreeOnCheck(){
					refreshLayers();
					clearCheckedOldNodes();
				}
				//刷新图层的显示情况
				var layers;
				function refreshLayers() {
					var zTree = $.fn.zTree.getZTreeObj("ztree2");
					var changedNodes = zTree.getChangeCheckedNodes();
					for ( var i=0 ; i < changedNodes.length ; i++ ){
						var treeNode = changedNodes[i];
					}
				}
				
				//清理善后工作
				function clearCheckedOldNodes() {
					var zTree = $.fn.zTree.getZTreeObj("ztree2"),
					nodes = zTree.getChangeCheckedNodes();
					for (var i=0, l=nodes.length; i<l; i++) {
						nodes[i].checkedOld = nodes[i].checked;
					}
				};
				
			$(function(){
				//Resubmit
				$("#resubmit").on("click",function(){
					var flag = true;
					//1.eventID(这个是作为唯一标识)
					var myData = new Date(); 
					var eventId = myData.getTime();//当前时间的毫秒数	
					//console.log(eventID);
					
					//2.PIR
			        var pirObj = $("#pirEnable").get(0);		        
			        if(pirObj.checked){
			        	var pir = 1;
			        }else{
			        	var pir = 0;
			        }
			        
			      //4.dimLvl
			        var dimLevel = $('.dimLevel').text().trim();
			        dimLevel = parseInt(dimLevel);
			        // console.log(dimLevel);
			        
			        //9.RTC
			        var rtcObj = $("#rtc").get(0);
			        if(rtcObj.checked){
			        	var rtc = 1;
			        }else{
			        	var rtc = 0;
			        }
			        // console.log("RTC",rtc);
			        
			        //10.wintermonth
			        var wintermonth = $("#wintermonth").val().trim();
			        wintermonth = parseInt(wintermonth);
			        // console.log(wintermonth);
			        
			        //11.summermonth
			        var summermonth = $("#summermonth").val().trim();
			        summermonth = parseInt(summermonth);
			        
			        function getStrTime(time){
			        	var array = time.split(':');
			        	var hour = array[0];
			        	var minute = array[1];
			        	strTime = hour + minute;
			        	return strTime;		        	
			        }
			        
			        //12.deviceTime
			        var deviceTimeObj = $("#deviceTime").get(0);
			        if(deviceTimeObj.checked){
			        	var deviceTime = 1;
			        }else{
			        	var deviceTime = 0;
			        }
			        console.log("deviceTime",deviceTime);
			        
			        //12.WT
			        var wst = $("#winterstart").val().trim();
			        wst = getStrTime(wst);
			        //console.log("wst",wst);	
			        var wet = $("#winterend").val().trim();
			        wet = getStrTime(wet);
			        var wt = wst + wet;
			        //console.log("WT",wt);
			        
			        //14.ST
			        var sst = $("#summerstart").val().trim();
			        sst = getStrTime(sst);
			        //console.log("sst",sst);
			        var set = $("#summerend").val().trim();
			        set = getStrTime(set);
			        //console.log("set",set);
			        var st = sst + set;
			        //console.log("ST",st);
			        
			        //15.userId
			        var userId = ${currentUser.userId};
			        //console.log("userId",userId);
			        
			        //16.lightIntensity
			        var lightIntensity = $("#lightIntensity option:selected").val().trim();
			        lightIntensity = parseInt(lightIntensity);
			        console.log(lightIntensity);
			        
			        var spans = $("#table span");
			        //console.log(spans);
			        var idArrays = new Array();
			        for(var i=0;i<spans.length;i++){
			            var spanObj = spans[i];
			            var idVal = spanObj.id;
			            idArrays.push(idVal);
			        }
			        //console.log('idArrays',idArrays);
			        var jsonId = [];
			        if(idArrays.length<1){
			           alert('No failed lights are required to be configured!');
			           return;
			        }else{
			          for(var i=0;i<idArrays.length;i++){
			              var j = {};
			              j.whatId = 4;
			              j.idValue = idArrays[i];
			              jsonId.push(j);
			          }
			        }
			        console.log('jsonId',jsonId);
			        
			        var params = {
			        		eventId:eventId,
			        		messageCode:4,
			        		jsonId:jsonId, 
			        		pir:pir,
			        		dimLvl:dimLevel,
			        		rtc:rtc,
			        		wm:wintermonth,
			        		sm:summermonth,
			        		wt:wt,
			        		st:st,
			        		deviceTime:deviceTime,
			        		lightIntensity:lightIntensity,
			        		userId:userId
			        };
			        console.log("params",params);
					var ws;
					//这里的SPS100项目路径一定要带上,否则找不到。
					var protocal = '<%=SchemeValue%>'=='http'?"ws://":"wss://";
					console.info("protocal:" + protocal);
					<%-- var target = "wss://"+ '<%=websocketPath%>' + "websocket/smartControl"; --%>
					var target = protocal+ '<%=websocketPath%>' + "websocket/smartControl";
					console.log("target:" + target);
					if ('WebSocket' in window) {
						 ws = new WebSocket(target);
					 } else if ('MozWebSocket' in window) {
						 ws = new MozWebSocket(target);
					 } else {
						 alert('WebSocket is not supported by this browser.');
						 return;
					}
					ws.onopen = function(){
						sendMessage();
					};
					function sendMessage(){
						//把json对象转成String
						var str = JSON.stringify(params);
						//console.info("params" + str);
						//这里先演示传入一个字符串,后面会从数据库查询数,然后封装成一个json字符串对象传给后台广播给C程序
						var r = confirm('Submit the config parameters?');
							if (r == true){
								ws.send(str);
								ws.close(); //关闭TCP连接
								//发送之后提示Ready to send data....							
								$(".info").html("Ready to send data to server....");
								//每次发送一周都要清空错误数据
								$("#table tr").eq(0).siblings().remove();
								//重新提交的时候两个按钮要禁用
								document.getElementById('config_param').disabled = true;
								document.getElementById('resubmit').disabled = true;
							} else{
					    	    alert("Cancelled!");
							}
						
						//这里是回调函数,websocket广播的json数据就是发送到这里
						//应该在外面定义一个count统计变量,否则每次进来都会被初始化成0
						var count = 0;
						ws.onmessage = function(message){
							eval("var msg = " + message.data + ";");
							//console.info("msg",msg);
							if(undefined!=msg.eventId && undefined!=msg.messageCode && eventId==msg.eventId){
								console.log(msg.flag);
								if(msg.flag!=undefined && msg.flag==1){
									$(".info").html("The data is all assembled.....");
								}else if(msg.flag!=undefined && msg.flag==2){
									//这个其实如果是响应很快的话这个其实是不会执行的,但是实际上实惠执行的,因为处理总需要时间,而且C程序返回传输也需要时间
									$(".info").html("All data was successfully sent....");
								}
								//(在这里可以做填充表格数据的代码)
								//只有eventId一致并且code是100才是C程序响应给SPS100的
								if(msg.messageCode==104){
									count++;
									console.log("count",count);
									//这里就需要添加表格
									console.log('lightId',msg.lightId);	
									if(msg.lightId!=undefined && msg.infoList!=undefined){								
										var infoList = msg.infoList;
										console.log("infoList",infoList);
										//遍历并添加表格
										//遍历数组 for循环
										for(var i=0;i<infoList.length;i++){									
											var lightId = infoList[i].lightId;
											var lightName = infoList[i].lightName;
											var floorName = infoList[i].floorName;
											var blockName = infoList[i].blockName;
											var communityName = infoList[i].communityName;
											$("#table").append("<tr><td class=\"t_td light\"><span id=\""+lightId+"\">"+lightName+"</span></td><td class=\"t_td\">"+floorName+"</td><td class=\"t_td\">"+blockName+"</td><td class=\"t_td\">"+communityName+"</td></tr>");
										}
									}
								}
								//只有次数一致才能关闭连接,因为如果客户端为0也会断开
								if(msg.count!=0 && msg.count==count){	
									 $(".info").html("All lights are fully configured!");
									 //关闭连接之前可以通知,如果infoList为0,说明没有失败的灯,这个时候可以告诉全部配置成功
									 var spanObjs = $("#table span");
									 //如果没有lihgt的列表,说明是没有配置失败
									 console.log("spanObjs.length",spanObjs.length);
								     if(spanObjs.length==0){
								    	 $(".info").html("All configured successfully!");
								     }else{
								     	 $(".info").html("Some lights configured failed!");
								     }
									 //如果所有的灯都配置完毕就需要解禁按钮
									 document.getElementById('config_param').disabled = false;
									 document.getElementById('resubmit').disabled = false;
									 ws.close(); //关闭TCP连接
								}
								//如果msg.count为0说明C程序是没有block连接上websocket服务
								if(msg.count==0){
									$(".info").html("No device connect the websocket service!");
									//如果客户端没有设备连接websocket就需要解禁所有的按钮
									document.getElementById('config_param').disabled = false;
									document.getElementById('resubmit').disabled = false;
									ws.close();
								}
							}
						};
						
					}
				});
				
			});
		</script>
	</head>

	<body>
		<div class="wrapper">
        	<!-- Sidebar  -->
        	<nav id="sidebar">
	            <div class="sidebar-header">
	                <font color="#1c6299" size="7" face="Arial"><b>Learn</b></font>
	                <font color="#15a2b3" size="7" face="Helvetica"><b>tech</b></font>
	                <br><font color="#5d5b5d" size="5" face="Calibri">Smart LMS v1.0.1</font>
	            </div>
	            
	            <div class="sidebar-username"><font color="black">Welcome, ${currentUser.userName}</font></div>
	            	<ul class="list-unstyled components">            
		                <li>
		                    <a href="${pageContext.request.contextPath}/community/dashboard.action">Home dashboard</a>
		                </li>
		                <li>
		                    <a href="${pageContext.request.contextPath}/community/controlLights.action">Control lights</a>
		                </li>
		                <li>
		                    <a href="#pageSubmenu2" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle">Configure lights</a>
		                    <ul class="list-unstyled" id="pageSubmenu2">
		                        <li>
		                            <a href="${pageContext.request.contextPath}/configParam.action">SPS100</a>
		                        </li>
		                        <li class="active">
		                            <a href="${pageContext.request.contextPath}/sps200Config.action">SPS200</a>
		                        </li>
		                        <li>
		                            <a href="${pageContext.request.contextPath}/photoParam.action">Photosensor</a>
		                        </li>
		                        <li>
	                            	<a href="${pageContext.request.contextPath}/configAddNew.action">Add new data</a>
		                        </li>
		                    </ul>
		                </li>
		                <li>
		                	<a href="#pageSubmenu3" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle">Manage account</a>
		                    <ul class="collapse list-unstyled" id="pageSubmenu3">
		                   		<li>
		                            <a href="${pageContext.request.contextPath}/user/user_account.action">Update profile</a>
		                        </li>
		                        <li>
		                            <a href="${pageContext.request.contextPath}/user/user_register.action">Register new user</a>
		                        </li>
		                        <li>
		                            <a href="${pageContext.request.contextPath}/user/user_management.action">User management</a>
		                        </li>	
		                    </ul>
		                </li>
		            </ul>
	
	            	<ul class="list-unstyled CTAs">
		                <li>
	                    <a href="${pageContext.request.contextPath}/user/logout.action" class="download">Logout</a>
		                </li>
						<li><br>
							<div id="time" style="text-align:center">
								<script>
									updateTime();
									function updateTime() {
										var date = new Date().toLocaleString();
										var day = new Date().getDay();
										var datetime;
										if (day == 0) {
											day = "<br>Sunday";
										} else if (day == 1) {
											day = "<br>Monday";
										} else if (day == 2) {
											day = "<br>Tuesday";
										} else if (day == 3) {
											day = "<br>Wednesday";
										} else if (day == 4) {
											day = "<br>Thursday";
										} else if (day == 5) {
											day = "<br>Friday";
										} else {
											day = "<br>Saturday";
										}
		
										datetime = date + day;
										document.getElementById('time').innerHTML = datetime;
									}
									setInterval("updateTime()", 1000);
								</script>
							</div>
						</li>
					</ul>
		        </nav>
        
				<div id="content">
					<div class="main">
						<div id="container">
						
						<div id="title">Configure SPS200 Lights</div>
	
						<div id="first_hr">
							<hr align="center" width="80%" color="#b5b7b9">
						</div>	
	
					    <!-- DIM Level -->
					 	<div class="slide_title">DIM Level (10-100%)</div>
					    <br><br>
					    <div class="comment_father">
					        <div class="comment_son1">
					          <ul>
					            <li>10%</li>
					            <li>20%</li>
					            <li>30%</li>
					            <li>40%</li>
					            <li>50%</li>
					            <li>60%</li>
					            <li>70%</li>
					            <li>80%</li>
					            <li>90%</li>
					            <li>100%</li>
					          </ul>
					        </div>
					        <div class="comment_son2">
					          <ul>
					            <li>|</li>
					            <li>|</li>
					            <li>|</li>
					            <li>|</li>
					            <li>|</li>
					            <li>|</li>
					            <li>|</li>
					            <li>|</li>
					            <li>|</li>
					            <li>|</li>
					          </ul>
					        </div>
				    	</div>
				    
					    <div class="slide_father">
					  		<div class="slide_son1"></div>
						    <div class="slide_son2"></div>
						    <div class="slide_ball"></div>
					      	<div class="dimLevel">10</div>
					    </div>
					    
					 	<br>
					    
						<!-- D/E PIR Sensitivity -->
						<div class="schedule">
					  		<div class="sche_checkbox">
					        PIR D/E &nbsp;&nbsp;&nbsp;<input type="checkbox" checked="checked" id="pirEnable">
					      </div>
					    </div>
											
					    <!-- Schedule --> 
					    <div class="schedule">
					  		<div class="sche_checkbox">
					        Schedule: D/E &nbsp;&nbsp;&nbsp;<input type="checkbox" checked="checked" id="rtc">
					      </div>
					    </div>
					    
					    <!-- lightIntensity -->
					    <div class="lightIntensity">    
					        <div class="title_lightIntensity">
					          Light Intensity:&nbsp;&nbsp;
					        </div>
						    <div class="s_lightIntensity">
						        <select id="lightIntensity">
						          <option value="1">Fast</option>
						          <option value="2" selected="selected">Medium</option>
						          <option value="3">Slow</option>
						        </select>
						    </div>
					    </div>
				    
				    	<br>
				    
					    <!-- Month -->
					    <table style="width: 70%; margin: auto">
					    	<tr><td>Group 1 </td><td>Group 2</td></tr>
					    	<tr><td>					
						    	<div id="first_hr">
								<hr align="left" width="70%" color="#b5b7b9">
								</div></td><td>					
								<div id="first_hr">
								<hr align="left" width="70%" color="#b5b7b9">
								</div>
							</td></tr>
					    	<tr>
					    		<td style="width:30%;">
					    			<div class="winter_month">
								  	Period: <input style="margin-left:42px" type="text" name="wintermonth" value="10" id="wintermonth"> 
								  	<span class="wm_number"></span>
					      			</div>
					    		</td>
					    		<td style="width:30%;">
									<div class="summer_month">
								 	Period: <input style="margin-left:42px" type="text" name="summermonth" value="5" id="summermonth"> 
								  	<span class="sm_number"></span>
					      			</div>
					    		</td>
					    	</tr>
					    	
					    	<tr>
					    		<td style="width:35%;">
					    			<div class="winter_start">
							        Start time: <input style="margin-left:10px" type="time" name="winterstart" id="winterstart"> 
							        <span class="ws_number"></span>
					      			</div>
					    		</td>
					    		<td style="width:35%;">
									<div class="summer_start">
									Start time: <input style="margin-left:10px" type="time" name="summerstart" id="summerstart"> 
									<span class="we_number"></span>
					     			</div>
					    		</td>
					    	</tr>
					    	
					    	<tr>
					    		<td style="width:35%;">
					    			<div class="winter_end">
								    End time: <input style="margin-left:20px" type="time" name="winterend" id="winterend">
					      			</div>
					    		</td>
					    		<td style="width:35%;">
									<div class="summer_end">
								    End time: <input style="margin-left:20px" type="time" name="summerend" id="summerend">
								    </div>
					    		</td>
					    	</tr>
					    </table>
					
						<br>
					    <!-- Configure Device Time --> 
					    <div class="deviceTime">
					      <div class="deviceTime_checkbox">
					        Configure Device Time: D/E &nbsp;&nbsp;&nbsp;<input type="checkbox" id="deviceTime">
					      </div>
					    </div>
					    
						<!-- area_block_floor_light_info -->
					    <div class="area_block">      
					      <ul id="ztree2" class="ztree">
					      </ul>
					    </div>
					    
					    <div class="config_btn">
					    	<button id="config_param">Submit</button>
					    </div>
					    
					    <!-- <div class="feedback">
					      <div class="info"></div>      
					    </div>
					    
					    <div class="t_title">List of Configuration failed SPS200</div>
					    <div class="show_table">
					    	<table id="table" border="1">
					   		  <tr>
					   		 	<td>Light</td>
					            <td>Floor</td>
					            <td>Block</td>
					            <td>Area</td>
					   		  </tr>
					    	</table>
					    </div>
					    
					    <div class="resubmit">
					      <button id="resubmit">Resubmit</button>
					    </div> -->
					</div>
	
					<div id="bottom">
						<p>
							<br><font color="#999">Copyright &copy; 1986 - 2018</font> <b>Learn Group Ltd. All rights reserved.</b>
						</p>
					</div>
				</div>
			</div>
		</div>
	</body>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值