Commit 094884c8 by kenzo

feat: init

parents
.DS_Store
build/
out/
**/httpRequests/
.gradle/
.cache/
.idea*/
~$*
*.iml
*.ipr
*.iws
*.log
dataSources/
.ideaDataSources/
\ No newline at end of file
# risafety-gas-station-service
#### Description
瑞森加油站项目,视频监控分析、IOT预警
#### Software Architecture
Software architecture description
#### Installation
1. xxxx
2. xxxx
3. xxxx
#### Instructions
1. xxxx
2. xxxx
3. xxxx
#### Contribution
1. Fork the repository
2. Create Feat_xxx branch
3. Commit your code
4. Create Pull Request
#### Gitee Feature
1. You can use Readme\_XXX.md to support different languages, such as Readme\_en.md, Readme\_zh.md
2. Gitee blog [blog.gitee.com](https://blog.gitee.com)
3. Explore open source project [https://gitee.com/explore](https://gitee.com/explore)
4. The most valuable open source project [GVP](https://gitee.com/gvp)
5. The manual of Gitee [https://gitee.com/help](https://gitee.com/help)
6. The most popular members [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/)
# risafety-gas-station-service
#### 介绍
瑞森加油站项目,视频监控分析、IOT预警
#### 软件架构
软件架构说明
#### 安装教程
1. xxxx
2. xxxx
3. xxxx
#### 使用说明
1. xxxx
2. xxxx
3. xxxx
#### 参与贡献
1. Fork 本仓库
2. 新建 Feat_xxx 分支
3. 提交代码
4. 新建 Pull Request
#### 特技
1. 使用 Readme\_XXX.md 来支持不同的语言,例如 Readme\_en.md, Readme\_zh.md
2. Gitee 官方博客 [blog.gitee.com](https://blog.gitee.com)
3. 你可以 [https://gitee.com/explore](https://gitee.com/explore) 这个地址来了解 Gitee 上的优秀开源项目
4. [GVP](https://gitee.com/gvp) 全称是 Gitee 最有价值开源项目,是综合评定出的优秀开源项目
5. Gitee 官方提供的使用手册 [https://gitee.com/help](https://gitee.com/help)
6. Gitee 封面人物是一档用来展示 Gitee 会员风采的栏目 [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/)
plugins {
id 'base'
id 'idea'
id 'org.springframework.boot' version '2.2.9.RELEASE'
id 'io.spring.dependency-management' version '1.0.9.RELEASE'
}
group 'com.risensafe'
version '1.0-SNAPSHOT'
apply plugin: 'java'
apply plugin: 'java-library'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
apply plugin: 'idea'
apply from: 'libraries.gradle'
sourceCompatibility = "11"
targetCompatibility = "11"
[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'
repositories {
maven { url "https://maven.aliyun.com/nexus/content/groups/public/" }
mavenCentral()
jcenter()
maven { url "https://raw.githubusercontent.com/xingePush/maven-repository/release/" }
maven { url "http://mvn.gt.igexin.com/nexus/content/repositories/releases/" }
maven {
url "https://nexus.risafety.com/repository/maven-releases/"
credentials {
username "public"
password "XyOVEWDunNExsHEd"
}
}
}
jar {
// excludes = excludedFiles(sourceSets.main.allSource.files)
}
dependencies {
implementation(
libraries.sb_web,
libraries.sb_jdbc,
libraries.sb_redis,
libraries.sb_websocket,
libraries.jackson_databind,
libraries.jackson_dataformat_xml,
libraries.hibernate_validator,
libraries.retrofit,
libraries.retrofit_jackson,
libraries.guava,
libraries.commons_pool,
libraries.commons_lang,
libraries.springfox_swagger2,
libraries.springfox_swagger2_ui,
libraries.aly_core,
libraries.open_cv,
libraries.java_cv,
libraries.java_cv_platform,
libraries.sb_quartz,
libraries.quartz,
libraries.commons_net,
libraries.aly_core,
libraries.aly_oss,
libraries.hikvision_jna,
libraries.hikvision_examples,
libraries.mapstruct,
libraries.oshi_core,
'commons-fileupload:commons-fileupload:1.3.2',
'com.alibaba:fastjson:1.2.78',
"org.aspectj:aspectjweaver:1.9.6",
libraries.integration_mqtt,
libraries.integration_stream,
"org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.5",
)
implementation(libraries.baidu_api){
exclude group:'org.slf4j',module:'slf4j-simple'
}
runtimeOnly(
libraries.mysql,
)
testImplementation(
libraries.sb_test,
)
}
test {
useJUnitPlatform()
}
//configurations {
// all*.exclude group: "org.bytedeco", module: 'leptonica'
//}
//gradle.projectsEvaluated {
// tasks.withType(JavaCompile) {
// options.compilerArgs << "-Xlint:all"
// }
//}
def excludedFiles(Collection<File> files) {
List<String> classes = new ArrayList<>()
files.each { file ->
if (file.isDirectory()) {
excludedFiles(Arrays.asList(file.listFiles()))
} else {
if (file.text.contains("@YourAnnotation") && file.text.contains("import foo.bar.YourAnnotation")) {
classes += getClassName(file.absolutePath)
}
}
}
return classes
}
\ No newline at end of file
###
POST http://localhost:8689/parking/add/enter
Content-Type: application/json
{
"boutNumber": 12,
"carNo": "京N6PQ65",
"enterTime": "2021-12-13 16:15:01",
"enterGateName": "入口1"
}
###
###
GET http://localhost:8689/weather/info
Accept: application/json
###
GET http://localhost:8689/weather/city
Accept: application/json
###
GET http://localhost:8689/test
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed 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.
#
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
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
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
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
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
exec "$JAVACMD" "$@"
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem 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, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
<?xml version="1.0" encoding="GB2312"?>
<SdkLocal>
<SdkLog>
<logLevel>3</logLevel><!--req, 1-ERROR, 2-DEBUG, 3-INFO-->
<logDirectory>./SDKLOG/</logDirectory><!--the end of the string must be '/'-->
<autoDelete>true</autoDelete><!--true: There are less than 10 files in the directory, it will be auto deleted by sdk when the files are more than 10; false: No upper limit to the number of log files-->
</SdkLog>
<HeartbeatCfg>
<Interval>120</Interval> <!-- 心跳时间间隔,单位秒,等于0,使用默认值120s,取值范围为[30, 120] 小于30s,间隔为30s,大于120s,间隔为120s-->
<Count>1</Count> <!-- 触发异常回调需要心跳交互异常的次数,等于0,使用默认值1次-->
</HeartbeatCfg>
</SdkLocal>
\ No newline at end of file
The dll in this directoryiconv.dll,libxml2.dll,zlib1.dll,calib.dllonly used in ClientDemo.
\ No newline at end of file
ext.versions = [
jackson : '2.10.1',
retrofit: '2.7.0',
protobuf: '3.11.1',
grpc : '1.26.0',
devh : '2.6.2.RELEASE',
sba : '2.2.1',
zxing : '3.4.0',
activiti: '7.0.0.GA',
]
ext.libraries = [
sb_core : "org.springframework.boot:spring-boot-starter",
sb_websocket : "org.springframework.boot:spring-boot-starter-websocket",
sb_web : "org.springframework.boot:spring-boot-starter-web",
sb_jdbctemplate : "org.springframework.boot:spring-boot-starter-jdbc",
sb_jdbc : "org.springframework.boot:spring-boot-starter-data-jdbc",
sb_redis : "org.springframework.boot:spring-boot-starter-data-redis",
sb_quartz : "org.springframework.boot:spring-boot-starter-quartz",
sb_test : "org.springframework.boot:spring-boot-starter-test",
sb_grpc_server : "net.devh:grpc-server-spring-boot-starter:${versions.devh}",
sb_grpc_client : "net.devh:grpc-client-spring-boot-starter:${versions.devh}",
spring_statemachine : "org.springframework.statemachine:spring-statemachine-core:2.2.0.RELEASE",
spring_aop : "org.springframework:spring-aop:5.3.0",
mysql : "mysql:mysql-connector-java",
protobuf : "com.google.protobuf:protobuf-java:${versions.protobuf}",
grpc_pb : "io.grpc:grpc-protobuf:${versions.grpc}",
grpc_stub : "io.grpc:grpc-stub:${versions.grpc}",
grpc_netty : "io.grpc:grpc-netty:${versions.grpc}",
grpc_alts : "io.grpc:grpc-alts:${versions.grpc}",
grpc_services : "io.grpc:grpc-services:${versions.grpc}",
sba_server : "de.codecentric:spring-boot-admin-starter-server:${versions.sba}",
sba_client : "de.codecentric:spring-boot-admin-starter-client:${versions.sba}",
guava : "com.google.guava:guava:28.2-jre",
commons_lang : "org.apache.commons:commons-lang3:3.9",
commons_pool : "org.apache.commons:commons-pool2:2.8.1",
commons_net : "commons-net:commons-net:3.8.0",
jackson_core : "com.fasterxml.jackson.core:jackson-core:${versions.jackson}",
jackson_databind : "com.fasterxml.jackson.core:jackson-databind:${versions.jackson}",
jackson_jsr310 : "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:${versions.jackson}",
jackson_dataformat_xml: "com.fasterxml.jackson.dataformat:jackson-dataformat-xml:${versions.jackson}",
retrofit : "com.squareup.retrofit2:retrofit:${versions.retrofit}",
retrofit_jackson : "com.squareup.retrofit2:converter-jackson:${versions.retrofit}",
quartz : "org.quartz-scheduler:quartz:2.3.2",
hibernate_validator : 'org.hibernate.validator:hibernate-validator:6.1.0.Final',
aly_core : "com.aliyun:aliyun-java-sdk-core:4.4.8",
aly_oss : "com.aliyun.oss:aliyun-sdk-oss:3.8.0",
xinge : "com.github.xingePush:xinge:1.2.1",
apache_poi : "org.apache.poi:poi:4.1.1",
apache_poi_ooxml : "org.apache.poi:poi-ooxml:4.1.1:",
alipay : "com.alipay.sdk:alipay-sdk-java:4.10.38.ALL",
httpcomponents : "org.apache.httpcomponents:httpclient:4.5.3",
easyexcel : "com.alibaba:easyexcel:2.1.6",
bcpkix_jdk15on : "org.bouncycastle:bcpkix-jdk15on:1.49",
bcprov_jdk15on : "org.bouncycastle:bcprov-jdk15on:1.49",
itextpdf : "com.itextpdf:itextpdf:5.5.13",
itext_asian : "com.itextpdf:itext-asian:5.2.0",
zxing_core : "com.google.zxing:core:${versions.zxing}",
zxing_javase : "com.google.zxing:javase:${versions.zxing}",
activiti_engine : "org.activiti:activiti-engine:${versions.activiti}",
activiti_spring : "org.activiti:activiti-spring:${versions.activiti}",
activiti_bpmn_model : "org.activiti:activiti-bpmn-model:${versions.activiti}",
activiti_sb : "org.activiti:activiti-spring-boot-starter:${versions.activiti}",
tess4j : "net.sourceforge.tess4j:tess4j:4.5.3",
htmlparser : "org.htmlparser:htmlparser:2.1",
jsoup : "org.jsoup:jsoup:1.13.1",
aspectjweaver : "org.aspectj:aspectjweaver:1.9.6",
java_ws : "javax.xml.ws:jaxws-api:2.3.1",
java_jws : "javax.jws:javax.jws-api:1.1",
baidu_api : "com.baidu.aip:java-sdk:4.15.1",
activiti_bpmn_converter:"org.activiti:activiti-bpmn-converter:${versions.activiti}",
activiti_json_converter:"org.activiti:activiti-json-converter:${versions.activiti}",
pinyin4j : "com.belerweb:pinyin4j:2.5.1",
bcprov : "org.bouncycastle:bcprov-jdk15:1.46",
commons_codec : "commons-codec:commons-codec:1.15",
json : "org.json:json:20201115",
influxdb : "org.influxdb:influxdb-java:2.5",
aws_sdk : "com.amazonaws:aws-java-sdk-s3:1.11.926",
mapstruct : "org.mapstruct:mapstruct:1.4.2.Final",
oshi_core : "com.github.oshi:oshi-core-java11:5.8.5",
springfox_swagger2 : "io.springfox:springfox-swagger2:3.0.0",
springfox_swagger2_ui : "io.springfox:springfox-swagger-ui:3.0.0",
// 天威私有包
tca_javaCertAPI : "com.itrus:cert-api:3.0.1",
tca_crypto : "com.itrus:basic-crypto:1.9",
tca_core : "com.itrus:top-core:1.9",
tca_eas : "com.itrus:top-esa:3.6.0",
tca_security : "com.itrus:top-security:1.9",
open_cv : "com.opencv:opencv:V4.5.1",
java_cv_platform : "org.bytedeco:javacv-platform:1.5.1",
java_cv : "org.bytedeco:javacv:1.5.1",
//海康私自有包
hikvision_jna : "com.hikvision:jna:v1.1",
hikvision_examples : "com.hikvision:examples:v1.1",
//mqtt
integration_stream : "org.springframework.integration:spring-integration-stream:5.4.2",
integration_mqtt : "org.springframework.integration:spring-integration-mqtt:5.4.2",
]
rootProject.name = 'risafety-gas-station-service'
package com.risensafe.gas;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
@EnableAsync
public class GasStationApp {
public static void main(String[] args) {
SpringApplication.run(GasStationApp.class, args);
}
}
package com.risensafe.gas;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.risensafe.gas.iot.IotResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Random;
/**
* @author kenzo
* @create 2021-02-27 10:44
*/
@RestController
public class IotApi {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@GetMapping("/monitor/api/getSensorInDis")
public IotResult get() {
//return iotIntelFile();
return iotIntelRandom();
}
@Value("${iot.fg-json-url}")
private String fgJsonUrl;
private IotResult iotIntelFile() {
InputStreamReader inputStreamReader = null;
BufferedReader br = null;
String json = "";
try {
URL url = new URL(fgJsonUrl);
HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
urlCon.setConnectTimeout(30000);
urlCon.setReadTimeout(30000);
inputStreamReader = new InputStreamReader(urlCon.getInputStream(), StandardCharsets.UTF_8);
br = new BufferedReader(inputStreamReader);
String read;
while ((read = br.readLine()) != null) {
json = json + read;
}
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(json, IotResult.class);
} catch (Exception e) {
logger.error("{}", e.getMessage());
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStreamReader != null) {
try {
inputStreamReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
private IotResult iotIntelRandom() {
//String warnJson = "{\"code\":\"ok\",\"data\":[{\"disName\":\"加油区\",\"sortCode\":0,\"device\":[{\"port\":10000,\"ip\":\"192.168.1.232\",\"deviceModel\":\"可燃气体检v1\",\"sensor\":[{\"isAlert\":false,\"realValue\":\"{\\\"a1\\\":\\\"1.0%LEL\\\"}\",\"sensorName\":\"可燃气体2\",\"alertSystem\":false,\"alertValue\":\"\",\"sensorId\":\"1788d3ac-9be0-41c0-a3f5-7eba01dae1ec\"},{\"isAlert\":true,\"realValue\":\"{\\\"a1\\\":\\\"42.0%LEL\\\"}\",\"sensorName\":\"可燃气体1\",\"alertSystem\":false,\"alertValue\":\"浓度数据:42.0%LEL;\",\"sensorId\":\"8f0dd1d7-1564-4230-b6a1-429ce590aea9\"}],\"deviceName\":\"可燃气体检测器\"},{\"port\":10000,\"ip\":\"192.168.1.232\",\"deviceModel\":\"TH_485\",\"sensor\":[{\"isAlert\":false,\"realValue\":\"{\\\"hum\\\":\\\"31.6%RH\\\",\\\"temp\\\":\\\"21.2℃\\\"}\",\"sensorName\":\"温湿度1\",\"alertSystem\":false,\"alertValue\":\"\",\"sensorId\":\"52c0f586-e141-4332-9fdf-0e378802d5d8\"},{\"isAlert\":false,\"realValue\":\"{\\\"hum\\\":\\\"33.9%RH\\\",\\\"temp\\\":\\\"21.5℃\\\"}\",\"sensorName\":\"温湿度2\",\"alertSystem\":false,\"alertValue\":\"\",\"sensorId\":\"a7e07ff5-85ac-46dc-a510-0be19e09438e\"}],\"deviceName\":\"温湿度\"},{\"port\":10000,\"ip\":\"192.168.1.232\",\"deviceModel\":\"JYDAM204_DI2\",\"sensor\":[{\"isAlert\":false,\"realValue\":\"{\\\"state\\\":\\\"正常\\\"}\",\"sensorName\":\"烟雾2\",\"alertSystem\":false,\"alertValue\":\"\",\"sensorId\":\"986b4424-e738-4451-b351-fb18b30056a9\"}],\"deviceName\":\"烟雾2\"},{\"port\":10000,\"ip\":\"192.168.1.232\",\"deviceModel\":\"JYDAM204_DI1\",\"sensor\":[{\"isAlert\":false,\"realValue\":\"{\\\"state\\\":\\\"正常\\\"}\",\"sensorName\":\"烟雾1\",\"alertSystem\":false,\"alertValue\":\"\",\"sensorId\":\"ee8720cb-4a56-473a-9b1b-1aa153be37df\"}],\"deviceName\":\"烟雾1\"}]}]}";
String normalJson = "{\"code\":\"ok\",\"data\":[{\"disName\":\"加油区\",\"sortCode\":0,\"device\":[{\"port\":10000,\"ip\":\"192.168.1.232\",\"deviceModel\":\"可燃气体检v1\",\"sensor\":[{\"isAlert\":false,\"realValue\":\"{\\\"a1\\\":\\\"1.0%LEL\\\"}\",\"sensorName\":\"可燃气体2\",\"alertSystem\":false,\"alertValue\":\"\",\"sensorId\":\"1788d3ac-9be0-41c0-a3f5-7eba01dae1ec\"},{\"isAlert\":false,\"realValue\":\"{\\\"a1\\\":\\\"0.0%LEL\\\"}\",\"sensorName\":\"可燃气体1\",\"alertSystem\":false,\"alertValue\":\"\",\"sensorId\":\"8f0dd1d7-1564-4230-b6a1-429ce590aea9\"}],\"deviceName\":\"可燃气体检测器\"},{\"port\":10000,\"ip\":\"192.168.1.232\",\"deviceModel\":\"TH_485\",\"sensor\":[{\"isAlert\":false,\"realValue\":\"{\\\"hum\\\":\\\"31.6%RH\\\",\\\"temp\\\":\\\"21.2℃\\\"}\",\"sensorName\":\"温湿度1\",\"alertSystem\":false,\"alertValue\":\"\",\"sensorId\":\"52c0f586-e141-4332-9fdf-0e378802d5d8\"},{\"isAlert\":false,\"realValue\":\"{\\\"hum\\\":\\\"33.9%RH\\\",\\\"temp\\\":\\\"21.5℃\\\"}\",\"sensorName\":\"温湿度2\",\"alertSystem\":false,\"alertValue\":\"\",\"sensorId\":\"a7e07ff5-85ac-46dc-a510-0be19e09438e\"}],\"deviceName\":\"温湿度\"},{\"port\":10000,\"ip\":\"192.168.1.232\",\"deviceModel\":\"JYDAM204_DI2\",\"sensor\":[{\"isAlert\":false,\"realValue\":\"{\\\"state\\\":\\\"正常\\\"}\",\"sensorName\":\"烟雾2\",\"alertSystem\":false,\"alertValue\":\"\",\"sensorId\":\"986b4424-e738-4451-b351-fb18b30056a9\"}],\"deviceName\":\"烟雾2\"},{\"port\":10000,\"ip\":\"192.168.1.232\",\"deviceModel\":\"JYDAM204_DI1\",\"sensor\":[{\"isAlert\":false,\"realValue\":\"{\\\"state\\\":\\\"正常\\\"}\",\"sensorName\":\"烟雾1\",\"alertSystem\":false,\"alertValue\":\"\",\"sensorId\":\"ee8720cb-4a56-473a-9b1b-1aa153be37df\"}],\"deviceName\":\"烟雾1\"}]}]}";
ObjectMapper objectMapper = new ObjectMapper();
IotResult iotResult = null;
try {
ArrayList<String> list = Lists.newArrayList(normalJson);
int index = new Random().nextInt(1);
iotResult = objectMapper.readValue(list.get(index), IotResult.class);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return iotResult;
}
}
package com.risensafe.gas;
import com.risensafe.gas.service.AppTokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
/**
* 项目启动后自动加载 appId,appSecret 到 缓存
*
* @author kenzo
* @create 2021-12-09 11:45
*/
@Component
public class LoadRisenTokenApplicationListener implements ApplicationListener<ContextRefreshedEvent> {
private static final Logger LOG = LoggerFactory.getLogger(LoadRisenTokenApplicationListener.class);
private final AppTokenService appTokenService;
public LoadRisenTokenApplicationListener(AppTokenService appTokenService) {
this.appTokenService = appTokenService;
}
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
LOG.info("Starting load risenToken now");
appTokenService.initCacheToken();
}
}
package com.risensafe.gas;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.TimeZone;
@Configuration
public class LocalDateTimeConfiguration {
@Bean
public Jackson2ObjectMapperBuilderCustomizer jacksonCustomizer() {
return jacksonObjectMapperBuilder -> {
jacksonObjectMapperBuilder.serializationInclusion(JsonInclude.Include.NON_NULL);
jacksonObjectMapperBuilder.featuresToEnable(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN);
jacksonObjectMapperBuilder.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
jacksonObjectMapperBuilder.featuresToDisable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
jacksonObjectMapperBuilder.featuresToDisable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
jacksonObjectMapperBuilder.timeZone(TimeZone.getTimeZone("GMT+8"));
jacksonObjectMapperBuilder.modulesToInstall(new JavaTimeModule());
};
}
}
package com.risensafe.gas;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.risensafe.gas.config.UserConfigProperties;
import com.risensafe.gas.dto.MonitorSensors;
import com.risensafe.gas.dto.ProtocolAnalysis;
import com.risensafe.gas.dto.SocketEntity;
import com.risensafe.gas.utils.ApiResult;
import com.risensafe.gas.utils.ProtocolAnalysisUtil;
import com.risensafe.gas.utils.ProtocolUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
@RestController
public class SocketTest {
final static String PATH = "/socket-test";
boolean deviceIsAlert = false;
boolean isAlertRule = false;
private static Map<String, SocketEntity> tcpSocket = new HashMap();
public static Map<String, SocketEntity> getTcpSocket(){
return tcpSocket;
}
private final UserConfigProperties userConfigProperties;
public SocketTest(UserConfigProperties userConfigProperties) {
this.userConfigProperties = userConfigProperties;
}
@PostMapping(PATH)
public ApiResult cross(){
StringBuilder alertRule = new StringBuilder();
Map<String, Object> realValue = new HashMap<>();
String ip=userConfigProperties.getIotIp();
int port=userConfigProperties.getIotPort();
// String proContent="*,03,00,00,00,02";// 溫度
String proContent="*,03,00,00,00,01"; //可燃气体
if (tcpSocket.get(ip + port) == null) {
try{
Socket socket = new Socket();
try{
SocketAddress address = new InetSocketAddress(ip, port);
socket.connect(address, 1000);
DataOutputStream pw = new DataOutputStream(socket.getOutputStream());
SocketEntity socketEntity = new SocketEntity();
socketEntity.setSocket(socket);
socketEntity.setDataOutputStream(pw);
tcpSocket.put(ip + port, socketEntity);
this.deviceIsAlert = false;
}catch (Exception e1){
this.tcpClose(ip, port);
this.deviceIsAlert = true;
}
}catch (Exception e){
this.tcpClose(ip, port);
this.deviceIsAlert = true;
}
}
byte[] sendData= ProtocolUtil.getModbusData(proContent.replace("*", String.format("%x", new Object[] { 3 })));
long sleepSocket= 100L;
Map<String, Object> map = this.tcpSendData(ip,port,sendData,sleepSocket);
List<ProtocolAnalysis> list = Lists.newArrayList();
ProtocolAnalysis protocolAnalysis = new ProtocolAnalysis();
// protocolAnalysis.setAnalysisType(5);
// protocolAnalysis.setHighLow(0);
// protocolAnalysis.setArrayNumber(4);
// protocolAnalysis.setArrayLength(2);
// protocolAnalysis.setAnalysisRule(11);
// protocolAnalysis.setAnalysisCal("");
// protocolAnalysis.setAnalysisUnit("℃");
// protocolAnalysis.setUpperAlertGrade(0);
// protocolAnalysis.setKeepFigures(2);
// protocolAnalysis.setArrayJson("temp");
// protocolAnalysis.setAnalysisName("温度");
// protocolAnalysis.setAlertCondition("{\"upper\":50,\"lower\":10}");
// 溫度
// =================================================================================
//可燃气体
protocolAnalysis.setAnalysisType(1);
protocolAnalysis.setHighLow(0);
protocolAnalysis.setArrayNumber(4);
protocolAnalysis.setArrayLength(2);
protocolAnalysis.setAnalysisRule(1);
protocolAnalysis.setAnalysisCal("1");
protocolAnalysis.setAnalysisUnit("");
protocolAnalysis.setUpperAlertGrade(1);
protocolAnalysis.setKeepFigures(1);
protocolAnalysis.setArrayJson("H");
protocolAnalysis.setAnalysisName("浓度");
protocolAnalysis.setAlertCondition("{\"upper\":100,\"lower\":0}");
protocolAnalysis.setIsStartCondition(true);
list.add(protocolAnalysis);
MonitorSensors monitorSensors = new MonitorSensors();
int[] datas = (int[])map.get("buf");
Map<String,Object> iotMap = Maps.newHashMap();
iotMap.put("upper",userConfigProperties.getIotUpper());
iotMap.put("lower",userConfigProperties.getIotLower());
String iotMapString = JSONObject.toJSONString(iotMap);
Map<String, Object> map1 = ProtocolAnalysisUtil.analysisData(datas, list, monitorSensors,iotMapString);
if (((Boolean)map1.get("isAlertRule")).booleanValue()) {
isAlertRule = true;
alertRule.append((String)map1.get("alertRule"));
}
map1.remove("alertRule");
map1.remove("isAlertRule");
realValue.putAll(map1);
return ApiResult.okWithData(realValue);
}
public Map<String, Object> tcpSendData(String ip, int port, byte[] sendData, long sleepSocket){
try{
SocketEntity socketEntity = (SocketEntity)tcpSocket.get(ip.replaceAll(" ", "") + port);
synchronized (socketEntity){
Map<String, Object> map = new HashMap<>();
Socket socket = socketEntity.getSocket();
DataOutputStream pw = socketEntity.getDataOutputStream();
pw.write(sendData);
InputStream input = socket.getInputStream();
int count = input.available();
int a = 0;
while ((count == 0) && (a < 3)){
try{
Thread.sleep(sleepSocket);
}catch (Exception e){
a = 3;
}
a++;
count = input.available();
}
if (count > 0){
byte[] bufs = new byte[1024];
int size = input.read(bufs, 0, bufs.length);
int[] buf = ProtocolUtil.bytIntArray(bufs, size);
map.put("size", size);
map.put("buf", buf);
}
tcpClose(ip, port);
return map;
}
}catch (Exception e){
tcpClose(ip, port);
}
return null;
}
public void tcpClose(String ip, int port){
try{
SocketEntity socketEntity = (SocketEntity)tcpSocket.get(ip.replaceAll(" ", "") + port);
if (socketEntity == null) {
return;
}
tcpSocket.remove(ip.replaceAll(" ", "") + port);
Socket socket = socketEntity.getSocket();
DataOutputStream pw = socketEntity.getDataOutputStream();
pw.close();
socket.close();
}catch (Exception localException) {
localException.printStackTrace();
}
}
}
package com.risensafe.gas;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title("rui sen gas station api document")
.version("1.0")
.description("this is web api.")
.build();
}
}
package com.risensafe.gas;
import java.util.Collections;
public class Test {
public static void main(String[] args) {
}
}
package com.risensafe.gas;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.risensafe.gas.config.UserConfigProperties;
import com.risensafe.gas.dto.FacilityDto;
import com.risensafe.gas.dto.ListFacilityResponse;
import com.risensafe.gas.service.*;
import com.risensafe.gas.service.ai.ImageUpdateResponse;
import com.risensafe.gas.service.ai.ImageUploadInterface;
import com.risensafe.gas.utils.TimeHelper;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import org.apache.commons.lang3.SystemUtils;
import org.opencv.core.Core;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;
import javax.annotation.PostConstruct;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
@RestController(TestCamera.PATH)
public class TestCamera extends RemoteService {
final static String PATH = "/test-camera";
private final FacilityService facilityService;
private final ToDashboardWebSocket webSocket;
private final DictionaryService dictionaryService;
private final AlarmRecordService alarmRecordService;
private final UserConfigProperties userConfigProperties;
private final SmokingService smokingService;
private final EscapeRouteService escapeRouteService;
public TestCamera(FacilityService facilityService,
ToDashboardWebSocket webSocket,
DictionaryService dictionaryService,
AlarmRecordService alarmRecordService,
UserConfigProperties userConfigProperties,
SmokingService smokingService, EscapeRouteService escapeRouteService) {
this.facilityService = facilityService;
this.webSocket = webSocket;
this.dictionaryService = dictionaryService;
this.alarmRecordService = alarmRecordService;
this.userConfigProperties = userConfigProperties;
this.smokingService = smokingService;
this.escapeRouteService = escapeRouteService;
}
private ImageUploadInterface imageUploadInterface;
@PostConstruct
public void init() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(userConfigProperties.getUrl())
.addConverterFactory(JacksonConverterFactory.create())
.build();
this.imageUploadInterface = retrofit.create(ImageUploadInterface.class);
}
protected final ObjectMapper objectMapper = new ObjectMapper();
final static String FOLDER_PATH = System.getProperty("java.io.tmpdir");
private static final int POLYGON_MIN_SIZE = 3;
private static class CameraImage {
private String id;
private String image;
public CameraImage(String id, String image) {
this.id = id;
this.image = image;
}
}
@GetMapping(PATH)
public void process() throws Exception {
final ExecutorService exec = Executors.newCachedThreadPool();
final String date = TimeHelper.formatDate(LocalDateTime.now());
Path dirPath = Paths.get(userConfigProperties.getImgPath(), "ai-img", date);
File dir = dirPath.toFile();
if (!dir.exists()) {
boolean created = dir.mkdirs();
logger.debug("{},{}", dir.getPath(), created);
}
//临时文件目录
Path tmpPath = Paths.get(FOLDER_PATH, date);
File tempFile = tmpPath.toFile();
if (!tempFile.exists()) {
boolean created = tempFile.mkdir();
logger.debug("{},{}", dir.getPath(), created);
}
Map<String, String> map = new HashMap<>();
if (SystemUtils.IS_OS_WINDOWS) {
logger.info("================system is windows================");
System.load(userConfigProperties.getJavaDll());
System.load(userConfigProperties.getFfmpegDll());
} else if (SystemUtils.IS_OS_LINUX) {
logger.info("================system is linux================");
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
}
FacilityDto dto = new FacilityDto();
dto.setFacilityType(1);
ListFacilityResponse response = facilityService.listFacility(1, 100, dto);
// String rtsp = "rtsp://admin:abcd@1234@192.168.1.63:554/h264/ch1/sub/av_stream";
// String rtsp = "rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mov";
long start = System.currentTimeMillis();
List<File> files = Lists.newArrayList();
// for (FacilityDto s : response.getDtoList()) {
// if(s.getFacilityType() == 1){
// String rtsp = "rtsp://"+s.getAccessAccount()+":"+s.getPassword()+"@"+s.getIpAddress()+":554/h264/ch1/sub/av_stream";
//
// String cameraImg = alarmRecordService.getCameraImgMap(tempPath,rtsp);
// logger.info("cameraImg 地址:{}",cameraImg);
// map.put(s.getSerial(),cameraImg);
// files.add(new File(cameraImg));
// }
// }
// List<Future<CameraImage>> futures = Lists.newArrayListWithCapacity(response.getDtoList().size());
// for (FacilityDto s : response.getDtoList()) {
// if (s.getFacilityType() == 1) {
// Future<CameraImage> future = exec.submit(() -> {
// String rtsp = String.format("rtsp://%s:%s@%s:554/h264/ch1/sub/av_stream",
// s.getAccessAccount(),
// s.getPassword(),
// s.getIpAddress());
// String cameraImg = alarmRecordService.getCameraImgMap(tmpPath.toString(), rtsp);
// return new CameraImage(s.getSerial(), cameraImg);
// });
// futures.add(future);
// }
// }
// List<MultipartBody.Part> parts = Lists.newArrayList();
// for (Future<CameraImage> future : futures) {
// try {
// CameraImage cameraImage= future.get();
// map.put(cameraImage.id,cameraImage.image);
// File fi = new File(cameraImage.id);
// RequestBody body = RequestBody.create(MediaType.parse("image/*"), fi);
// MultipartBody.Part imgPart = MultipartBody.Part.createFormData("img", fi.getName(), body);
// parts.add(imgPart);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
// exec.shutdown();
//
// long end = System.currentTimeMillis();
//
// logger.info("===================获取rtsp流用时===========:{}", end - start);
//
//// files.forEach(imgFile -> {
//// RequestBody body = RequestBody.create(MediaType.parse("image/*"), imgFile);
//// MultipartBody.Part imgPart = MultipartBody.Part.createFormData("img", imgFile.getName(), body);
//// parts.add(imgPart);
//// });
//
//
//// Call<ImageUpdateResponse> stringCall = imageUploadInterface.upload(parts,
//// RequestBody.create(MediaType.parse("text/plain"),"od"),
//// RequestBody.create(MediaType.parse("text/plain"),"testsmoking"),
//// RequestBody.create(MediaType.parse("text/plain"),"json"));
//// ImageUpdateResponse ret = result(stringCall, "uploadImage");
// Call<ImageUpdateResponse> stringCall = imageUploadInterface.upload(parts,
// RequestBody.create(MediaType.parse("text/plain"), "od"),
// RequestBody.create(MediaType.parse("text/plain"), "source_model"),
// RequestBody.create(MediaType.parse("text/plain"), "json"));
// ImageUpdateResponse ret = result(stringCall, "uploadImage");
//
// if (ret == null) {
// logger.warn("ret is null.");
// for (String key : map.keySet()) {
// new File(map.get(key)).delete();
// }
//
// return;
// }
//
// String path = "";
// if (!Strings.isNullOrEmpty(ret.getPath())) {
// path = ret.getPath();
// }
}
}
package com.risensafe.gas;
import com.google.common.collect.Maps;
import com.risensafe.gas.utils.Constant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
@Component
@ServerEndpoint(value = "/ws")
public class ToDashboardWebSocket {
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* 记录当前在线连接数
*/
private static final AtomicInteger onlineCount = new AtomicInteger(0);
/**
* 存放所有在线的客户端
*/
private static final Map<String, Session> clients = Maps.newConcurrentMap();
public Session getSession(String id) {
return clients.get(id);
}
@OnOpen
public void onOpen(Session session) {
onlineCount.incrementAndGet();
//clients.put(session.getId(), session);
clients.put(Constant.WEB_SOCKET_CLIENT_NAME, session);
logger.debug("new client:{},online:{}", session.getId(), onlineCount.get());
}
@OnClose
public void onClose(Session session) {
onlineCount.decrementAndGet();
//clients.remove(session.getId());
clients.remove(Constant.WEB_SOCKET_CLIENT_NAME);
logger.debug("close client{},online:{}", session.getId(), onlineCount.get());
}
@OnError
public void onError(Session session, Throwable err) {
logger.error("WebSocket({}) has error:{}", session.getId(), err.getMessage());
err.printStackTrace();
}
@OnMessage
public void onMessage(String message, Session fromSession) {
logger.debug("Messages are received:{},form:{}", message, fromSession.getId());
}
public void sendMessage(String message, String sessionId) {
// Session session = getSession(sessionId);
// sendMessage(message, session);
sendMessage(message);
}
public synchronized void sendMessage(String message){
clients.forEach((k,v)->{
try {
v.getBasicRemote().sendText(message);
} catch (IOException e) {
e.printStackTrace();
}
});
}
public synchronized void sendMessage(String message, Session toSession) {
try {
if (toSession == null) {
logger.warn("session is null,message lose.");
return;
}
logger.debug("{}", toSession);
logger.debug(" to client({}):{}", toSession.getId(), message);
toSession.getBasicRemote().sendText(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.risensafe.gas;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
package com.risensafe.gas.aop;
import com.risensafe.gas.common.exception.RisenParkingAuthException;
import com.risensafe.gas.dto.AppTokenDto;
import com.risensafe.gas.dto.ParkingDto;
import com.risensafe.gas.service.AppTokenService;
import com.risensafe.gas.service.DictionaryService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
* @author kenzo
* @create 2021-12-08 20:01
*/
@Aspect
@Component
public class ParkingAspect {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final DictionaryService dictionaryService;
private final AppTokenService appTokenService;
public ParkingAspect(DictionaryService dictionaryService,
AppTokenService appTokenService) {
this.dictionaryService = dictionaryService;
this.appTokenService = appTokenService;
}
@Pointcut("execution(public * com.risensafe.gas.controller.parking.ParkingAdd*Controller.process(..))")
public void parkingAdd() {
}
@Before(value = "parkingAdd()")
public void parkingAddDoAuth(JoinPoint point) {
// 道闸数据上报授权
if (dictionaryService.getRisenAuthSwitch()) {
logger.info("ParkingAddDoAuth - Starting");
Object[] args = point.getArgs();
if (args[0] instanceof ParkingDto) {
ParkingDto payload = (ParkingDto) args[0];
AppTokenDto token = appTokenService.getAppIdAndAppSecret();
if (!this.authValidate(token.getAppId(), token.getAppSecretMd5(), payload)) {
throw new RisenParkingAuthException("appId or appSecret error.");
}
}
}
}
private boolean authValidate(String appId, String appSecretMd5, ParkingDto payload) {
return appId.equals(payload.getAppId() != null ? payload.getAppId().trim() : null)
&& appSecretMd5.equals(payload.getAppSecret() != null ? payload.getAppSecret().trim() : null) ? Boolean.TRUE : Boolean.FALSE;
}
}
package com.risensafe.gas.camera;
import retrofit2.Call;
import retrofit2.http.GET;
import java.util.List;
public interface CameraInterface {
@GET("/v.json")
Call<List<CameraResultItem>> cameraList();
}
package com.risensafe.gas.camera;
public class CameraResult {
//private CameraResultItem;
}
package com.risensafe.gas.camera;
import com.fasterxml.jackson.annotation.JsonProperty;
public class CameraResultItem {
private String ip;
@JsonProperty("time_stamp")
private long timeStamp;
@JsonProperty("od_result")
private String odResult;
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public long getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(long timeStamp) {
this.timeStamp = timeStamp;
}
public String getOdResult() {
return odResult;
}
public void setOdResult(String odResult) {
this.odResult = odResult;
}
}
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
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