Commit 3a36587b authored by 史余彬's avatar 史余彬

环境监测demo

parents
Pipeline #128 failed with stages
# Getting Started
### Reference Documentation
For further reference, please consider the following sections:
* [Official Apache Maven documentation](https://maven.apache.org/guides/index.html)
* [Spring Boot Maven Plugin Reference Guide](https://docs.spring.io/spring-boot/docs/2.3.3.RELEASE/maven-plugin/reference/html/)
* [Create an OCI image](https://docs.spring.io/spring-boot/docs/2.3.3.RELEASE/maven-plugin/reference/html/#build-image)
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
<component name="FacetManager">
<facet type="Spring" name="Spring">
<configuration />
</facet>
<facet type="jpa" name="JPA">
<configuration>
<setting name="validation-enabled" value="true" />
<setting name="provider-name" value="Hibernate" />
<datasource-mapping>
<factory-entry name="entityManagerFactory" />
</datasource-mapping>
<naming-strategy-map />
</configuration>
</facet>
</component>
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_8">
<output url="file://$MODULE_DIR$/target/classes" />
<output-test url="file://$MODULE_DIR$/target/test-classes" />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="jdk" jdkName="1.8" jdkType="JavaSDK" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter:2.3.3.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot:2.3.3.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-context:5.2.8.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-expression:5.2.8.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-autoconfigure:2.3.3.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-logging:2.3.3.RELEASE" level="project" />
<orderEntry type="library" name="Maven: ch.qos.logback:logback-classic:1.2.3" level="project" />
<orderEntry type="library" name="Maven: ch.qos.logback:logback-core:1.2.3" level="project" />
<orderEntry type="library" name="Maven: org.apache.logging.log4j:log4j-to-slf4j:2.13.3" level="project" />
<orderEntry type="library" name="Maven: org.apache.logging.log4j:log4j-api:2.13.3" level="project" />
<orderEntry type="library" name="Maven: org.slf4j:jul-to-slf4j:1.7.30" level="project" />
<orderEntry type="library" name="Maven: jakarta.annotation:jakarta.annotation-api:1.3.5" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-core:5.2.8.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-jcl:5.2.8.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.yaml:snakeyaml:1.26" level="project" />
<orderEntry type="library" name="Maven: org.projectlombok:lombok:1.18.12" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework.boot:spring-boot-starter-test:2.3.3.RELEASE" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework.boot:spring-boot-test:2.3.3.RELEASE" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework.boot:spring-boot-test-autoconfigure:2.3.3.RELEASE" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: com.jayway.jsonpath:json-path:2.4.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.minidev:json-smart:2.3" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.minidev:accessors-smart:1.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.ow2.asm:asm:5.0.4" level="project" />
<orderEntry type="library" name="Maven: jakarta.xml.bind:jakarta.xml.bind-api:2.3.3" level="project" />
<orderEntry type="library" name="Maven: jakarta.activation:jakarta.activation-api:1.2.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.assertj:assertj-core:3.16.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.hamcrest:hamcrest:2.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.jupiter:junit-jupiter:5.6.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.jupiter:junit-jupiter-api:5.6.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apiguardian:apiguardian-api:1.1.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.opentest4j:opentest4j:1.2.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.platform:junit-platform-commons:1.6.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.jupiter:junit-jupiter-params:5.6.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.jupiter:junit-jupiter-engine:5.6.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.junit.platform:junit-platform-engine:1.6.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.mockito:mockito-core:3.3.3" level="project" />
<orderEntry type="library" name="Maven: net.bytebuddy:byte-buddy:1.10.14" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.bytebuddy:byte-buddy-agent:1.10.14" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.objenesis:objenesis:2.6" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.mockito:mockito-junit-jupiter:3.3.3" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.skyscreamer:jsonassert:1.5.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: com.vaadin.external.google:android-json:0.0.20131108.vaadin1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework:spring-test:5.2.8.RELEASE" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.xmlunit:xmlunit-core:2.7.0" level="project" />
<orderEntry type="library" name="Maven: org.springframework.data:spring-data-redis:2.2.5.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework.data:spring-data-keyvalue:2.3.3.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework.data:spring-data-commons:2.3.3.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-tx:5.2.8.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-beans:5.2.8.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-oxm:5.2.8.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-aop:5.2.8.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-context-support:5.2.8.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.slf4j:slf4j-api:1.7.30" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-data-redis:2.1.8.RELEASE" level="project" />
<orderEntry type="library" name="Maven: io.lettuce:lettuce-core:5.3.3.RELEASE" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-common:4.1.51.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-handler:4.1.51.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-resolver:4.1.51.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-buffer:4.1.51.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-codec:4.1.51.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-transport:4.1.51.Final" level="project" />
<orderEntry type="library" name="Maven: io.projectreactor:reactor-core:3.3.9.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.reactivestreams:reactive-streams:1.0.3" level="project" />
<orderEntry type="library" name="Maven: cn.hutool:hutool-all:5.0.6" level="project" />
<orderEntry type="library" name="Maven: org.apache.commons:commons-lang3:3.7" level="project" />
<orderEntry type="library" name="Maven: javax.servlet:javax.servlet-api:4.0.1" level="project" />
<orderEntry type="library" name="Maven: com.alibaba:fastjson:1.2.68" level="project" />
<orderEntry type="library" name="Maven: io.jsonwebtoken:jjwt-jackson:0.10.6" level="project" />
<orderEntry type="library" name="Maven: io.jsonwebtoken:jjwt-api:0.10.6" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-databind:2.11.2" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-annotations:2.11.2" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-core:2.11.2" level="project" />
<orderEntry type="library" name="Maven: org.mapstruct:mapstruct-jdk8:1.2.0.Final" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.mapstruct:mapstruct-processor:1.2.0.Final" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-data-jpa:2.3.3.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-aop:2.3.3.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.aspectj:aspectjweaver:1.9.6" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-jdbc:2.3.3.RELEASE" level="project" />
<orderEntry type="library" name="Maven: com.zaxxer:HikariCP:3.4.5" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-jdbc:5.2.8.RELEASE" level="project" />
<orderEntry type="library" name="Maven: jakarta.transaction:jakarta.transaction-api:1.3.3" level="project" />
<orderEntry type="library" name="Maven: jakarta.persistence:jakarta.persistence-api:2.2.3" level="project" />
<orderEntry type="library" name="Maven: org.hibernate:hibernate-core:5.4.20.Final" level="project" />
<orderEntry type="library" name="Maven: org.javassist:javassist:3.24.0-GA" level="project" />
<orderEntry type="library" name="Maven: antlr:antlr:2.7.7" level="project" />
<orderEntry type="library" name="Maven: org.jboss:jandex:2.1.3.Final" level="project" />
<orderEntry type="library" name="Maven: org.dom4j:dom4j:2.1.3" level="project" />
<orderEntry type="library" name="Maven: org.hibernate.common:hibernate-commons-annotations:5.1.0.Final" level="project" />
<orderEntry type="library" name="Maven: org.glassfish.jaxb:jaxb-runtime:2.3.3" level="project" />
<orderEntry type="library" name="Maven: org.glassfish.jaxb:txw2:2.3.3" level="project" />
<orderEntry type="library" name="Maven: com.sun.istack:istack-commons-runtime:3.0.11" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: com.sun.activation:jakarta.activation:1.2.2" level="project" />
<orderEntry type="library" name="Maven: org.springframework.data:spring-data-jpa:2.3.3.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-orm:5.2.8.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-aspects:5.2.8.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.hibernate.validator:hibernate-validator:6.1.0.Final" level="project" />
<orderEntry type="library" name="Maven: jakarta.validation:jakarta.validation-api:2.0.2" level="project" />
<orderEntry type="library" name="Maven: org.jboss.logging:jboss-logging:3.4.1.Final" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml:classmate:1.5.1" level="project" />
</component>
</module>
\ No newline at end of file
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
if [ -n "$MVNW_REPOURL" ]; then
jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
else
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
fi
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
esac
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if $cygwin; then
wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
fi
if command -v wget > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget "$jarUrl" -O "$wrapperJarPath"
else
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
fi
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl -o "$wrapperJarPath" "$jarUrl" -f
else
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaClass=`cygpath --path --windows "$javaClass"`
fi
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaClass")
fi
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
if [ "$MVNW_VERBOSE" = true ]; then
echo $MAVEN_PROJECTBASEDIR
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM https://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.gemho</groupId>
<artifactId>environment</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>environment</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--添加Redis依赖-->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.1.8.RELEASE</version>
</dependency>
<!--工具包-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.0.6</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.7</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.68</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.10.6</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-jdk8</artifactId>
<version>1.2.0.Final</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.2.0.Final</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.1.0.Final</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
package com.gemho.environment;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class EnvironmentApplication {
public static void main(String[] args) {
SpringApplication.run(EnvironmentApplication.class, args);
}
}
package com.gemho.environment.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author Zheng Jie
* @date 2019-6-4 13:52:30
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Query {
// Dong ZhaoYang 2017/8/7 基本对象的属性名
String propName() default "";
// Dong ZhaoYang 2017/8/7 查询方式
Type type() default Type.EQUAL;
/**
* 连接查询的属性名,如User类中的dept
*/
String joinName() default "";
/**
* 默认左连接
*/
Join join() default Join.LEFT;
/**
* 多字段模糊搜索,仅支持String类型字段,多个用逗号隔开, 如@Query(blurry = "email,username")
*/
String blurry() default "";
enum Type {
// jie 2019/6/4 相等
EQUAL
// Dong ZhaoYang 2017/8/7 大于等于
, GREATER_THAN
// Dong ZhaoYang 2017/8/7 小于等于
, LESS_THAN
// Dong ZhaoYang 2017/8/7 中模糊查询
, INNER_LIKE
// Dong ZhaoYang 2017/8/7 左模糊查询
, LEFT_LIKE
// Dong ZhaoYang 2017/8/7 右模糊查询
, RIGHT_LIKE
// Dong ZhaoYang 2017/8/7 小于
, LESS_THAN_NQ
// jie 2019/6/4 包含
, IN
// 不等于
,NOT_EQUAL
// between
,BETWEEN
// 不为空
,NOT_NULL
}
/**
* @author Zheng Jie
* 适用于简单连接查询,复杂的请自定义该注解,或者使用sql查询
*/
enum Join {
/** jie 2019-6-4 13:18:30 左右连接 */
LEFT, RIGHT
}
}
package com.gemho.environment.constants;
import java.util.HashMap;
import java.util.Map;
public class Constants {
public static final String NETTY_MONITOR_CLIENT_PORT = "7000"; //智慧农业监测设备上传端口
public static final String NETTY_RELAY_CLIENT_PORT = "8011"; //控制器端口
public static final String NETTY_MIST_CLIENT_PORT = "7001"; //烟感报警器(外采设备)
public static final String REDIS_DEVICE_CHANNEL_KEY = "device_channel"; //redis 设备和通道缓存key
public static final String REDIS_CHANNEL_DEVICE_KEY = "channel_device"; //redis 设备和通道缓存key
public static final String REDIS_Smoke_KEY = "Smoke"; //redis 烟感报警key
public static Map<String,String> sendMap = new HashMap<>();
}
package com.gemho.environment.constants;
public class RegisterToSensorConstants {
public static final String REGISTER_To_SENSOR = "{\n" +
" \"0000\":\"TMP\",\n" +
" \"0001\":\"TMP2\",\n" +
" \"0002\":\"TMP3\",\n" +
" \"0003\":\"TMP4\",\n" +
" \"0004\":\"TMP5\",\n" +
" \"0005\":\"TMP6\",\n" +
" \"0006\":\"TMP7\",\n" +
" \"0007\":\"TMP8\",\n" +
" \"0008\":\"TMP9\",\n" +
" \"0009\":\"TMP10\",\n" +
" \"0020\":\"HR\",\n" +
" \"0021\":\"HR2\",\n" +
" \"0022\":\"HR3\",\n" +
" \"0023\":\"HR4\",\n" +
" \"0024\":\"HR5\",\n" +
" \"0025\":\"HR6\",\n" +
" \"0026\":\"HR7\",\n" +
" \"0027\":\"HR8\",\n" +
" \"0028\":\"HR9\",\n" +
" \"0029\":\"HR10\",\n" +
" \"0060\":\"ILL\",\n" +
" \"0061\":\"ILL2\",\n" +
" \"0062\":\"ILL3\",\n" +
" \"0063\":\"ILL4\",\n" +
" \"0064\":\"ILL5\",\n" +
" \"0065\":\"ILL6\",\n" +
" \"0066\":\"ILL7\",\n" +
" \"0067\":\"ILL8\",\n" +
" \"0068\":\"ILL9\",\n" +
" \"0069\":\"ILL10\",\n" +
" \"0040\":\"CO2\",\n" +
" \"0041\":\"CO22\",\n" +
" \"0042\":\"CO23\",\n" +
" \"0043\":\"CO24\",\n" +
" \"0044\":\"CO25\",\n" +
" \"0045\":\"CO26\",\n" +
" \"0046\":\"CO27\",\n" +
" \"0047\":\"CO28\",\n" +
" \"0048\":\"CO29\",\n" +
" \"0049\":\"CO210\",\n" +
" \"1000\":\"sTMP\",\n" +
" \"1001\":\"sTMP2\",\n" +
" \"1020\":\"sHR\",\n" +
" \"1021\":\"sHR2\",\n" +
" \"1022\":\"sHR3\",\n" +
" \"1060\":\"sPH\",\n" +
" \"1061\":\"sPH2\",\n" +
" \"1080\":\"NN\",\n" +
" \"10A0\":\"PP\",\n" +
" \"10C0\":\"KK\",\n" +
" \"20E0\":\"RO2\",\n" +
" \"20E1\":\"RO22\",\n" +
" \"2040\":\"wTMP\",\n" +
" \"2041\":\"wTMP2\",\n" +
" \"20C0\":\"NH4\",\n" +
" \"20C1\":\"NH42\",\n" +
" \"2000\":\"wPH\",\n" +
" \"2001\":\"wPH2\",\n" +
" \"20A0\":\"NO3P\",\n" +
" \"20A1\":\"NO3P2\",\n" +
" \"2100\":\"WL\",\n" +
" \"00A0\":\"FS\",\n" +
" \"00C0\":\"FX\",\n" +
" \"0080\":\"PRS\",\n" +
" \"00E0\":\"RV\",\n" +
" \"0100\":\"RD\",\n" +
" \"0120\":\"PM25\",\n" +
" \"0140\":\"PM10\",\n" +
" \"1040\":\"sEC\",\n" +
" \"1041\":\"sEC2\",\n" +
" \"1042\":\"sEC3\",\n" +
" \"1043\":\"sEC4\"\n" +
"}";
}
package com.gemho.environment.constants;
/**
* 传感器与寄存器对照表
* @Author: liujing
* @Date: 2019/10/26 9:20
* @Version: 1.0
*/
public class SensorToRegisterConstants {
public static final String SENSOR_TO_REGISTER = "{\n" +
" \"TMP\": \"0000\",\n" +
" \"TMP2\": \"0001\",\n" +
" \"TMP3\": \"0002\",\n" +
" \"TMP4\": \"0003\",\n" +
" \"TMP5\": \"0004\",\n" +
" \"TMP6\": \"0005\",\n" +
" \"TMP7\": \"0006\",\n" +
" \"TMP8\": \"0007\",\n" +
" \"TMP9\": \"0008\",\n" +
" \"TMP10\": \"0009\",\n" +
" \"HR\": \"0020\",\n" +
" \"HR2\": \"0021\",\n" +
" \"HR3\": \"0022\",\n" +
" \"HR4\": \"0023\",\n" +
" \"HR5\": \"0024\",\n" +
" \"HR6\": \"0025\",\n" +
" \"HR7\": \"0026\",\n" +
" \"HR8\": \"0027\",\n" +
" \"HR9\": \"0028\",\n" +
" \"HR10\": \"0029\",\n" +
" \"ILL\": \"0060\",\n" +
" \"ILL2\": \"0061\",\n" +
" \"ILL3\": \"0062\",\n" +
" \"ILL4\": \"0063\",\n" +
" \"ILL5\": \"0064\",\n" +
" \"ILL6\": \"0065\",\n" +
" \"ILL7\": \"0066\",\n" +
" \"ILL8\": \"0067\",\n" +
" \"ILL9\": \"0068\",\n" +
" \"ILL10\": \"0069\",\n" +
" \"CO2\": \"0040\",\n" +
" \"CO22\": \"0041\",\n" +
" \"CO23\": \"0042\",\n" +
" \"CO24\": \"0043\",\n" +
" \"CO25\": \"0044\",\n" +
" \"CO26\": \"0045\",\n" +
" \"CO27\": \"0046\",\n" +
" \"CO28\": \"0047\",\n" +
" \"CO29\": \"0048\",\n" +
" \"CO210\": \"0049\",\n" +
" \"sTMP\": \"1000\",\n" +
" \"sTMP2\": \"1001\",\n" +
" \"sHR\": \"1020\",\n" +
" \"sHR2\": \"1021\",\n" +
" \"sHR3\": \"1022\",\n" +
" \"sPH\": \"1060\",\n" +
" \"sPH2\": \"1061\",\n" +
" \"NN\": \"1080\",\n" +
" \"PP\": \"10A0\",\n" +
" \"KK\": \"10C0\",\n" +
" \"RO2\": \"20E0\",\n" +
" \"RO22\": \"20E1\",\n" +
" \"wTMP\": \"2040\",\n" +
" \"wTMP2\": \"2041\",\n" +
" \"NH4\": \"20C0\",\n" +
" \"NH42\": \"20C1\",\n" +
" \"wPH\": \"2000\",\n" +
" \"wPH2\": \"2001\",\n" +
" \"NO3P\": \"20A0\",\n" +
" \"NO3P2\": \"20A1\",\n" +
" \"WL\": \"2100\",\n" +
" \"FS\": \"00A0\",\n" +
" \"FX\": \"00C0\",\n" +
" \"PRS\": \"0080\",\n" +
" \"RV\": \"00E0\",\n" +
" \"RD\": \"0100\",\n" +
" \"PM25\": \"0120\",\n" +
" \"PM10\": \"0140\",\n" +
" \"sEC\": \"1040\",\n" +
" \"sEC2\": \"1041\",\n" +
" \"sEC3\": \"1042\",\n" +
" \"sEC4\": \"1043\"\n" +
"}";
}
package com.gemho.environment.controller;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.gemho.environment.model.DevicetypeDto;
import com.gemho.environment.model.RelayDto;
import com.gemho.environment.model.SensorData;
import com.gemho.environment.model.SensorDto;
import com.gemho.environment.service.Channelhandler;
import com.gemho.environment.service.DevicetypeService;
import com.gemho.environment.service.SensorService;
import com.gemho.environment.service.mapper.SensorMapper;
import com.gemho.environment.utils.*;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.InetSocketAddress;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import static com.gemho.environment.utils.StringUtil.hexStringToAlgorism;
import static com.gemho.environment.utils.StringUtil.hexStringToString;
@Component
@Slf4j
@ChannelHandler.Sharable
public class ServerHandler extends SimpleChannelInboundHandler<Object> {
@Autowired
private ServerToRelayService serverToRelayService;
@Autowired
private SensorMapper sensorMapper;
@Autowired
private Channelhandler sChannelService;
@Autowired
private SensorService sensorService;
@Autowired
private DevicetypeService devicetypeService;
private static ServerHandler serverHandler;
static ScriptEngine jse = new ScriptEngineManager().getEngineByName("JavaScript");
//保留所有与服务器建立连接的channel对象,这边的GlobalEventExecutor在写博客的时候解释一下,看其doc
public static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
public static Map<String,String> ydMap = new HashMap<>();
@PostConstruct
public void init() {
serverHandler = this;
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
InetSocketAddress insocket = (InetSocketAddress) ctx.channel().localAddress();
String clientPort = String.valueOf(insocket.getPort());
log.info(ctx.channel().remoteAddress() + " " + ctx.channel().id() + " ");
/*检测类设备-7000端口*/
if (clientPort.equals(Constants.NETTY_MONITOR_CLIENT_PORT)) {
log.info("端口号 {} 接收信息: {}", Constants.NETTY_MONITOR_CLIENT_PORT, msg);
Map<String, Object> rawdataMap = new HashMap();
rawdataMap = JSON.parseObject(msg.toString(), rawdataMap.getClass()); //上传的原始数据
log.info("上传的原始数据:{}", rawdataMap);
String U = rawdataMap.get("U").toString(); //获取CPU编号
log.info("CPU编号:{}", U);
SensorDto sensorDto = sensorService.findByDeviceid(U);
// valid = 1
if (sensorDto != null && !"valid".equals("0")) {
if (sensorDto.getExpire() != null && sensorDto.getExpire().before(new Timestamp(System.currentTimeMillis()))) {
log.info("传感器设备:" + sensorDto.getDeviceid() + "的到期时间:" + sensorDto.getExpire());
ctx.channel().close();
ctx.close();
return;
}
/*配置IP和端口号*/
if (rawdataMap.containsKey("cfg")) {
String cfg = rawdataMap.get("cfg").toString();
if (cfg.equals("0")) {
ctx.channel().writeAndFlush("{\"ip\":\"" + sensorDto.getIp() + "\"," + "\"port\":" + Integer.valueOf(sensorDto.getPort()) + "}");
ctx.channel().close();
ctx.close();
return;
}
}
if (rawdataMap.containsKey("t1") && rawdataMap.containsKey("t2")) {
int t1 = Integer.valueOf(rawdataMap.get("t1").toString());
int t2 = Integer.valueOf(rawdataMap.get("t2").toString());
//比较设备时间和设置时间是否一致
if (t1 != sensorDto.getTimetrack() || t2 != sensorDto.getTimetrack2()) {
Map<String, Object> map = new HashMap<>();
map.put("t1", sensorDto.getTimetrack());
map.put("t2", sensorDto.getTimetrack2());
ctx.channel().writeAndFlush(JsonUtil.jsonObj2Sting(map));
}
}
/*信号强度*/
String Q = null;
if (rawdataMap.containsKey("Q")) {
Q = rawdataMap.get("Q").toString();
sensorDto.setRssi(Q);
}
/*电量信息*/
Double V = null;
if (rawdataMap.containsKey("V")) {
V = Double.valueOf(rawdataMap.get("V").toString()) / 1000;
sensorDto.setBattery(V.toString()); //电池电量
}
sensorDto.setOnlinetime(new Timestamp(System.currentTimeMillis()));
/*更新设备表里的电量和信号和在线时间*/
sensorService.update(sensorMapper.toEntity(sensorDto));
/*获取检测项数据*/
DevicetypeDto type = devicetypeService.findById(Long.valueOf(sensorDto.getDevicetype()));
String[] key = type.getCode().split(",");
String[] gs = type.getGs().split(",");
Long time = System.currentTimeMillis();
/*循环遍历当前设备检测项code,例如:['TMP','HR','O2']*/
for (int i = 0; i < key.length; i++) {
List<SensorData> datalst = new ArrayList<>();
if (rawdataMap.containsKey(key[i])) {
//获取上传数据中的检测数据value
List<Integer> value = (List<Integer>) rawdataMap.get(key[i]);
//如果上传数据不为空,开始处理数据
if (value != null && !value.isEmpty()) {
for (int j = value.size() - 1; j >= 0; j--) {
SensorData sensorData = new SensorData();
sensorData.setItem(key[i]);
sensorData.setDeviceid(U);
//执行公式
String zxgs = gs[i].replace("@data", value.get(j).toString());
//湿度单独处理,防止超出100
if (key[i].equals("HR") || key[i].contains("sHR")) {
try {
if (Double.valueOf(jse.eval(zxgs).toString()) > 100) {
sensorData.setData(String.valueOf(100));
} else {
sensorData.setData(String.valueOf(jse.eval(zxgs)));
}
} catch (ScriptException e) {
e.printStackTrace();
}
} else {
try {
sensorData.setData(String.valueOf(jse.eval(zxgs)));
} catch (ScriptException e) {
e.printStackTrace();
}
}
//时间处理
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if (j == value.size() - 1) {
sensorData.setDtime(dateformat.format(time));
} else {
int oldTime = (value.size() - 1 - j) * Integer.valueOf(rawdataMap.get("t1").toString());
sensorData.setDtime(dateformat.format(time - oldTime));
}
if (Q != null) {
sensorData.setRssi(Q);
}
if (V != null) {
sensorData.setBattery(String.valueOf(V));
}
log.info("处理后的数据:{}", sensorData);
if (j == value.size() - 1) {
// warnMsg(sData);
Thread t = new Thread(new Runnable() {
public void run() {
// 起线程执行报警过滤
// warnMsg(sensorData);
}
});
t.start();
}
datalst.add(sensorData);
}
Map<String, Object> finalRawdataMap = rawdataMap;
Thread t = new Thread(new Runnable() {
@SneakyThrows
public void run() {
// sendDataToRelay(key, gs, finalRawdataMap, U);
/*设备数据推送到4GLED(如果关联了4GLED)*/
serverToRelayService.sendDataTo4GMonitor(U, msg.toString());
}
});
t.start();
} else {
log.info("设备{}的检测项为:{},检测项{}没有数据", U, key, key[i]);
}
} else {
log.info("设备{}的检测项为:{},其中当前数据没有'{}'的数据", U, key, key[i]);
}
}
}
}
/*控制器设备对接-8011*/
if (clientPort.equals(Constants.NETTY_RELAY_CLIENT_PORT)){
byte[] msgbyte = StringUtil.stringToAscii(String.valueOf(msg));
// ByteBuf buf = (ByteBuf) msg;
// byte[] msgbyte = new byte[buf.readableBytes()];
String rewdata = StringUtil.bytesToHexString(msgbyte);
log.info("接收到的设备指令:{}",rewdata);
String zt = StrUtil.subWithLength(rewdata, 0, 4);
if (zt.equals("C33C")) {
/*获取数据长度*/
int datalength = Integer.parseInt(rewdata.substring(4,6),16);
log.info("获取数据长度:{}", datalength);
String CRCData = rewdata.substring(rewdata.length()-4); //获取最后4位
String ServerCRC = Integer.toHexString(CRC16Util.calcCrc16(msgbyte,3,datalength-2)).toUpperCase();
ServerCRC = StringUtils.leftPad(ServerCRC, 4, "0").toUpperCase();
log.info("服务器计算的CRC:{}, 指令的CRC:{}",ServerCRC,CRCData);
/*获取心跳包数据位数据*/
int HeartbeatDataNum = datalength-12-2; //心跳包数据位长度
String Heartbeat = StrUtil.subWithLength(rewdata,30,HeartbeatDataNum*2);
String deviceId = StrUtil.subWithLength(rewdata, 6, 24);
RelayDto relayDto = relayService.findByDeviceid(deviceId);
if (relayDto.getExpire() != null &&relayDto.getExpire().before(new Timestamp(System.currentTimeMillis()))) {
log.info("控制器设备:"+relayDto.getDeviceid()+"的到期时间:"+relayDto.getExpire());
ctx.channel().close();
ctx.close();
return;
}
/*应答处理*/
if (rewdata.substring(4,6).equals("0F")) {
String ydData = StrUtil.subWithLength(rewdata, 30, 2);
log.info("设备{}应答数据:{}",deviceId,ydData);
if (Constants.sendMap.containsKey(deviceId)) {
if (ydData.equals("00")){
ydMap.put(deviceId, "00");
}else if(ydData.equals("FF")) {
ydMap.put(deviceId, "FF");
}
}
}
/*心跳处理*/
if (Heartbeat.equals("A55A")) {
log.info("接收到设备 {} 的心跳!", deviceId);
sChannelService.setDeviceChannel(deviceId,ctx.channel().id().toString());
relayService.updateRelayOnlinetime(deviceId);//保存设备在线时间
ByteBuf bufff = Unpooled.buffer();
bufff.writeBytes(StringUtil.hexString2Bytes(rewdata));//对接需要16进制
ctx.channel().writeAndFlush(bufff);
}
/*指令处理 start*/
String commandData = StrUtil.subWithLength(rewdata, 3*2+12*2,2); //获取指令位数据 帧头*2+数据长度*2+设备ID*2
/*上传继电器状态值指令处理*/
if (commandData.equals("91")) {
String relayStatusData = StrUtil.subWithLength(rewdata, 3*2+12*2+2+4, (datalength-12-1-2-2)*2);
log.info("{}上传继电器状态值指令{}",deviceId,relayStatusData);
log.info(CRCData);
String binData = NumberUtil.getBinaryStr(Integer.parseInt(relayStatusData,16));
binData = StringUtils.leftPad(binData, 16, "0");
log.info("relayStatusBytes:{}", binData);
relayWayService.updateWayStatus(deviceId, binData);
//应答
ByteBuf bufff = resUtil(CRCData, ServerCRC,deviceId);
ctx.channel().writeAndFlush(bufff);
}else if (commandData.equals("AF")){
/*上传工作模式处理*/
String workData = StrUtil.subWithLength(rewdata, 3*2+12*2+2+4, (datalength-12-1-2-2)*2);
log.info("{}上传工作模式{}",deviceId,workData);
if (workData.equals("1111")){
relayService.updateRelayWorkMode(deviceId, "1");
}else if (workData.equals("0000")){
relayService.updateRelayWorkMode(deviceId, "0");
}
//应答
ByteBuf bufff = resUtil(CRCData, ServerCRC,deviceId);
ctx.channel().writeAndFlush(bufff);
}else if (commandData.equals("90")) {
log.info("90>>>");
/*获取设备传输的检测项*/
String deviceIdX = deviceId + "X";
String itemNum = StrUtil.subWithLength(rewdata, 3*2+12*2+2, 4);
JSONObject jsonObject = JSONUtil.parseObj(RegisterToSensorConstants.REGISTER_To_SENSOR);
String item = String.valueOf(jsonObject.get(itemNum)); //寄存器地址
String itemDataHex = StrUtil.subWithLength(rewdata, 3*2+12*2+2+4, 8);
int itemData = Integer.parseInt(itemDataHex, 16);
log.info("设备{}上传监测项为{}的数据为:{}", deviceIdX,item,itemData);
Map<String, Object> rawdataMap = new HashMap();
rawdataMap.put("U", deviceIdX);
rawdataMap.put(item, new int[]{itemData});
log.info("jsons数据{}",rawdataMap);
SensorDto sensorDto = sensorService.findByDeviceid(deviceIdX);
sensorDto.setOnlinetime(new Timestamp(System.currentTimeMillis()));
/*更新设备表里的电量和信号和在线时间*/
sensorService.update(sensorMapper.toEntity(sensorDto));
/*获取检测项数据*/
DevicetypeDto type = devicetypeService.findById(Long.valueOf(sensorDto.getDevicetype()));
String[] key = type.getCode().split(",");
String[] gs = type.getGs().split(",");
Long time =System.currentTimeMillis();
SensorData sensorData = new SensorData();
sensorData.setItem(item);
sensorData.setDeviceid(deviceIdX);
for(int i = 0; i<key.length; i++){
List<SensorData> datalst = new ArrayList<>();
if (rawdataMap.containsKey(key[i])) {
List<Integer> value = new ArrayList<>();
value.add(itemData);
if (value != null && !value.isEmpty()) {
for (int j = value.size() -1 ; j >= 0; j--){
sensorData.setItem(key[i]);
sensorData.setDeviceid(deviceIdX);
//执行公式
String zxgs = gs[i].replace("@data", value.get(j).toString());
//湿度单独处理,防止超出100
if (key[i].equals("HR") || key[i].contains("sHR")){
try {
if (Double.valueOf(jse.eval(zxgs).toString()) > 100) {
sensorData.setData(String.valueOf(100));
}else {
sensorData.setData(String.valueOf(jse.eval(zxgs)));
}
} catch (ScriptException e) {
e.printStackTrace();
}
} else {
try {
sensorData.setData(String.valueOf(jse.eval(zxgs)));
} catch (ScriptException e) {
e.printStackTrace();
}
}
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if (j == value.size() -1) {
sensorData.setDtime(dateformat.format(time));
}else {
int oldTime = (value.size()-1-j) * Integer.valueOf(rawdataMap.get("t1").toString());
sensorData.setDtime(dateformat.format(time-oldTime));
}
log.info("处理后的数据:{}",sensorData);
if (j == value.size() - 1 ) {
Thread t = new Thread(new Runnable(){
public void run(){
// 起线程执行报警过滤
warnMsg(sensorData);
}});
t.start();
}
datalst.add(sensorData);
}
//写入mangoDB
mongoTemplate.insertAll(datalst);
}
}
}
//应答
ByteBuf bufff = resUtil(CRCData, ServerCRC,deviceId);
ctx.channel().writeAndFlush(bufff);
}
}
}
if (clientPort.equals(Constants.NETTY_MIST_CLIENT_PORT)){
String receivedata = msg.toString();
log.info("端口:{},外采烟感报警器发送数据:{}",Constants.NETTY_MIST_CLIENT_PORT, receivedata);
String type = receivedata.substring(12,14);//获取消息类型
log.info("消息类型:{}", type);
if ("02".equals(type)) { //接收到心跳包
log.info("外采烟感报警器发送心跳包");
ctx.channel().writeAndFlush("2b633273000b02004f4bda");
}else if ("04".equals(type)){ //设备发送当前状态
log.info("外采烟感报警器发送自身消息");
ctx.channel().writeAndFlush("2b633273000b04004f4bdc");
}else if ("0a".equals(type)){
log.info("外采烟感报警器发送复位消息");
ctx.channel().writeAndFlush("2b633273000b09004f4be1");
}else if ("09".equals(type)){
log.info("外采烟感报警器发送报警消息");
int length = hexStringToAlgorism(receivedata.substring(8,12));//接收到的数据字节数
String equipid = hexStringToString(receivedata.substring(16,20),2) + receivedata.substring(20,32);//主设备
int total = hexStringToAlgorism(receivedata.substring(32,34));//报警总数
String defence = hexStringToString(receivedata.substring(58,64),2);//报警防区
String code = hexStringToString(receivedata.substring(48,54),2);//报警代码
log.info("信息长度:" + length + ":" + receivedata.length());
log.info("主设备ID:" + equipid);
log.info("报警总数:" + total);
log.info("报警防区:" + defence);
log.info("报警代码:" + code);
if ("111".equals(code)){
ctx.channel().writeAndFlush("2b633273000b09004f4be1");
if (!smokeAlarmCache.checkSmokeAlarmCache(equipid)){
log.info("设备{},10分钟内没有报警",equipid);
smokeAlarmCache.setSmokeAlarmCache(equipid);
//保存报警记录
Warnmsg sWarnmsg = new Warnmsg();
sWarnmsg.setDeviceid(equipid);
sWarnmsg.setItem("SW");
sWarnmsg.setFlg("0");
sWarnmsg.setMessage("发生烟雾报警");
sWarnmsg.setNt("true");
warnmsgService.create(sWarnmsg);
//获取设备关联的用户
List<User> users = userSensorService.getUserBySensorId(equipid);
//发送短信报警
for (User user : users) {
SDKTestSendTemplateSMS.sendMsg(user.getPhone(), "487466", new String[]{equipid, "发生烟雾报警"});
}
}else {
log.info("设备{},10分钟内有报警",equipid);
}
}
}
}
}
//表示服务端与客户端连接建立
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
Channel channel = ctx.channel(); //其实相当于一个connection
/* 添加 */
channelGroup.add(channel);
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
Channel channel = ctx.channel();
//验证一下每次客户端断开连接,连接自动地从channelGroup中删除调。
log.info("{}断开连接", channel.remoteAddress());
try {
sChannelService.rmDeviceChannel(channel.id().toString());
}catch (Exception e) {
}
//删除连接池的通道
channelGroup.remove(channel);
}
//连接处于活动状态
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
Channel channel = ctx.channel();
log.info(channel.remoteAddress() +" 上线了");
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
Channel channel = ctx.channel();
log.info(channel.remoteAddress() +" 下线了");
channelGroup.remove(channel);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
Channel channel = ctx.channel();
cause.printStackTrace();
channelGroup.remove(channel);
ctx.close();
}
@Override
public void userEventTriggered (ChannelHandlerContext ctx, Object evt) throws Exception {
Channel channel = ctx.channel();
log.info("{}心跳超时,删除本次连接",channel.remoteAddress());
try {
sChannelService.rmDeviceChannel(channel.id().toString());
}catch (Exception e) {
}
//删除连接池的通道
channelGroup.remove(channel);
ctx.close();
}
}
package com.gemho.environment.controller;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import lombok.extern.slf4j.Slf4j;
import com.gemho.environment.constants.Constants;
import com.gemho.environment.constants.SensorToRegisterConstants;
import com.gemho.environment.utils.CRC16Util;
import com.gemho.environment.utils.StringUtil;
import com.gemho.environment.utils.RedisUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
/**
* @Author: liujing
* @Date: 2019/10/26 10:04
* @Version: 1.0
*/
@Component
@Slf4j
public class ServerToRelayService {
@Resource
RedisUtils redisUtil;
/**
* 发送传感器数据到控制器
* @param sensorid 监测设备ID
* @param item 检测项
* @param vale 监测数据
*/
public void sendDataToRelay(String sensorid, String item, Double vale) {
log.debug("执行>>sendDataToRelay<< :监测设备ID{}, item:{}, value:{}",sensorid,item,vale);
try {
// deviceId: 控制器
String channelID = redisUtil.hget(Constants.REDIS_DEVICE_CHANNEL_KEY, "deviceId").toString();
//获取item对应的寄存器地址
JSONObject jsonObject = JSONUtil.parseObj(SensorToRegisterConstants.SENSOR_TO_REGISTER);
String register = String.valueOf(jsonObject.get("TMP2")); //寄存器地址
//数据转成十六进制码表示
String hexVale = Integer.toHexString(vale.intValue());
if (hexVale.length() < 8) {
hexVale = StringUtils.leftPad(hexVale, 8, "0").toUpperCase();
}
log.debug("hexVale:{}", hexVale);
//拼接指令
String command = "deviceId"+"80"+register+hexVale;
byte[] resByte = StringUtil.hexString2Bytes(command);
String resCRC = Integer.toHexString(CRC16Util.calcCrc16(resByte)).toUpperCase();
if (resCRC.length() < 4) {
resCRC = StringUtils.leftPad(resCRC, 4, "0").toUpperCase();
}
command = command+resCRC;
Integer dataLength = resByte.length+2;
command = "C33C"+Integer.toHexString(dataLength)+command;
String finalCommand = command.toUpperCase();
// deviceId: 控制器
log.debug("向{}控制器发送设备{}下{}传感器的指令:{}","deviceId",sensorid,item,finalCommand);
ServerHandler.channelGroup.forEach(ch -> {
// channelId 查看链接通道
if (ch.id().toString().equals(channelID)) {
ByteBuf bufff = Unpooled.buffer();
// bufff.clear();
bufff.writeBytes(StringUtil.hexString2Bytes(finalCommand));
ch.writeAndFlush(bufff);
}
});
}catch (Exception e) {
log.error(e.getMessage());
}
}
public void sendDataTo4GMonitor(String sensorid, String data) {
log.debug("执行>>sendDataTo4GMonitor<< sensorid:{}, data:{}",sensorid,data);
//设备关联的控制器
// deviceId : 控制器
log.debug("redis是否存在LED设备:"+"deviceId"+":"+redisUtil.hHasKey(Constants.REDIS_DEVICE_CHANNEL_KEY, "deviceId"));
if (redisUtil.hHasKey(Constants.REDIS_DEVICE_CHANNEL_KEY, "deviceId") == true) {
try{
//获取通道ID
String channelID = redisUtil.hget(Constants.REDIS_DEVICE_CHANNEL_KEY, "deviceId").toString();
ServerHandler.channelGroup.forEach(ch -> {
if (ch.id().toString().equals(channelID)) {
ch.writeAndFlush(data);
}
});
}catch (Exception e) {
log.error(e.getMessage());
}
}
}
}
package com.gemho.environment.model;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import lombok.Data;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
import java.sql.Timestamp;
/**
* @author 靖小侠
* @date 2020-05-08
*/
@Entity
@Data
@Table(name="s_devicetype")
public class Devicetype implements Serializable {
/** 主键 */
@Id
@Column(name = "id")
private Long id;
/** 设备类型名称 */
@Column(name = "typename")
private String typename;
/** 检测项代码 */
@Column(name = "code")
private String code;
/** 检测项名称 */
@Column(name = "subject")
private String subject;
/** 检测项计算公式 */
@Column(name = "gs")
private String gs;
/** 创建时间 */
@Column(name = "create_time")
@CreationTimestamp
private Timestamp createTime;
/** 更新时间 */
@Column(name = "update_time")
@UpdateTimestamp
private Timestamp updateTime;
public void copy(Devicetype source){
BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true));
}
}
package com.gemho.environment.model;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import lombok.Data;
import java.io.Serializable;
import java.sql.Timestamp;
/**
* @author 靖小侠
* @date 2020-05-08
*/
@Data
public class DevicetypeDto implements Serializable {
/** 主键 */
/** 防止精度丢失 */
@JsonSerialize(using= ToStringSerializer.class)
private Long id;
/** 设备类型名称 */
private String typename;
/** 检测项代码 */
private String code;
/** 检测项名称 */
private String subject;
/** 检测项计算公式 */
private String gs;
/** 创建时间 */
private Timestamp createTime;
/** 更新时间 */
private Timestamp updateTime;
}
\ No newline at end of file
package com.gemho.environment.model;
import com.gemho.environment.annotation.Query;
import lombok.Data;
/**
* @author 靖小侠
* @date 2020-05-08
*/
@Data
public class DevicetypeQueryCriteria{
/** 精确 */
@Query
private Long id;
/** 模糊 */
@Query(type = Query.Type.INNER_LIKE)
private String typename;
}
\ No newline at end of file
package com.gemho.environment.model;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import lombok.Data;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import javax.persistence.*;
import java.io.Serializable;
import java.sql.Timestamp;
/**
* @author 靖小侠
* @date 2020-05-07
*/
@Entity
@Data
@Table(name="s_relay")
public class Relay implements Serializable {
/** 主键 */
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
/** 所属公司 */
@Column(name = "company")
private String company;
/** IMEI码 */
@Column(name = "imei")
private String imei;
/** 电信编码 */
@Column(name = "telecomCode")
private String telecomcode;
/** 设备id */
@Column(name = "deviceid")
private String deviceid;
/** 监测设备类型 */
@Column(name = "devicetype")
private String devicetype;
/** 设备名称 */
@Column(name = "name")
private String name;
/** 描述 */
@Column(name = "nt")
private String nt;
/** 设备类型 0:nb 1:4g */
@Column(name = "type")
private String type;
/** 安装位置 */
@Column(name = "address")
private String address;
/** 经度 */
@Column(name = "jd")
private Double jd;
/** 纬度 */
@Column(name = "wd")
private Double wd;
/** 采集频率 */
@Column(name = "timetrack")
private Integer timetrack;
/** 上传频率 */
@Column(name = "timetrack2")
private Integer timetrack2;
/** 信号强度 */
@Column(name = "rssi")
private String rssi;
/** 电池电量 */
@Column(name = "battery")
private String battery;
/** 是否有效 */
@Column(name = "valid")
private String valid;
/** ICCID或卡号 */
@Column(name = "phoneCode")
private String phonecode;
/** ip */
@Column(name = "ip")
private String ip;
/** 端口 */
@Column(name = "port")
private String port;
/** 二维码 */
@Column(name = "qrcode")
private String qrcode;
/** 创建时间 */
@Column(name = "create_time")
@CreationTimestamp
private Timestamp createTime;
/** 更新时间 */
@Column(name = "update_time")
@UpdateTimestamp
private Timestamp updateTime;
/** 工作模式 0手动1自动 */
@Column(name = "workmode")
private String workmode;
/** 在线时间 */
@Column(name = "onlinetime")
private Timestamp onlinetime;
/** 在线 */
@Column(name = "online")
private String online;
/** 0: 普通设备 1:控制器 2:无线LED屏幕 */
@Column(name = "relay")
private String relay;
/** 到期时间 */
@Column(name = "expire")
private Timestamp expire;
/** 监测项目 */
@Column(name = "subject")
private String subject;
/** 监测项目代码 */
@Column(name = "code")
private String code;
/** 计算公式 */
@Column(name = "gs")
private String gs;
/** 运营商 */
@Column(name = "isp")
private String isp;
public void copy(Relay source){
BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true));
}
}
\ No newline at end of file
package com.gemho.environment.model;
import lombok.Data;
import java.io.Serializable;
import java.sql.Timestamp;
/**
* @author 靖小侠
* @date 2020-05-07
*/
@Data
public class RelayDto implements Serializable {
/** 主键 */
private Long id;
/** 所属公司 */
private String company;
/** IMEI码 */
private String imei;
/** 电信编码 */
private String telecomcode;
/** 设备id */
private String deviceid;
/** 监测设备类型 */
private String devicetype;
/** 设备名称 */
private String name;
/** 描述 */
private String nt;
/** 设备类型 0:nb 1:4g */
private String type;
/** 安装位置 */
private String address;
/** 经度 */
private Double jd;
/** 纬度 */
private Double wd;
/** 采集频率 */
private Integer timetrack;
/** 上传频率 */
private Integer timetrack2;
/** 信号强度 */
private String rssi;
/** 电池电量 */
private String battery;
/** 是否有效 */
private String valid;
/** ICCID或卡号 */
private String phonecode;
/** ip */
private String ip;
/** 端口 */
private String port;
/** 二维码 */
private String qrcode;
/** 创建时间 */
private Timestamp createTime;
/** 更新时间 */
private Timestamp updateTime;
/** 工作模式 0手动1自动 */
private String workmode;
/** 在线时间 */
private Timestamp onlinetime;
/** 在线 */
private String online;
/** 0: 普通设备 1:控制器 2:无线LED屏幕 */
private String relay;
/** 到期时间 */
private Timestamp expire;
/** 监测项目 */
private String subject;
/** 监测项目代码 */
private String code;
/** 计算公式 */
private String gs;
/** 运营商 */
private String isp;
}
\ No newline at end of file
package com.gemho.environment.model;
import com.gemho.environment.annotation.Query;
import lombok.Data;
/**
* @author 靖小侠
* @date 2020-05-07
*/
@Data
public class RelayQueryCriteria{
/** 精确 */
@Query
private String deviceid;
/** 模糊 */
@Query(type = Query.Type.INNER_LIKE)
private String name;
}
\ No newline at end of file
package com.gemho.environment.model;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import lombok.Data;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import javax.persistence.*;
import java.io.Serializable;
import java.sql.Timestamp;
/**
* @author 靖小侠
* @date 2020-05-07
*/
@Entity
@Data
@Table(name="s_sensor")
public class Sensor implements Serializable {
/** 主键 */
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
/** 所属公司 */
@Column(name = "company")
private String company;
/** IMEI码 */
@Column(name = "imei")
private String imei;
/** 电信编码 */
@Column(name = "telecomCode")
private String telecomcode;
/** 设备id */
@Column(name = "deviceid")
private String deviceid;
/** 监测设备类型 */
@Column(name = "devicetype")
private String devicetype;
/** 设备名称 */
@Column(name = "name")
private String name;
/** 描述 */
@Column(name = "nt")
private String nt;
/** 设备类型 0:nb 1:4g */
@Column(name = "type")
private String type;
/** 安装位置 */
@Column(name = "address")
private String address;
/** 经度 */
@Column(name = "jd")
private Double jd;
/** 纬度 */
@Column(name = "wd")
private Double wd;
/** 采集频率 */
@Column(name = "timetrack")
private Integer timetrack;
/** 上传频率 */
@Column(name = "timetrack2")
private Integer timetrack2;
/** 信号强度 */
@Column(name = "rssi")
private String rssi;
/** 电池电量 */
@Column(name = "battery")
private String battery;
/** 是否有效 */
@Column(name = "valid")
private String valid;
/** ICCID或卡号 */
@Column(name = "phoneCode")
private String phonecode;
/** ip */
@Column(name = "ip")
private String ip;
/** 端口 */
@Column(name = "port")
private String port;
/** 监测项目 */
@Column(name = "subject")
private String subject;
/** 监测项目代码 */
@Column(name = "code")
private String code;
/** 计算公式 */
@Column(name = "gs")
private String gs;
/** 二维码 */
@Column(name = "qrcode")
private String qrcode;
/** 创建时间 */
@Column(name = "create_time")
@CreationTimestamp
private Timestamp createTime;
/** 到期时间 */
@Column(name = "expire")
private Timestamp expire;
/** 更新时间 */
@Column(name = "update_time")
@UpdateTimestamp
private Timestamp updateTime;
/** 工作模式 0手动1自动 */
@Column(name = "workmode")
private String workmode;
/** 在线时间 */
@Column(name = "onlinetime")
private Timestamp onlinetime;
/** 在线 */
@Column(name = "online")
private String online;
/** 运营商 */
@Column(name = "isp")
private String isp;
public void copy(Sensor source){
BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true));
}
}
\ No newline at end of file
package com.gemho.environment.model;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import lombok.Data;
import javax.persistence.*;
import java.io.Serializable;
/**
* @author lhl
* @date 2020-06-19
*/
@Entity
@Data
@Table(name="s_sensor_data")
public class SensorData implements Serializable {
/** 主键 */
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private String id;
/** 设备id */
@Column(name = "deviceId")
private String deviceid;
/** 检测项 */
@Column(name = "item")
private String item;
/** 检测项名 */
@Column(name = "itemStr")
private String itemStr;
/** 时间 */
@Column(name = "dtime")
private String dtime;
/** 数据值 */
@Column(name = "data")
private String data;
/** 信号强度 */
@Column(name = "rssi")
private String rssi;
/** 电量 */
@Column(name = "battery")
private String battery;
/** 备注 */
@Column(name = "nt")
private String nt;
public void copy(SensorData source){
BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true));
}
}
\ No newline at end of file
package com.gemho.environment.model;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import lombok.Data;
import java.io.Serializable;
import java.sql.Timestamp;
/**
* @author 靖小侠
* @date 2020-05-07
*/
@Data
public class SensorDto implements Serializable {
/** 主键 */
/** 防止精度丢失 */
@JsonSerialize(using= ToStringSerializer.class)
private Long id;
/** 所属公司 */
private String company;
/** IMEI码 */
private String imei;
/** 电信编码 */
private String telecomcode;
/** 设备id */
private String deviceid;
/** 监测设备类型 */
private String devicetype;
/** 设备名称 */
private String name;
/** 描述 */
private String nt;
/** 设备类型 0:nb 1:4g */
private String type;
/** 安装位置 */
private String address;
/** 经度 */
private Double jd;
/** 纬度 */
private Double wd;
/** 采集频率 */
private Integer timetrack;
/** 上传频率 */
private Integer timetrack2;
/** 信号强度 */
private String rssi;
/** 电池电量 */
private String battery;
/** 是否有效 */
private String valid;
/** ICCID或卡号 */
private String phonecode;
/** ip */
private String ip;
/** 端口 */
private String port;
/** 监测项目 */
private String subject;
/** 监测项目代码 */
private String code;
/** 计算公式 */
private String gs;
/** 二维码 */
private String qrcode;
/** 到期时间 */
private Timestamp expire;
/** 创建时间 */
private Timestamp createTime;
/** 更新时间 */
private Timestamp updateTime;
/** 工作模式 0手动1自动 */
private String workmode;
/** 在线时间 */
private Timestamp onlinetime;
/** 在线 */
private String online;
/** 运营商 */
private String isp;
}
\ No newline at end of file
package com.gemho.environment.model;
import com.gemho.environment.annotation.Query;
import lombok.Data;
/**
* @author 靖小侠
* @date 2020-05-07
*/
@Data
public class SensorQueryCriteria{
/** 精确 */
@Query
private String imei;
/** 精确 */
@Query
private String deviceid;
/** 模糊 */
@Query(type = Query.Type.INNER_LIKE)
private String name;
}
\ No newline at end of file
package com.gemho.environment.repository;
import com.gemho.environment.model.Devicetype;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
/**
* @author 靖小侠
* @date 2020-05-08
*/
public interface DevicetypeRepository extends JpaRepository<Devicetype, Long>, JpaSpecificationExecutor<Devicetype> {
}
\ No newline at end of file
package com.gemho.environment.repository;
import com.gemho.environment.model.Sensor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
/**
* @author 靖小侠
* @date 2020-05-07
*/
public interface SensorRepository extends JpaRepository<Sensor, Long>, JpaSpecificationExecutor<Sensor> {
Sensor findByImei(String imei);
sun.management.Sensor findByDeviceid(String deviceid);
@Query(value = "select s.* from s_sensor s LEFT JOIN s_user_sensor u ON s.deviceid = u.sensorid where u.userid = ?1 ",
nativeQuery = true)
List<Sensor> findSensorByUserid(Long userid);
@Query(value = "select case WHEN (unix_timestamp()-unix_timestamp(s.onlinetime)) <= ((s.timetrack2)/1000)*2 THEN '在线' ELSE '离线' END online, s.* from s_sensor s left join s_user_sensor sus on sus.sensorid = s.deviceid where sus.userid = ?1",
countQuery = "select count(1) from s_sensor s left join s_user_sensor sus on sus.sensorid = s.deviceid where sus.userid = ?1",
nativeQuery = true)
Page<Sensor> queryAllByUserid(Long userid, Pageable pageable);
@Query(value = "select case WHEN (unix_timestamp()-unix_timestamp(s.onlinetime)) <= ((s.timetrack2)/1000)*2 THEN '在线' ELSE '离线' END online, s.* from s_sensor s left join s_user_sensor sus on sus.sensorid = s.deviceid where sus.userid = ?1 and s.deviceid like ?2",
countQuery = "select count(1) from s_sensor s left join s_user_sensor sus on sus.sensorid = s.deviceid where sus.userid = ?1 and s.deviceid like ?2",
nativeQuery = true)
Page<Sensor> queryAllByUseridAndDeviceid(Long userid, String deviceid, Pageable pageable);
@Query(value = "select case WHEN (unix_timestamp()-unix_timestamp(s.onlinetime)) <= ((s.timetrack2)/1000)*2 THEN '在线' ELSE '离线' END online, s.* from s_sensor s left join s_user_sensor sus on sus.sensorid = s.deviceid where sus.userid = ?1 and s.imei like ?2",
countQuery = "select count(1) from s_sensor s left join s_user_sensor sus on sus.sensorid = s.deviceid where sus.userid = ?1 and s.imei like ?2",
nativeQuery = true)
Page<Sensor> queryAllByUseridAndImei(Long userid, String imei, Pageable pageable);
@Query(value = "select case WHEN (unix_timestamp()-unix_timestamp(s.onlinetime)) <= ((s.timetrack2)/1000)*2 THEN '在线' ELSE '离线' END online, s.* from s_sensor s left join s_user_sensor sus on sus.sensorid = s.deviceid where sus.userid = ?1 and s.name like ?2",
countQuery = "select count(1) from s_sensor s left join s_user_sensor sus on sus.sensorid = s.deviceid where sus.userid = ?1 and s.name like ?2",
nativeQuery = true)
Page<Sensor> queryAllByUseridAndName(Long userid, String name, Pageable pageable);
@Query(value = "select su.* from ( " +
" select s.* from s_sensor s LEFT JOIN s_user_sensor u ON s.deviceid = u.sensorid where u.userid = ?1 " +
") su LEFT JOIN s_sensor_device r on su.deviceid = r.sensorid WHERE r.deviceid = ?2 ",
nativeQuery = true)
List<Sensor> findSensorByUserAndRelay(Long userid, String relayid);
@Query(value = "select count(s.id) AS total FROM s_sensor s INNER JOIN s_user_sensor us ON us.sensorid = s.deviceid where unix_timestamp()-unix_timestamp((s.onlinetime)) <= ((s.timetrack2)/1000)*2 and us.userid = ?1", nativeQuery = true)
int queryOnlineSensorByUser(Long userid);
@Query(value = "select count(s.id) AS total FROM s_sensor s INNER JOIN s_user_sensor us ON us.sensorid = s.deviceid where (unix_timestamp() -unix_timestamp((s.onlinetime)) > ((s.timetrack2)/1000)*2 OR s.onlinetime is NULL) and us.userid = ?1", nativeQuery = true)
int queryNotOnlineSensorByUser(Long userid);
@Query(value = "select count(s.id) AS total FROM s_sensor s where unix_timestamp()-unix_timestamp((s.onlinetime)) <= ((s.timetrack2)/1000)*2 ", nativeQuery = true)
int queryOnlineSensorBySuper();
@Query(value = "select count(s.id) AS total FROM s_sensor s where unix_timestamp()-unix_timestamp((s.onlinetime)) > ((s.timetrack2)/1000)*2 OR s.onlinetime is NULL ", nativeQuery = true)
int queryNotOnlineSensorBySuper();
}
\ No newline at end of file
package com.gemho.environment.service;
import com.gemho.environment.constants.Constants;
import com.gemho.environment.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
@Component
@Slf4j
public class Channelhandler {
@Resource
RedisUtils redisUtil;
public void setDeviceChannel(String deviceId,String channelId) {
/*查询redis是否存在映射关系*/
Object channel = redisUtil.hget(Constants.REDIS_DEVICE_CHANNEL_KEY, deviceId);
if (channel == null) {
log.debug(">>>>>");
//保存设备通道映射
log.debug("redis保存设备通道映射{}",redisUtil.hset(Constants.REDIS_DEVICE_CHANNEL_KEY,deviceId,channelId));
//保存通道设备映射
log.debug("redis保存通道设备映射{}",redisUtil.hset(Constants.REDIS_CHANNEL_DEVICE_KEY,channelId,deviceId));
}
}
public void rmDeviceChannel(String channelId){
//查询通道和设备的映射
String deviceId = redisUtil.hget(Constants.REDIS_CHANNEL_DEVICE_KEY, channelId).toString();
log.debug(deviceId);
if (deviceId != null) {
log.debug("设备Id为{},已断开连接",deviceId);
//查询设备和通道的映射
String device_channel = redisUtil.hget(Constants.REDIS_DEVICE_CHANNEL_KEY, deviceId).toString();
if (device_channel != null) {
//删除设备和通道的映射
redisUtil.hdel(Constants.REDIS_DEVICE_CHANNEL_KEY, deviceId);
}
//删除通道和设备的映射
redisUtil.hdel(Constants.REDIS_CHANNEL_DEVICE_KEY, channelId);
}
}
public String getDeviceIdByChannelId(String channelId) {
String deviceId = redisUtil.hget(Constants.REDIS_CHANNEL_DEVICE_KEY, channelId).toString();
if (deviceId != null) {
return deviceId;
}else {
return null;
}
}
}
package com.gemho.environment.service;
import com.gemho.environment.model.Devicetype;
import com.gemho.environment.model.DevicetypeDto;
import com.gemho.environment.model.DevicetypeQueryCriteria;
import org.springframework.data.domain.Pageable;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;
/**
* @author 靖小侠
* @date 2020-05-08
*/
public interface DevicetypeService {
/**
* 根据ID查询
* @param id ID
* @return DevicetypeDto
*/
DevicetypeDto findById(Long id);
}
package com.gemho.environment.service;
import com.gemho.environment.model.Relay;
import com.gemho.environment.model.RelayDto;
import com.gemho.environment.model.RelayQueryCriteria;
import org.springframework.data.domain.Pageable;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;
/**
* @author 靖小侠
* @date 2020-05-07
*/
public interface RelayService {
/**
* 查询数据分页
* @param criteria 条件
* @param pageable 分页参数
* @return Map<String,Object>
*/
Map<String,Object> queryAll(RelayQueryCriteria criteria, Pageable pageable);
/**
* 查询所有数据不分页
* @param criteria 条件参数
* @return List<RelayDto>
*/
List<RelayDto> queryAll(RelayQueryCriteria criteria);
/**
* 根据ID查询
* @param id ID
* @return RelayDto
*/
RelayDto findById(Long id);
/**
* 创建
* @param resources /
* @return RelayDto
*/
RelayDto create(Relay resources);
/**
* 编辑
* @param resources /
*/
void update(Relay resources);
/**
* 多选删除
* @param ids /
*/
void deleteAll(Long[] ids);
/**
* 导出数据
* @param all 待导出的数据
* @param response /
* @throws IOException /
*/
void download(List<RelayDto> all, HttpServletResponse response) throws IOException;
/**
* 通过imei查询设备
* @param imei
* @return
*/
RelayDto findByImei(String imei);
/**
* 通过deviceid查询设备
* @param deviceid
* @return
*/
RelayDto findByDeviceid(String deviceid);
Map<String,Object> queryAllByUserid(Long userid, RelayQueryCriteria criteria, Pageable pageable);
void unbind(String relayid);
List<RelayDto> queryAllRelayByUseridNoPage(Long userid);
String sendCommand(String relayId, String command);
/**
* 更新设备在线时间
* @param deviceId
*/
public void updateRelayOnlinetime(String deviceId);
/**
* 更新设备工作模式
* @param deviceId
* @param workmode
*/
public void updateRelayWorkMode(String deviceId, String workmode);
Map<String,Object> queryRelayAndSensorByUserid(Long userid, RelayQueryCriteria criteria, Pageable pageable);
List<RelayDto> findRelayByMonitor(Long userid, String id);
int queryOnlineRelayByUser(Long userid);
int queryNotOnlineRelayByUser(Long userid);
int queryOnlineRelayBySuper();
int queryNotOnlineRelayBySuper();
}
\ No newline at end of file
package com.gemho.environment.service;
import com.gemho.environment.model.Sensor;
import com.gemho.environment.model.SensorDto;
import com.gemho.environment.model.SensorQueryCriteria;
import org.springframework.data.domain.Pageable;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;
/**
* @author 靖小侠
* @date 2020-05-07
*/
public interface SensorService {
/**
* 通过deviceid查询设备
* @param deviceid
* @return
*/
SensorDto findByDeviceid(String deviceid);
/**
* 编辑
* @param resources /
*/
void update(Sensor resources);
}
\ No newline at end of file
package com.gemho.environment.service.impl;
import com.gemho.environment.model.Devicetype;
import com.gemho.environment.model.DevicetypeDto;
import com.gemho.environment.repository.DevicetypeRepository;
import com.gemho.environment.service.DevicetypeService;
import com.gemho.environment.service.mapper.DevicetypeMapper;
import com.gemho.environment.utils.ValidationUtil;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* @author 靖小侠
* @date 2020-05-08
*/
@Service
//@CacheConfig(cacheNames = "devicetype")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class DevicetypeServiceImpl implements DevicetypeService {
private final DevicetypeRepository devicetypeRepository;
private final DevicetypeMapper devicetypeMapper;
public DevicetypeServiceImpl(DevicetypeRepository devicetypeRepository, DevicetypeMapper devicetypeMapper) {
this.devicetypeRepository = devicetypeRepository;
this.devicetypeMapper = devicetypeMapper;
}
@Override
//@Cacheable(key = "#p0")
public DevicetypeDto findById(Long id) {
Devicetype devicetype = devicetypeRepository.findById(id).orElseGet(Devicetype::new);
ValidationUtil.isNull(devicetype.getId(),"Devicetype","id",id);
return devicetypeMapper.toDto(devicetype);
}
}
package com.gemho.environment.service.impl;
import cn.hutool.core.util.NumberUtil;
import com.gemho.environment.model.Relay;
import com.gemho.environment.model.RelayDto;
import com.gemho.environment.service.RelayService;
import com.gemho.environment.utils.RedisUtils;
import com.gemho.environment.utils.ValidationUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
/**
* @author 靖小侠
* @date 2020-05-07
*/
@Slf4j
@Service
//@CacheConfig(cacheNames = "relay")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class RelayServiceImpl implements RelayService {
private final RedisUtils redisUtils;
private final RelayRepository relayRepository;
private final RelayMapper relayMapper;
private final UserRelayRepository userRelayRepository;
private final SensorDeviceRepository sensorDeviceRepository;
@Value("${smart.offlineCount}")
private String offlineCount;
public RelayServiceImpl(RedisUtils redisUtils, RelayRepository relayRepository, RelayMapper relayMapper, UserRelayRepository userRelayRepository, SensorDeviceRepository sensorDeviceRepository) {
this.redisUtils = redisUtils;
this.relayRepository = relayRepository;
this.relayMapper = relayMapper;
this.userRelayRepository = userRelayRepository;
this.sensorDeviceRepository = sensorDeviceRepository;
}
@Override
//@Cacheable(key = "#p0")
public RelayDto findById(Long id) {
Relay relay = relayRepository.findById(id).orElseGet(Relay::new);
ValidationUtil.isNull(relay.getId(),"Relay","id",id);
return relayMapper.toDto(relay);
}
@Override
//@CacheEvict(allEntries = true)
@Transactional(rollbackFor = Exception.class)
public RelayDto create(Relay resources) {
// resources.setId(IdUtil.simpleUUID());
return relayMapper.toDto(relayRepository.save(resources));
}
@Override
//@CacheEvict(allEntries = true)
@Transactional(rollbackFor = Exception.class)
public void update(Relay resources) {
Relay relay = relayRepository.findById(resources.getId()).orElseGet(Relay::new);
ValidationUtil.isNull( relay.getId(),"Relay","id",resources.getId());
relay.copy(resources);
relayRepository.save(relay);
}
@Override
//@CacheEvict(allEntries = true)
public void deleteAll(Long[] ids) {
for (Long id : ids) {
relayRepository.deleteById(id);
}
}
@Override
public void download(List<RelayDto> all, HttpServletResponse response) throws IOException {
List<Map<String, Object>> list = new ArrayList<>();
for (RelayDto relay : all) {
Map<String,Object> map = new LinkedHashMap<>();
map.put("所属公司", relay.getCompany());
map.put("IMEI码", relay.getImei());
map.put("电信编码", relay.getTelecomcode());
map.put("设备id", relay.getDeviceid());
map.put("监测设备类型", relay.getDevicetype());
map.put("设备名称", relay.getName());
map.put("描述", relay.getNt());
map.put("设备类型 0:nb 1:4g", relay.getType());
map.put("安装位置", relay.getAddress());
map.put("经度", relay.getJd());
map.put("纬度", relay.getWd());
map.put("信号强度", relay.getRssi());
map.put("电池电量", relay.getBattery());
map.put("是否有效", relay.getValid());
map.put("ICCID或卡号", relay.getPhonecode());
map.put("ip", relay.getIp());
map.put("端口", relay.getPort());
map.put("二维码", relay.getQrcode());
map.put("创建时间", relay.getCreateTime());
map.put("更新时间", relay.getUpdateTime());
map.put("工作模式 0手动1自动", relay.getWorkmode());
map.put("在线时间", relay.getOnlinetime());
map.put("在线", relay.getOnline());
map.put("0: 普通设备 1:控制器 2:无线LED屏幕", relay.getRelay());
list.add(map);
}
FileUtil.downloadExcel(list, response);
}
@Override
public RelayDto findByImei(String imei) {
return relayMapper.toDto(relayRepository.findByImei(imei));
}
@Override
public RelayDto findByDeviceid(String deviceid) {
return relayMapper.toDto(relayRepository.findByDeviceid(deviceid));
}
}
package com.gemho.environment.service.impl;
import com.gemho.environment.model.SensorDto;
import com.gemho.environment.repository.SensorRepository;
import com.gemho.environment.service.SensorService;
import com.gemho.environment.service.mapper.SensorMapper;
import com.gemho.environment.utils.ValidationUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.gemho.environment.model.Sensor;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* @author 靖小侠
* @date 2020-05-07
*/
@Service
//@CacheConfig(cacheNames = "sensor")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class SensorServiceImpl implements SensorService {
private final SensorRepository sensorRepository;
private final SensorMapper sensorMapper;
public SensorServiceImpl(SensorRepository sensorRepository, SensorMapper sensorMapper) {
this.sensorRepository = sensorRepository;
this.sensorMapper = sensorMapper;
}
@Override
public SensorDto findByDeviceid(String deviceid) {
return sensorMapper.toDto(sensorRepository.findByDeviceid(deviceid));
}
@Override
//@CacheEvict(allEntries = true)
@Transactional(rollbackFor = Exception.class)
public void update(Sensor resources) {
Sensor sensor = sensorRepository.findById(resources.getId()).orElseGet(Sensor::new);
ValidationUtil.isNull( sensor.getId(),"Sensor","id",resources.getId());
sensor.copy(resources);
sensorRepository.save(sensor);
}
}
package com.gemho.environment.service.mapper;
import com.gemho.environment.model.Devicetype;
import com.gemho.environment.model.DevicetypeDto;
import com.gemho.environment.utils.BaseMapper;
import org.mapstruct.Mapper;
import org.mapstruct.ReportingPolicy;
/**
* @author 靖小侠
* @date 2020-05-08
*/
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface DevicetypeMapper extends BaseMapper<DevicetypeDto, Devicetype> {
}
\ No newline at end of file
package com.gemho.environment.service.mapper;
import com.gemho.environment.model.SensorDto;
import com.gemho.environment.utils.BaseMapper;
import org.mapstruct.Mapper;
import org.mapstruct.ReportingPolicy;
import sun.management.Sensor;
/**
* @author 靖小侠
* @date 2020-05-07
*/
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface SensorMapper extends BaseMapper<SensorDto, Sensor> {
}
\ No newline at end of file
package com.gemho.environment.utils;
import com.gemho.environment.model.Sensor;
import java.util.List;
/**
* @author Zheng Jie
* @date 2018-11-23
*/
public interface BaseMapper<D, E> {
/**
* DTO转Entity
* @param dto /
* @return /
*/
Sensor toEntity(D dto);
/**
* Entity转DTO
* @param entity /
* @return /
*/
D toDto(E entity);
/**
* DTO集合转Entity集合
* @param dtoList /
* @return /
*/
List <E> toEntity(List<D> dtoList);
/**
* Entity集合转DTO集合
* @param entityList /
* @return /
*/
List <D> toDto(List<E> entityList);
}
package com.gemho.environment.utils;
/**
* @Author: liujing
* @Date: 2019/10/24 16:49
* @Version: 1.0
*/
public class CRC16Util {
static byte[] crc16_tab_h = { (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01, (byte) 0xC0,
(byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1,
(byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0,
(byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0,
(byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40 };
static byte[] crc16_tab_l = { (byte) 0x00, (byte) 0xC0, (byte) 0xC1, (byte) 0x01, (byte) 0xC3, (byte) 0x03, (byte) 0x02, (byte) 0xC2, (byte) 0xC6, (byte) 0x06, (byte) 0x07, (byte) 0xC7, (byte) 0x05, (byte) 0xC5, (byte) 0xC4, (byte) 0x04, (byte) 0xCC, (byte) 0x0C, (byte) 0x0D, (byte) 0xCD, (byte) 0x0F, (byte) 0xCF, (byte) 0xCE, (byte) 0x0E, (byte) 0x0A, (byte) 0xCA, (byte) 0xCB, (byte) 0x0B, (byte) 0xC9, (byte) 0x09, (byte) 0x08, (byte) 0xC8, (byte) 0xD8, (byte) 0x18, (byte) 0x19, (byte) 0xD9, (byte) 0x1B, (byte) 0xDB, (byte) 0xDA, (byte) 0x1A, (byte) 0x1E, (byte) 0xDE, (byte) 0xDF, (byte) 0x1F, (byte) 0xDD, (byte) 0x1D, (byte) 0x1C, (byte) 0xDC, (byte) 0x14, (byte) 0xD4, (byte) 0xD5, (byte) 0x15, (byte) 0xD7, (byte) 0x17, (byte) 0x16, (byte) 0xD6, (byte) 0xD2, (byte) 0x12,
(byte) 0x13, (byte) 0xD3, (byte) 0x11, (byte) 0xD1, (byte) 0xD0, (byte) 0x10, (byte) 0xF0, (byte) 0x30, (byte) 0x31, (byte) 0xF1, (byte) 0x33, (byte) 0xF3, (byte) 0xF2, (byte) 0x32, (byte) 0x36, (byte) 0xF6, (byte) 0xF7, (byte) 0x37, (byte) 0xF5, (byte) 0x35, (byte) 0x34, (byte) 0xF4, (byte) 0x3C, (byte) 0xFC, (byte) 0xFD, (byte) 0x3D, (byte) 0xFF, (byte) 0x3F, (byte) 0x3E, (byte) 0xFE, (byte) 0xFA, (byte) 0x3A, (byte) 0x3B, (byte) 0xFB, (byte) 0x39, (byte) 0xF9, (byte) 0xF8, (byte) 0x38, (byte) 0x28, (byte) 0xE8, (byte) 0xE9, (byte) 0x29, (byte) 0xEB, (byte) 0x2B, (byte) 0x2A, (byte) 0xEA, (byte) 0xEE, (byte) 0x2E, (byte) 0x2F, (byte) 0xEF, (byte) 0x2D, (byte) 0xED, (byte) 0xEC, (byte) 0x2C, (byte) 0xE4, (byte) 0x24, (byte) 0x25, (byte) 0xE5, (byte) 0x27, (byte) 0xE7,
(byte) 0xE6, (byte) 0x26, (byte) 0x22, (byte) 0xE2, (byte) 0xE3, (byte) 0x23, (byte) 0xE1, (byte) 0x21, (byte) 0x20, (byte) 0xE0, (byte) 0xA0, (byte) 0x60, (byte) 0x61, (byte) 0xA1, (byte) 0x63, (byte) 0xA3, (byte) 0xA2, (byte) 0x62, (byte) 0x66, (byte) 0xA6, (byte) 0xA7, (byte) 0x67, (byte) 0xA5, (byte) 0x65, (byte) 0x64, (byte) 0xA4, (byte) 0x6C, (byte) 0xAC, (byte) 0xAD, (byte) 0x6D, (byte) 0xAF, (byte) 0x6F, (byte) 0x6E, (byte) 0xAE, (byte) 0xAA, (byte) 0x6A, (byte) 0x6B, (byte) 0xAB, (byte) 0x69, (byte) 0xA9, (byte) 0xA8, (byte) 0x68, (byte) 0x78, (byte) 0xB8, (byte) 0xB9, (byte) 0x79, (byte) 0xBB, (byte) 0x7B, (byte) 0x7A, (byte) 0xBA, (byte) 0xBE, (byte) 0x7E, (byte) 0x7F, (byte) 0xBF, (byte) 0x7D, (byte) 0xBD, (byte) 0xBC, (byte) 0x7C, (byte) 0xB4, (byte) 0x74,
(byte) 0x75, (byte) 0xB5, (byte) 0x77, (byte) 0xB7, (byte) 0xB6, (byte) 0x76, (byte) 0x72, (byte) 0xB2, (byte) 0xB3, (byte) 0x73, (byte) 0xB1, (byte) 0x71, (byte) 0x70, (byte) 0xB0, (byte) 0x50, (byte) 0x90, (byte) 0x91, (byte) 0x51, (byte) 0x93, (byte) 0x53, (byte) 0x52, (byte) 0x92, (byte) 0x96, (byte) 0x56, (byte) 0x57, (byte) 0x97, (byte) 0x55, (byte) 0x95, (byte) 0x94, (byte) 0x54, (byte) 0x9C, (byte) 0x5C, (byte) 0x5D, (byte) 0x9D, (byte) 0x5F, (byte) 0x9F, (byte) 0x9E, (byte) 0x5E, (byte) 0x5A, (byte) 0x9A, (byte) 0x9B, (byte) 0x5B, (byte) 0x99, (byte) 0x59, (byte) 0x58, (byte) 0x98, (byte) 0x88, (byte) 0x48, (byte) 0x49, (byte) 0x89, (byte) 0x4B, (byte) 0x8B, (byte) 0x8A, (byte) 0x4A, (byte) 0x4E, (byte) 0x8E, (byte) 0x8F, (byte) 0x4F, (byte) 0x8D, (byte) 0x4D,
(byte) 0x4C, (byte) 0x8C, (byte) 0x44, (byte) 0x84, (byte) 0x85, (byte) 0x45, (byte) 0x87, (byte) 0x47, (byte) 0x46, (byte) 0x86, (byte) 0x82, (byte) 0x42, (byte) 0x43, (byte) 0x83, (byte) 0x41, (byte) 0x81, (byte) 0x80, (byte) 0x40 };
/**
* 计算CRC16校验
*
* @param data
* 需要计算的数组
* @return CRC16校验值
*/
public static int calcCrc16(byte[] data) {
return calcCrc16(data, 0, data.length);
}
/**
* 计算CRC16校验
*
* @param data
* 需要计算的数组
* @param offset
* 起始位置
* @param len
* 长度
* @return CRC16校验值
*/
public static int calcCrc16(byte[] data, int offset, int len) {
return calcCrc16(data, offset, len, 0xffff);
}
/**
* 计算CRC16校验
*
* @param data
* 需要计算的数组
* @param offset
* 起始位置
* @param len
* 长度
* @param preval
* 之前的校验值
* @return CRC16校验值
*/
public static int calcCrc16(byte[] data, int offset, int len, int preval) {
int ucCRCHi = (preval & 0xff00) >> 8;
int ucCRCLo = preval & 0x00ff;
int iIndex;
for (int i = 0; i < len; ++i) {
iIndex = (ucCRCLo ^ data[offset + i]) & 0x00ff;
ucCRCLo = ucCRCHi ^ crc16_tab_h[iIndex];
ucCRCHi = crc16_tab_l[iIndex];
}
return ((ucCRCLo & 0x00ff) << 8) | (ucCRCHi & 0x00ff) & 0xffff;
}
}
package com.gemho.environment.utils;
import java.util.HashMap;
import java.util.Map;
public class Constants {
public static final String NETTY_MONITOR_CLIENT_PORT = "7000"; //智慧农业监测设备上传端口
public static final String NETTY_RELAY_CLIENT_PORT = "8011"; //控制器端口
public static final String NETTY_MIST_CLIENT_PORT = "7001"; //烟感报警器(外采设备)
public static final String REDIS_DEVICE_CHANNEL_KEY = "device_channel"; //redis 设备和通道缓存key
public static final String REDIS_CHANNEL_DEVICE_KEY = "channel_device"; //redis 设备和通道缓存key
public static final String REDIS_Smoke_KEY = "Smoke"; //redis 烟感报警key
public static Map<String,String> sendMap = new HashMap<>();
}
/*
* Copyright Notice:
* Copyright 1998-2008, Huawei Technologies Co., Ltd. ALL Rights Reserved.
*
* Warning: This computer software sourcecode is protected by copyright law
* and international treaties. Unauthorized reproduction or distribution
* of this sourcecode, or any portion of it, may result in severe civil and
* criminal penalties, and will be prosecuted to the maximum extent
* possible under the law.
*/
package com.gemho.environment.utils;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.IOException;
public class JsonUtil {
private static ObjectMapper objectMapper;
static {
objectMapper = new ObjectMapper();
// 设置FAIL_ON_EMPTY_BEANS属性,当序列化空对象不要抛异常
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
// 设置FAIL_ON_UNKNOWN_PROPERTIES属性,当JSON字符串中存在Java对象没有的属性,忽略
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
/**
* Convert Object to JsonString
*
* @param jsonObj
* @return
*/
public static String jsonObj2Sting(Object jsonObj) {
String jsonString = null;
try {
jsonString = objectMapper.writeValueAsString(jsonObj);
} catch (IOException e) {
System.out.printf("pasre json Object[{}] to string failed.",jsonString);
}
return jsonString;
}
/**
* Convert JsonString to Simple Object
*
* @param jsonString
* @param cls
* @return
*/
public static <T> T jsonString2SimpleObj(String jsonString, Class<T> cls) {
T jsonObj = null;
try {
jsonObj = objectMapper.readValue(jsonString, cls);
} catch (IOException e) {
System.out.printf("pasre json Object[{}] to string failed.",jsonString);
}
return jsonObj;
}
/**
* Method that will convert object to the ObjectNode.
*
*
* the source data; if null, will return null.
* @return the ObjectNode data after converted.
*
*/
public static <T> ObjectNode convertObject2ObjectNode(T object)
throws Exception {
if (null == object) {
return null;
}
ObjectNode objectNode = null;
if (object instanceof String) {
objectNode = convertJsonStringToObject((String) object,
ObjectNode.class);
} else {
objectNode = convertValue(object, ObjectNode.class);
}
return objectNode;
}
/**
* Method that will convert the json string to destination by the type(cls).
*
* @param jsonString
* the source json string; if null, will return null.
* @param cls
* the destination data type.
* @return
* @throws
*/
public static <T> T convertJsonStringToObject(String jsonString,
Class<T> cls) throws Exception {
if (StringUtil.strIsNullOrEmpty(jsonString)) {
return null;
}
try {
T object = objectMapper.readValue(jsonString, cls);
return object;
} catch (Exception e) {
throw new Exception(e);
}
}
/**
* Method that will convert from given value into instance of given value
* type.
*
* @param fromValue
* @param toValueType
* @return
* @throws JsonException
*/
private static <T> T convertValue(Object fromValue, Class<T> toValueType)
throws Exception {
try {
return objectMapper.convertValue(fromValue, toValueType);
} catch (IllegalArgumentException e) {
throw new Exception(e);
}
}
}
package com.gemho.environment.utils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.*;
import java.util.concurrent.TimeUnit;
/**
* @author /
*/
@Component
@SuppressWarnings({"unchecked","all"})
public class RedisUtils {
private RedisTemplate<Object, Object> redisTemplate;
@Value("${jwt.online-key}")
private String onlineKey;
public RedisUtils(RedisTemplate<Object, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
// =============================common============================
/**
* 指定缓存失效时间
* @param key 键
* @param time 时间(秒)
*/
public boolean expire(String key, long time) {
try {
if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 根据 key 获取过期时间
* @param key 键 不能为null
* @return 时间(秒) 返回0代表为永久有效
*/
public long getExpire(Object key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
/**
* 查找匹配key
* @param pattern key
* @return /
*/
public List<String> scan(String pattern) {
ScanOptions options = ScanOptions.scanOptions().match(pattern).build();
RedisConnectionFactory factory = redisTemplate.getConnectionFactory();
RedisConnection rc = Objects.requireNonNull(factory).getConnection();
Cursor<byte[]> cursor = rc.scan(options);
List<String> result = new ArrayList<>();
while (cursor.hasNext()) {
result.add(new String(cursor.next()));
}
try {
RedisConnectionUtils.releaseConnection(rc, factory);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 分页查询 key
* @param patternKey key
* @param page 页码
* @param size 每页数目
* @return /
*/
public List<String> findKeysForPage(String patternKey, int page, int size) {
ScanOptions options = ScanOptions.scanOptions().match(patternKey).build();
RedisConnectionFactory factory = redisTemplate.getConnectionFactory();
RedisConnection rc = Objects.requireNonNull(factory).getConnection();
Cursor<byte[]> cursor = rc.scan(options);
List<String> result = new ArrayList<>(size);
int tmpIndex = 0;
int fromIndex = page * size;
int toIndex = page * size + size;
while (cursor.hasNext()) {
if (tmpIndex >= fromIndex && tmpIndex < toIndex) {
result.add(new String(cursor.next()));
tmpIndex++;
continue;
}
// 获取到满足条件的数据后,就可以退出了
if(tmpIndex >=toIndex) {
break;
}
tmpIndex++;
cursor.next();
}
try {
RedisConnectionUtils.releaseConnection(rc, factory);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 判断key是否存在
* @param key 键
* @return true 存在 false不存在
*/
public boolean hasKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除缓存
* @param key 可以传一个值 或多个
*/
public void del(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate.delete(key[0]);
} else {
redisTemplate.delete(CollectionUtils.arrayToList(key));
}
}
}
// ============================String=============================
/**
* 普通缓存获取
* @param key 键
* @return 值
*/
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
/**
* 批量获取
* @param keys
* @return
*/
public List<Object> multiGet(List<String> keys) {
Object obj = redisTemplate.opsForValue().multiGet(Collections.singleton(keys));
return null;
}
/**
* 普通缓存放入
* @param key 键
* @param value 值
* @return true成功 false失败
*/
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 普通缓存放入并设置时间
* @param key 键
* @param value 值
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
public boolean set(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 普通缓存放入并设置时间
* @param key 键
* @param value 值
* @param time 时间
* @param timeUnit 类型
* @return true成功 false 失败
*/
public boolean set(String key, Object value, long time, TimeUnit timeUnit) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, timeUnit);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
// ================================Map=================================
/**
* HashGet
* @param key 键 不能为null
* @param item 项 不能为null
* @return 值
*/
public Object hget(String key, String item) {
return redisTemplate.opsForHash().get(key, item);
}
/**
* 获取hashKey对应的所有键值
* @param key 键
* @return 对应的多个键值
*/
public Map<Object, Object> hmget(String key) {
return redisTemplate.opsForHash().entries(key);
}
/**
* HashSet
* @param key 键
* @param map 对应多个键值
* @return true 成功 false 失败
*/
public boolean hmset(String key, Map<String, Object> map) {
try {
redisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* HashSet 并设置时间
* @param key 键
* @param map 对应多个键值
* @param time 时间(秒)
* @return true成功 false失败
*/
public boolean hmset(String key, Map<String, Object> map, long time) {
try {
redisTemplate.opsForHash().putAll(key, map);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一张hash表中放入数据,如果不存在将创建
*
* @param key 键
* @param item 项
* @param value 值
* @return true 成功 false失败
*/
public boolean hset(String key, String item, Object value) {
try {
redisTemplate.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一张hash表中放入数据,如果不存在将创建
*
* @param key 键
* @param item 项
* @param value 值
* @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
* @return true 成功 false失败
*/
public boolean hset(String key, String item, Object value, long time) {
try {
redisTemplate.opsForHash().put(key, item, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除hash表中的值
*
* @param key 键 不能为null
* @param item 项 可以使多个 不能为null
*/
public void hdel(String key, Object... item) {
redisTemplate.opsForHash().delete(key, item);
}
/**
* 判断hash表中是否有该项的值
*
* @param key 键 不能为null
* @param item 项 不能为null
* @return true 存在 false不存在
*/
public boolean hHasKey(String key, String item) {
return redisTemplate.opsForHash().hasKey(key, item);
}
/**
* hash递增 如果不存在,就会创建一个 并把新增后的值返回
*
* @param key 键
* @param item 项
* @param by 要增加几(大于0)
* @return
*/
public double hincr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, by);
}
/**
* hash递减
*
* @param key 键
* @param item 项
* @param by 要减少记(小于0)
* @return
*/
public double hdecr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, -by);
}
// ============================set=============================
/**
* 根据key获取Set中的所有值
*
* @param key 键
* @return
*/
public Set<Object> sGet(String key) {
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 根据value从一个set中查询,是否存在
*
* @param key 键
* @param value 值
* @return true 存在 false不存在
*/
public boolean sHasKey(String key, Object value) {
try {
return redisTemplate.opsForSet().isMember(key, value);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将数据放入set缓存
*
* @param key 键
* @param values 值 可以是多个
* @return 成功个数
*/
public long sSet(String key, Object... values) {
try {
return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 将set数据放入缓存
* @param key 键
* @param time 时间(秒)
* @param values 值 可以是多个
* @return 成功个数
*/
public long sSetAndTime(String key, long time, Object... values) {
try {
Long count = redisTemplate.opsForSet().add(key, values);
if (time > 0) {
expire(key, time);
}
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 获取set缓存的长度
* @param key 键
* @return
*/
public long sGetSetSize(String key) {
try {
return redisTemplate.opsForSet().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 移除值为value的
* @param key 键
* @param values 值 可以是多个
* @return 移除的个数
*/
public long setRemove(String key, Object... values) {
try {
Long count = redisTemplate.opsForSet().remove(key, values);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
// ===============================list=================================
/**
* 获取list缓存的内容
* @param key 键
* @param start 开始
* @param end 结束 0 到 -1代表所有值
* @return
*/
public List<Object> lGet(String key, long start, long end) {
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 获取list缓存的长度
* @param key 键
* @return
*/
public long lGetListSize(String key) {
try {
return redisTemplate.opsForList().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 通过索引 获取list中的值
* @param key 键
* @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
* @return
*/
public Object lGetIndex(String key, long index) {
try {
return redisTemplate.opsForList().index(key, index);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 将list放入缓存
* @param key 键
* @param value 值
* @return
*/
public boolean lSet(String key, Object value) {
try {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public boolean lSet(String key, Object value, long time) {
try {
redisTemplate.opsForList().rightPush(key, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
* @param key 键
* @param value 值
* @return
*/
public boolean lSet(String key, List<Object> value) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public boolean lSet(String key, List<Object> value, long time) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据索引修改list中的某条数据
* @param key 键
* @param index 索引
* @param value 值
* @return /
*/
public boolean lUpdateIndex(String key, long index, Object value) {
try {
redisTemplate.opsForList().set(key, index, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 移除N个值为value
* @param key 键
* @param count 移除多少个
* @param value 值
* @return 移除的个数
*/
public long lRemove(String key, long count, Object value) {
try {
return redisTemplate.opsForList().remove(key, count, value);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}
package com.gemho.environment.utils;
public class RegisterToSensorConstants {
public static final String REGISTER_To_SENSOR = "{\n" +
" \"0000\":\"TMP\",\n" +
" \"0001\":\"TMP2\",\n" +
" \"0002\":\"TMP3\",\n" +
" \"0003\":\"TMP4\",\n" +
" \"0004\":\"TMP5\",\n" +
" \"0005\":\"TMP6\",\n" +
" \"0006\":\"TMP7\",\n" +
" \"0007\":\"TMP8\",\n" +
" \"0008\":\"TMP9\",\n" +
" \"0009\":\"TMP10\",\n" +
" \"0020\":\"HR\",\n" +
" \"0021\":\"HR2\",\n" +
" \"0022\":\"HR3\",\n" +
" \"0023\":\"HR4\",\n" +
" \"0024\":\"HR5\",\n" +
" \"0025\":\"HR6\",\n" +
" \"0026\":\"HR7\",\n" +
" \"0027\":\"HR8\",\n" +
" \"0028\":\"HR9\",\n" +
" \"0029\":\"HR10\",\n" +
" \"0060\":\"ILL\",\n" +
" \"0061\":\"ILL2\",\n" +
" \"0062\":\"ILL3\",\n" +
" \"0063\":\"ILL4\",\n" +
" \"0064\":\"ILL5\",\n" +
" \"0065\":\"ILL6\",\n" +
" \"0066\":\"ILL7\",\n" +
" \"0067\":\"ILL8\",\n" +
" \"0068\":\"ILL9\",\n" +
" \"0069\":\"ILL10\",\n" +
" \"0040\":\"CO2\",\n" +
" \"0041\":\"CO22\",\n" +
" \"0042\":\"CO23\",\n" +
" \"0043\":\"CO24\",\n" +
" \"0044\":\"CO25\",\n" +
" \"0045\":\"CO26\",\n" +
" \"0046\":\"CO27\",\n" +
" \"0047\":\"CO28\",\n" +
" \"0048\":\"CO29\",\n" +
" \"0049\":\"CO210\",\n" +
" \"1000\":\"sTMP\",\n" +
" \"1001\":\"sTMP2\",\n" +
" \"1020\":\"sHR\",\n" +
" \"1021\":\"sHR2\",\n" +
" \"1022\":\"sHR3\",\n" +
" \"1060\":\"sPH\",\n" +
" \"1061\":\"sPH2\",\n" +
" \"1080\":\"NN\",\n" +
" \"10A0\":\"PP\",\n" +
" \"10C0\":\"KK\",\n" +
" \"20E0\":\"RO2\",\n" +
" \"20E1\":\"RO22\",\n" +
" \"2040\":\"wTMP\",\n" +
" \"2041\":\"wTMP2\",\n" +
" \"20C0\":\"NH4\",\n" +
" \"20C1\":\"NH42\",\n" +
" \"2000\":\"wPH\",\n" +
" \"2001\":\"wPH2\",\n" +
" \"20A0\":\"NO3P\",\n" +
" \"20A1\":\"NO3P2\",\n" +
" \"2100\":\"WL\",\n" +
" \"00A0\":\"FS\",\n" +
" \"00C0\":\"FX\",\n" +
" \"0080\":\"PRS\",\n" +
" \"00E0\":\"RV\",\n" +
" \"0100\":\"RD\",\n" +
" \"0120\":\"PM25\",\n" +
" \"0140\":\"PM10\",\n" +
" \"1040\":\"sEC\",\n" +
" \"1041\":\"sEC2\",\n" +
" \"1042\":\"sEC3\",\n" +
" \"1043\":\"sEC4\"\n" +
"}";
}
package com.gemho.environment.utils;
import com.cloopen.rest.sdk.CCPRestSmsSDK;
import java.util.HashMap;
import java.util.Set;
public class SDKTestSendTemplateSMS {
//测试发送短信验证码的方法
// public static void main(String[] args){
// SDKTestSendTemplateSMS sms = new SDKTestSendTemplateSMS();
// sendMsg("15588303201", "396457", new String[]{"213","1"});
//
// }
/**
* 发送短信验证码
* @param phoneNums 需要发送验证码的电话号码列表,逗号分割
* @param model 发送的模版编号
* @param paramArr 模版参数列表
*/
public static void sendMsg(String phoneNums, String model, String[] paramArr) {
HashMap<String, Object> result = null;
//初始化SDK
CCPRestSmsSDK restAPI = new CCPRestSmsSDK();
//******************************注释*********************************************
//*初始化服务器地址和端口 *
//*沙盒环境(用于应用开发调试):restAPI.init("sandboxapp.cloopen.com", "8883");*
//*生产环境(用户应用上线使用):restAPI.init("app.cloopen.com", "8883"); *
//*******************************************************************************
restAPI.init("app.cloopen.com", "8883");
//******************************注释*********************************************
//*初始化主帐号和主帐号令牌,对应官网开发者主账号下的ACCOUNT SID和AUTH TOKEN *
//*ACOUNT SID和AUTH TOKEN在登陆官网后,在“应用-管理控制台”中查看开发者主账号获取*
//*参数顺序:第一个参数是ACOUNT SID,第二个参数是AUTH TOKEN。 *
//*******************************************************************************
restAPI.setAccount("8a216da864da60ef0164ee23641e0b49", "184c69149b634bf9b4ad14496d94484a");
//******************************注释*********************************************
//*初始化应用ID *
//*测试开发可使用“测试Demo”的APP ID,正式上线需要使用自己创建的应用的App ID *
//*应用ID的获取:登陆官网,在“应用-应用列表”,点击应用名称,看应用详情获取APP ID*
//*******************************************************************************
restAPI.setAppId("8a216da86e011fa3016eaad0fa166456");
//******************************注释****************************************************************
//*调用发送模板短信的接口发送短信 *
//*参数顺序说明: *
//*第一个参数:是要发送的手机号码,可以用逗号分隔,一次最多支持100个手机号 *
//*第二个参数:是模板ID,在平台上创建的短信模板的ID值;测试的时候可以使用系统的默认模板,id为1。 *
//*系统默认模板的内容为“【云通讯】您使用的是云通讯短信模板,您的验证码是{1},请于{2}分钟内正确输入”*
//*第三个参数是要替换的内容数组。 *
//**************************************************************************************************
//**************************************举例说明***********************************************************************
//*假设您用测试Demo的APP ID,则需使用默认模板ID 1,发送手机号是13800000000,传入参数为6532和5,则调用方式为 *
//*result = restAPI.sendTemplateSMS("13800000000","1" ,new String[]{"6532","5"}); *
//*则13800000000手机号收到的短信内容是:【云通讯】您使用的是云通讯短信模板,您的验证码是6532,请于5分钟内正确输入 *
//*********************************************************************************************************************
result = restAPI.sendTemplateSMS(phoneNums,model,paramArr);
System.out.println("SDKTestGetSubAccounts result=" + result);
if("000000".equals(result.get("statusCode"))){
//正常返回输出data包体信息(map)
HashMap<String, Object> data = (HashMap<String, Object>) result.get("data");
Set<String> keySet = data.keySet();
for(String key:keySet){
Object object = data.get(key);
System.out.println(key +" = "+object);
}
}else{
//异常返回输出错误码和错误信息
System.out.println("错误码=" + result.get("statusCode") +" 错误信息= "+result.get("statusMsg"));
}
}
}
/*
* Copyright Notice:
* Copyright 1998-2008, Huawei Technologies Co., Ltd. ALL Rights Reserved.
*
* Warning: This computer software sourcecode is protected by copyright law
* and international treaties. Unauthorized reproduction or distribution
* of this sourcecode, or any portion of it, may result in severe civil and
* criminal penalties, and will be prosecuted to the maximum extent
* possible under the law.
*/
package com.gemho.environment.utils;
public class StringUtil {
public static boolean strIsNullOrEmpty(String s) {
return (null == s || s.trim().length() < 1);
}
public static byte[] stringToAscii(String value)
{
char[] chars = value.toCharArray();
byte[] b = new byte[chars.length];
for (int i = 0; i < chars.length; i++) {
b[i] = (byte) chars[i];
}
return b;
}
public static String bytesToHexString(byte[] bArray){
StringBuffer sb = new StringBuffer(bArray.length);
String sTemp;
for (int i = 0; i < bArray.length; i++) {
sTemp = Integer.toHexString(0xFF & bArray[i]);
if (sTemp.length() < 2)
sb.append(0);
sb.append(sTemp.toUpperCase());
}
return sb.toString();
}
/**
* @Title:hexString2Bytes
* @Description:16进制字符串转字节数组
* @param src 16进制字符串
* @return 字节数组
*/
public static byte[] hexString2Bytes(String src) {
int l = src.length() / 2;
byte[] ret = new byte[l];
for (int i = 0; i < l; i++) {
ret[i] = (byte) Integer
.valueOf(src.substring(i * 2, i * 2 + 2), 16).byteValue();
}
return ret;
}
/**
* 十六进制字符串转十进制
*
* @param hex
* 十六进制字符串
* @return 十进制数值
*/
public static int hexStringToAlgorism(String hex) {
hex = hex.toUpperCase();
int max = hex.length();
int result = 0;
for (int i = max; i > 0; i--) {
char c = hex.charAt(i - 1);
int algorism = 0;
if (c >= '0' && c <= '9') {
algorism = c - '0';
} else {
algorism = c - 55;
}
result += Math.pow(16, max - i) * algorism;
}
return result;
}
/**
* 十六进制转字符串
*
* @param hexString
* 十六进制字符串
* @param encodeType
* 编码类型4:Unicode,2:普通编码
* @return 字符串
*/
public static String hexStringToString(String hexString, int encodeType) {
String result = "";
int max = hexString.length() / encodeType;
for (int i = 0; i < max; i++) {
char c = (char) hexStringToAlgorism(hexString.substring(i
* encodeType, (i + 1) * encodeType));
result += c;
}
return result;
}
}
package com.gemho.environment.utils;
import cn.hutool.core.util.ObjectUtil;
import org.hibernate.validator.internal.constraintvalidators.hv.EmailValidator;
/**
* 验证工具
* @author Zheng Jie
* @date 2018-11-23
*/
public class ValidationUtil {
/**
* 验证空
*/
public static void isNull(Object obj, String entity, String parameter , Object value){
if(ObjectUtil.isNull(obj)){
String msg = entity + " 不存在: "+ parameter +" is "+ value;
}
}
/**
* 验证是否为邮箱
*/
public static boolean isEmail(String email) {
return new EmailValidator().isValid(email, null);
}
}
package com.gemho.environment;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class EnvironmentApplicationTests {
@Test
void contextLoads() {
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment