commit
d34978037f
@ -0,0 +1,37 @@ |
||||
HELP.md |
||||
.gradle |
||||
build/ |
||||
!gradle/wrapper/gradle-wrapper.jar |
||||
!**/src/main/**/build/ |
||||
!**/src/test/**/build/ |
||||
|
||||
### STS ### |
||||
.apt_generated |
||||
.classpath |
||||
.factorypath |
||||
.project |
||||
.settings |
||||
.springBeans |
||||
.sts4-cache |
||||
bin/ |
||||
!**/src/main/**/bin/ |
||||
!**/src/test/**/bin/ |
||||
|
||||
### IntelliJ IDEA ### |
||||
.idea |
||||
*.iws |
||||
*.iml |
||||
*.ipr |
||||
out/ |
||||
!**/src/main/**/out/ |
||||
!**/src/test/**/out/ |
||||
|
||||
### NetBeans ### |
||||
/nbproject/private/ |
||||
/nbbuild/ |
||||
/dist/ |
||||
/nbdist/ |
||||
/.nb-gradle/ |
||||
|
||||
### VS Code ### |
||||
.vscode/ |
@ -0,0 +1,23 @@ |
||||
plugins { |
||||
id 'java' |
||||
id "io.freefair.lombok" version "5.3.0" |
||||
id 'org.springframework.boot' version '2.7.4' |
||||
id 'io.spring.dependency-management' version '1.0.14.RELEASE' |
||||
} |
||||
|
||||
group 'org.example' |
||||
version '1.0-SNAPSHOT' |
||||
|
||||
repositories { |
||||
mavenCentral() |
||||
} |
||||
|
||||
dependencies { |
||||
implementation group: 'eu.chargetime.ocpp', name: 'v1_6', version: '1.0.1' |
||||
implementation 'org.springframework.boot:spring-boot-starter' |
||||
testImplementation 'org.springframework.boot:spring-boot-starter-test' |
||||
} |
||||
|
||||
test { |
||||
useJUnitPlatform() |
||||
} |
Binary file not shown.
@ -0,0 +1,5 @@ |
||||
distributionBase=GRADLE_USER_HOME |
||||
distributionPath=wrapper/dists |
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-bin.zip |
||||
zipStoreBase=GRADLE_USER_HOME |
||||
zipStorePath=wrapper/dists |
@ -0,0 +1,240 @@ |
||||
#!/bin/sh |
||||
|
||||
# |
||||
# Copyright © 2015-2021 the original 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 POSIX generated by Gradle. |
||||
# |
||||
# Important for running: |
||||
# |
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is |
||||
# noncompliant, but you have some other compliant shell such as ksh or |
||||
# bash, then to run this script, type that shell name before the whole |
||||
# command line, like: |
||||
# |
||||
# ksh Gradle |
||||
# |
||||
# Busybox and similar reduced shells will NOT work, because this script |
||||
# requires all of these POSIX shell features: |
||||
# * functions; |
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», |
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»; |
||||
# * compound commands having a testable exit status, especially «case»; |
||||
# * various built-in commands including «command», «set», and «ulimit». |
||||
# |
||||
# Important for patching: |
||||
# |
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided |
||||
# by Bash, Ksh, etc; in particular arrays are avoided. |
||||
# |
||||
# The "traditional" practice of packing multiple parameters into a |
||||
# space-separated string is a well documented source of bugs and security |
||||
# problems, so this is (mostly) avoided, by progressively accumulating |
||||
# options in "$@", and eventually passing that to Java. |
||||
# |
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, |
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; |
||||
# see the in-line comments for details. |
||||
# |
||||
# There are tweaks for specific operating systems such as AIX, CygWin, |
||||
# Darwin, MinGW, and NonStop. |
||||
# |
||||
# (3) This script is generated from the Groovy template |
||||
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt |
||||
# within the Gradle project. |
||||
# |
||||
# You can find Gradle at https://github.com/gradle/gradle/. |
||||
# |
||||
############################################################################## |
||||
|
||||
# Attempt to set APP_HOME |
||||
|
||||
# Resolve links: $0 may be a link |
||||
app_path=$0 |
||||
|
||||
# Need this for daisy-chained symlinks. |
||||
while |
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path |
||||
[ -h "$app_path" ] |
||||
do |
||||
ls=$( ls -ld "$app_path" ) |
||||
link=${ls#*' -> '} |
||||
case $link in #( |
||||
/*) app_path=$link ;; #( |
||||
*) app_path=$APP_HOME$link ;; |
||||
esac |
||||
done |
||||
|
||||
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit |
||||
|
||||
APP_NAME="Gradle" |
||||
APP_BASE_NAME=${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 "$*" |
||||
} >&2 |
||||
|
||||
die () { |
||||
echo |
||||
echo "$*" |
||||
echo |
||||
exit 1 |
||||
} >&2 |
||||
|
||||
# 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 ;; #( |
||||
MSYS* | 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" && ! "$darwin" && ! "$nonstop" ; then |
||||
case $MAX_FD in #( |
||||
max*) |
||||
MAX_FD=$( ulimit -H -n ) || |
||||
warn "Could not query maximum file descriptor limit" |
||||
esac |
||||
case $MAX_FD in #( |
||||
'' | soft) :;; #( |
||||
*) |
||||
ulimit -n "$MAX_FD" || |
||||
warn "Could not set maximum file descriptor limit to $MAX_FD" |
||||
esac |
||||
fi |
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order: |
||||
# * args from the command line |
||||
# * the main class name |
||||
# * -classpath |
||||
# * -D...appname settings |
||||
# * --module-path (only if needed) |
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. |
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java |
||||
if "$cygwin" || "$msys" ; then |
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) |
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) |
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" ) |
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh |
||||
for arg do |
||||
if |
||||
case $arg in #( |
||||
-*) false ;; # don't mess with options #( |
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath |
||||
[ -e "$t" ] ;; #( |
||||
*) false ;; |
||||
esac |
||||
then |
||||
arg=$( cygpath --path --ignore --mixed "$arg" ) |
||||
fi |
||||
# Roll the args list around exactly as many times as the number of |
||||
# args, so each arg winds up back in the position where it started, but |
||||
# possibly modified. |
||||
# |
||||
# NB: a `for` loop captures its iteration list before it begins, so |
||||
# changing the positional parameters here affects neither the number of |
||||
# iterations, nor the values presented in `arg`. |
||||
shift # remove old arg |
||||
set -- "$@" "$arg" # push replacement arg |
||||
done |
||||
fi |
||||
|
||||
# Collect all arguments for the java command; |
||||
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of |
||||
# shell script including quotes and variable substitutions, so put them in |
||||
# double quotes to make sure that they get re-expanded; and |
||||
# * put everything else in single quotes, so that it's not re-expanded. |
||||
|
||||
set -- \ |
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \ |
||||
-classpath "$CLASSPATH" \ |
||||
org.gradle.wrapper.GradleWrapperMain \ |
||||
"$@" |
||||
|
||||
# Stop when "xargs" is not available. |
||||
if ! command -v xargs >/dev/null 2>&1 |
||||
then |
||||
die "xargs is not available" |
||||
fi |
||||
|
||||
# Use "xargs" to parse quoted args. |
||||
# |
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed. |
||||
# |
||||
# In Bash we could simply go: |
||||
# |
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) && |
||||
# set -- "${ARGS[@]}" "$@" |
||||
# |
||||
# but POSIX shell has neither arrays nor command substitution, so instead we |
||||
# post-process each arg (as a line of input to sed) to backslash-escape any |
||||
# character that might be a shell metacharacter, then use eval to reverse |
||||
# that process (while maintaining the separation between arguments), and wrap |
||||
# the whole thing up as a single "set" statement. |
||||
# |
||||
# This will of course break if any of these variables contains a newline or |
||||
# an unmatched quote. |
||||
# |
||||
|
||||
eval "set -- $( |
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | |
||||
xargs -n1 | |
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | |
||||
tr '\n' ' ' |
||||
)" '"$@"' |
||||
|
||||
exec "$JAVACMD" "$@" |
@ -0,0 +1,2 @@ |
||||
# This file is generated by the 'io.freefair.lombok' Gradle plugin |
||||
config.stopBubbling = true |
@ -0,0 +1 @@ |
||||
rootProject.name = 'ocppstub' |
@ -0,0 +1,50 @@ |
||||
package com.yablochkov.ocppstub; |
||||
|
||||
import eu.chargetime.ocpp.model.core.*; |
||||
import lombok.RequiredArgsConstructor; |
||||
import lombok.extern.slf4j.Slf4j; |
||||
import org.springframework.stereotype.Service; |
||||
|
||||
import java.nio.charset.StandardCharsets; |
||||
import java.time.ZonedDateTime; |
||||
import java.util.Base64; |
||||
import java.util.UUID; |
||||
|
||||
@Slf4j |
||||
@Service |
||||
@RequiredArgsConstructor |
||||
public class BootService { |
||||
private final static int PASSWD = 1; |
||||
private final static int INTERVAL_SEC = 10; |
||||
|
||||
private final SessionService sessionService; |
||||
|
||||
public BootNotificationConfirmation handle(UUID sessionIndex, BootNotificationRequest request) { |
||||
String auth = sessionService.getAuthBySessionId(sessionIndex); |
||||
String passwd = getPasswd(auth); |
||||
|
||||
if (passwd != null) { |
||||
log.info("Accept boot request {}", sessionIndex); |
||||
return createResponse(RegistrationStatus.Accepted); |
||||
} |
||||
|
||||
log.info("Pending boot request {}", sessionIndex); |
||||
return createResponse(RegistrationStatus.Pending); |
||||
} |
||||
|
||||
private String getPasswd(String basic) { |
||||
if (basic != null && !basic.isEmpty()) { |
||||
byte[] credDecoded = Base64.getDecoder().decode(basic.substring("Basic ".length())); |
||||
String credentials = new String(credDecoded, StandardCharsets.UTF_8); |
||||
if (credentials.contains(":")) { |
||||
String[] parsedCredential = credentials.split(":", 2); |
||||
return parsedCredential[PASSWD]; |
||||
} |
||||
} |
||||
return null; |
||||
} |
||||
|
||||
private BootNotificationConfirmation createResponse(RegistrationStatus status) { |
||||
return new BootNotificationConfirmation(ZonedDateTime.now(), INTERVAL_SEC, status); |
||||
} |
||||
} |
@ -0,0 +1,49 @@ |
||||
package com.yablochkov.ocppstub; |
||||
|
||||
import eu.chargetime.ocpp.feature.profile.ServerCoreProfile; |
||||
import eu.chargetime.ocpp.model.core.*; |
||||
import lombok.extern.slf4j.Slf4j; |
||||
import org.springframework.beans.factory.annotation.Autowired; |
||||
import org.springframework.context.annotation.Lazy; |
||||
import org.springframework.stereotype.Service; |
||||
|
||||
import java.util.UUID; |
||||
|
||||
@Slf4j |
||||
@Service |
||||
public class ConfigService { |
||||
private final static String DEFAULT_KEY = "0001020304050607FFFFFFFFFFFFFFFFFFFFFFFF"; |
||||
@Lazy |
||||
@Autowired private OcppStub server; |
||||
@Lazy |
||||
@Autowired private ServerCoreProfile coreProfile; |
||||
|
||||
public void sengConfig(UUID sessionIndex) { |
||||
log.info("Sending configuration"); |
||||
ChangeConfigurationRequest configurationRequest = coreProfile |
||||
.createChangeConfigurationRequest("AuthorizationKey", DEFAULT_KEY); |
||||
|
||||
try { |
||||
server.send(sessionIndex, configurationRequest) |
||||
.thenApply(confirmation -> { |
||||
log.debug("Get confirmation"); |
||||
if (confirmation instanceof ChangeConfigurationConfirmation) { |
||||
log.debug("Confirmation type is ChangeConfigurationConfirmation"); |
||||
ConfigurationStatus status = ((ChangeConfigurationConfirmation) confirmation).getStatus(); |
||||
if (status == ConfigurationStatus.Accepted) { |
||||
log.debug("Confirmation status is accepted"); |
||||
return Void.TYPE; |
||||
} |
||||
} |
||||
log.error("Charge point don't confirm password change"); |
||||
throw new RuntimeException("CP don't confirm pass change"); |
||||
}) |
||||
.thenRunAsync(() -> { |
||||
log.info("Closing session {}", sessionIndex); |
||||
server.closeSession(sessionIndex); |
||||
}); |
||||
} catch (Exception e) { |
||||
log.error("Exception on ChangeConfiguration", e); |
||||
} |
||||
} |
||||
} |
@ -0,0 +1,16 @@ |
||||
package com.yablochkov.ocppstub; |
||||
|
||||
import eu.chargetime.ocpp.model.core.StatusNotificationConfirmation; |
||||
import eu.chargetime.ocpp.model.core.StatusNotificationRequest; |
||||
import lombok.extern.slf4j.Slf4j; |
||||
import org.springframework.stereotype.Service; |
||||
|
||||
import java.util.UUID; |
||||
|
||||
@Slf4j |
||||
@Service |
||||
public class ConnectorStatusService { |
||||
public StatusNotificationConfirmation handle(UUID sessionIndex, StatusNotificationRequest request) { |
||||
return new StatusNotificationConfirmation(); |
||||
} |
||||
} |
@ -0,0 +1,74 @@ |
||||
package com.yablochkov.ocppstub; |
||||
|
||||
import eu.chargetime.ocpp.ServerEvents; |
||||
import eu.chargetime.ocpp.feature.profile.ServerCoreEventHandler; |
||||
import eu.chargetime.ocpp.model.SessionInformation; |
||||
import eu.chargetime.ocpp.model.core.*; |
||||
import lombok.RequiredArgsConstructor; |
||||
import org.springframework.stereotype.Component; |
||||
|
||||
import java.util.UUID; |
||||
|
||||
@Component |
||||
@RequiredArgsConstructor |
||||
public class EventHandler implements ServerCoreEventHandler, ServerEvents { |
||||
private final SessionService sessionService; |
||||
private final BootService bootService; |
||||
private final HeartbeatService heartbeatService; |
||||
private final ConfigService configService; |
||||
private final ConnectorStatusService connectorService; |
||||
|
||||
@Override |
||||
public AuthorizeConfirmation handleAuthorizeRequest(UUID sessionIndex, AuthorizeRequest request) { |
||||
return null; |
||||
} |
||||
|
||||
@Override |
||||
public BootNotificationConfirmation handleBootNotificationRequest(UUID sessionIndex, BootNotificationRequest request) { |
||||
BootNotificationConfirmation response = bootService.handle(sessionIndex, request); |
||||
if (response.getStatus() == RegistrationStatus.Pending) { |
||||
configService.sengConfig(sessionIndex); |
||||
} |
||||
return response; |
||||
} |
||||
|
||||
@Override |
||||
public DataTransferConfirmation handleDataTransferRequest(UUID sessionIndex, DataTransferRequest request) { |
||||
return null; |
||||
} |
||||
|
||||
@Override |
||||
public HeartbeatConfirmation handleHeartbeatRequest(UUID sessionIndex, HeartbeatRequest request) { |
||||
return heartbeatService.handle(sessionIndex, request); |
||||
} |
||||
|
||||
@Override |
||||
public MeterValuesConfirmation handleMeterValuesRequest(UUID sessionIndex, MeterValuesRequest request) { |
||||
return null; |
||||
} |
||||
|
||||
@Override |
||||
public StartTransactionConfirmation handleStartTransactionRequest(UUID sessionIndex, StartTransactionRequest request) { |
||||
return null; |
||||
} |
||||
|
||||
@Override |
||||
public StatusNotificationConfirmation handleStatusNotificationRequest(UUID sessionIndex, StatusNotificationRequest request) { |
||||
return connectorService.handle(sessionIndex, request); |
||||
} |
||||
|
||||
@Override |
||||
public StopTransactionConfirmation handleStopTransactionRequest(UUID sessionIndex, StopTransactionRequest request) { |
||||
return null; |
||||
} |
||||
|
||||
@Override |
||||
public void newSession(UUID sessionIndex, SessionInformation information) { |
||||
sessionService.register(sessionIndex, information); |
||||
} |
||||
|
||||
@Override |
||||
public void lostSession(UUID sessionIndex) { |
||||
sessionService.unregister(sessionIndex); |
||||
} |
||||
} |
@ -0,0 +1,18 @@ |
||||
package com.yablochkov.ocppstub; |
||||
|
||||
import eu.chargetime.ocpp.model.core.HeartbeatConfirmation; |
||||
import eu.chargetime.ocpp.model.core.HeartbeatRequest; |
||||
import lombok.extern.slf4j.Slf4j; |
||||
import org.springframework.stereotype.Service; |
||||
|
||||
import java.time.ZonedDateTime; |
||||
import java.util.UUID; |
||||
|
||||
@Service |
||||
@Slf4j |
||||
public class HeartbeatService { |
||||
public HeartbeatConfirmation handle(UUID sessionIndex, HeartbeatRequest request) { |
||||
log.debug("Heartbeat for session {}", sessionIndex); |
||||
return new HeartbeatConfirmation(ZonedDateTime.now()); |
||||
} |
||||
} |
@ -0,0 +1,35 @@ |
||||
package com.yablochkov.ocppstub; |
||||
|
||||
import eu.chargetime.ocpp.NotConnectedException; |
||||
import eu.chargetime.ocpp.OccurenceConstraintException; |
||||
import eu.chargetime.ocpp.UnsupportedFeatureException; |
||||
import eu.chargetime.ocpp.YablJSONServer; |
||||
import eu.chargetime.ocpp.model.Confirmation; |
||||
import eu.chargetime.ocpp.model.Request; |
||||
import lombok.RequiredArgsConstructor; |
||||
import org.springframework.stereotype.Component; |
||||
|
||||
import javax.annotation.PostConstruct; |
||||
import java.util.UUID; |
||||
import java.util.concurrent.CompletionStage; |
||||
|
||||
@Component |
||||
@RequiredArgsConstructor |
||||
public class OcppStub { |
||||
private final EventHandler eventHandler; |
||||
private final YablJSONServer server; |
||||
|
||||
@PostConstruct |
||||
private void Init() { |
||||
server.open("0.0.0.0", 8080, eventHandler); |
||||
} |
||||
|
||||
public CompletionStage<Confirmation> send(UUID sessionIndex, Request request) |
||||
throws OccurenceConstraintException, UnsupportedFeatureException, NotConnectedException { |
||||
return server.send(sessionIndex, request); |
||||
} |
||||
|
||||
public void closeSession(UUID sessionIndex) { |
||||
server.closeSession(sessionIndex); |
||||
} |
||||
} |
@ -0,0 +1,13 @@ |
||||
package com.yablochkov.ocppstub; |
||||
|
||||
import org.springframework.boot.SpringApplication; |
||||
import org.springframework.boot.autoconfigure.SpringBootApplication; |
||||
|
||||
@SpringBootApplication |
||||
public class OcppStubApplication { |
||||
|
||||
public static void main(String[] args) { |
||||
SpringApplication.run(OcppStubApplication.class, args); |
||||
} |
||||
|
||||
} |
@ -0,0 +1,41 @@ |
||||
package com.yablochkov.ocppstub; |
||||
|
||||
import eu.chargetime.ocpp.YablSessionInformation; |
||||
import eu.chargetime.ocpp.model.SessionInformation; |
||||
import lombok.extern.slf4j.Slf4j; |
||||
import org.java_websocket.handshake.ClientHandshake; |
||||
import org.springframework.stereotype.Service; |
||||
|
||||
import java.util.HashMap; |
||||
import java.util.Map; |
||||
import java.util.UUID; |
||||
|
||||
@Service |
||||
@Slf4j |
||||
public class SessionService { |
||||
private final Map<UUID,SessionInformation> cache = new HashMap<>(); |
||||
public void register(UUID sessionIndex, SessionInformation information) { |
||||
log.info("Register new session {}", sessionIndex); |
||||
cache.put(sessionIndex, information); |
||||
} |
||||
|
||||
public void unregister(UUID sessionIndex) { |
||||
cache.remove(sessionIndex); |
||||
} |
||||
|
||||
public String getAuthBySessionId(UUID sessionId) { |
||||
SessionInformation sessionInformation = cache.get(sessionId); |
||||
|
||||
if (sessionInformation instanceof YablSessionInformation) { |
||||
YablSessionInformation session = (YablSessionInformation) sessionInformation; |
||||
|
||||
ClientHandshake clientHandshake = session.getClientHandshake(); |
||||
if (clientHandshake != null) { |
||||
return clientHandshake.getFieldValue("Authorization"); |
||||
} |
||||
} |
||||
|
||||
log.debug("Session {} auth status not found", sessionId); |
||||
return null; |
||||
} |
||||
} |
@ -0,0 +1,20 @@ |
||||
package com.yablochkov.ocppstub.configuration; |
||||
|
||||
import com.yablochkov.ocppstub.EventHandler; |
||||
import eu.chargetime.ocpp.YablJSONServer; |
||||
import eu.chargetime.ocpp.feature.profile.ServerCoreProfile; |
||||
import org.springframework.context.annotation.Bean; |
||||
import org.springframework.context.annotation.Configuration; |
||||
|
||||
@Configuration |
||||
public class AppConfig { |
||||
@Bean |
||||
public ServerCoreProfile getServerCoreProfile(EventHandler handler) { |
||||
return new ServerCoreProfile(handler); |
||||
} |
||||
|
||||
@Bean |
||||
public YablJSONServer getJSONServer(ServerCoreProfile profile) { |
||||
return new YablJSONServer(profile); |
||||
} |
||||
} |
@ -0,0 +1,140 @@ |
||||
package eu.chargetime.ocpp; |
||||
|
||||
import eu.chargetime.ocpp.feature.profile.Profile; |
||||
import eu.chargetime.ocpp.feature.profile.ServerCoreProfile; |
||||
import eu.chargetime.ocpp.model.Confirmation; |
||||
import eu.chargetime.ocpp.model.Request; |
||||
import eu.chargetime.ocpp.wss.BaseWssFactoryBuilder; |
||||
import eu.chargetime.ocpp.wss.WssFactoryBuilder; |
||||
import org.java_websocket.drafts.Draft; |
||||
import org.java_websocket.drafts.Draft_6455; |
||||
import org.java_websocket.protocols.IProtocol; |
||||
import org.java_websocket.protocols.Protocol; |
||||
import org.slf4j.Logger; |
||||
import org.slf4j.LoggerFactory; |
||||
|
||||
import javax.net.ssl.SSLContext; |
||||
import java.io.IOException; |
||||
import java.util.ArrayList; |
||||
import java.util.Collections; |
||||
import java.util.UUID; |
||||
import java.util.concurrent.CompletionStage; |
||||
|
||||
public class YablJSONServer implements IServerAPI { |
||||
private static final Logger logger = LoggerFactory.getLogger(eu.chargetime.ocpp.JSONServer.class); |
||||
|
||||
public final Draft draftOcppOnly; |
||||
private final YablWebSocketListener listener; |
||||
private final Server server; |
||||
private final FeatureRepository featureRepository; |
||||
|
||||
/** |
||||
* The core feature profile is required as a minimum. The constructor creates WS-ready server. |
||||
* |
||||
* @param coreProfile implementation of the core feature profile. |
||||
* @param configuration network configuration for a json server. |
||||
*/ |
||||
public YablJSONServer(ServerCoreProfile coreProfile, JSONConfiguration configuration) { |
||||
featureRepository = new FeatureRepository(); |
||||
SessionFactory sessionFactory = new SessionFactory(featureRepository); |
||||
|
||||
ArrayList<IProtocol> protocols = new ArrayList<>(); |
||||
protocols.add(new Protocol("ocpp1.6")); |
||||
protocols.add(new Protocol("")); |
||||
draftOcppOnly = new Draft_6455(Collections.emptyList(), protocols); |
||||
|
||||
this.listener = new YablWebSocketListener(sessionFactory, configuration, draftOcppOnly); |
||||
server = new Server(this.listener, featureRepository, new PromiseRepository()); |
||||
featureRepository.addFeatureProfile(coreProfile); |
||||
} |
||||
|
||||
/** |
||||
* The core feature profile is required as a minimum. The constructor creates WS-ready server. |
||||
* |
||||
* @param coreProfile implementation of the core feature profile. |
||||
*/ |
||||
public YablJSONServer(ServerCoreProfile coreProfile) { |
||||
this(coreProfile, JSONConfiguration.get()); |
||||
} |
||||
|
||||
/** |
||||
* The core feature profile is required as a minimum. The constructor creates WSS-ready server. |
||||
* |
||||
* @param coreProfile implementation of the core feature profile. |
||||
* @param wssFactoryBuilder to build {@link org.java_websocket.WebSocketServerFactory} to support |
||||
* wss://.
|
||||
* @param configuration network configuration for a json server. |
||||
*/ |
||||
public YablJSONServer( |
||||
ServerCoreProfile coreProfile, |
||||
WssFactoryBuilder wssFactoryBuilder, |
||||
JSONConfiguration configuration) { |
||||
this(coreProfile, configuration); |
||||
enableWSS(wssFactoryBuilder); |
||||
} |
||||
|
||||
/** |
||||
* The core feature profile is required as a minimum. The constructor creates WSS-ready server. |
||||
* |
||||
* @param coreProfile implementation of the core feature profile. |
||||
* @param wssFactoryBuilder to build {@link org.java_websocket.WebSocketServerFactory} to support |
||||
* wss://.
|
||||
*/ |
||||
public YablJSONServer(ServerCoreProfile coreProfile, WssFactoryBuilder wssFactoryBuilder) { |
||||
this(coreProfile, wssFactoryBuilder, JSONConfiguration.get()); |
||||
} |
||||
|
||||
// To ensure the exposed API is backward compatible
|
||||
public void enableWSS(SSLContext sslContext) throws IOException { |
||||
WssFactoryBuilder builder = BaseWssFactoryBuilder.builder().sslContext(sslContext); |
||||
enableWSS(builder); |
||||
} |
||||
|
||||
/** |
||||
* Enables server to accept WSS connections. The {@code wssFactoryBuilder} must be initialized at |
||||
* that step (as required parameters set might vary depending on implementation the {@link |
||||
* eu.chargetime.ocpp.wss.WssFactoryBuilder#verify()} is used to ensure initialization). |
||||
* |
||||
* @param wssFactoryBuilder builder to provide WebSocketServerFactory |
||||
* @return instance of {@link eu.chargetime.ocpp.JSONServer} |
||||
* @throws IllegalStateException in case if the server is already connected |
||||
* @throws IllegalStateException in case {@code wssFactoryBuilder} not initialized properly |
||||
*/ |
||||
public YablJSONServer enableWSS(WssFactoryBuilder wssFactoryBuilder) { |
||||
wssFactoryBuilder.verify(); |
||||
listener.enableWSS(wssFactoryBuilder); |
||||
return this; |
||||
} |
||||
|
||||
@Override |
||||
public void addFeatureProfile(Profile profile) { |
||||
featureRepository.addFeatureProfile(profile); |
||||
} |
||||
|
||||
@Override |
||||
public void closeSession(UUID session) { |
||||
server.closeSession(session); |
||||
} |
||||
|
||||
@Override |
||||
public void open(String host, int port, ServerEvents serverEvents) { |
||||
logger.info("Feature repository: {}", featureRepository); |
||||
server.open(host, port, serverEvents); |
||||
} |
||||
|
||||
@Override |
||||
public void close() { |
||||
server.close(); |
||||
} |
||||
|
||||
@Override |
||||
public boolean isClosed() { |
||||
return listener.isClosed(); |
||||
} |
||||
|
||||
@Override |
||||
public CompletionStage<Confirmation> send(UUID session, Request request) |
||||
throws OccurenceConstraintException, UnsupportedFeatureException, NotConnectedException { |
||||
return server.send(session, request); |
||||
} |
||||
} |
@ -0,0 +1,17 @@ |
||||
package eu.chargetime.ocpp; |
||||
|
||||
import eu.chargetime.ocpp.model.SessionInformation; |
||||
import lombok.Builder; |
||||
import lombok.Getter; |
||||
import org.java_websocket.handshake.ClientHandshake; |
||||
|
||||
import java.net.InetSocketAddress; |
||||
|
||||
@Builder |
||||
@Getter |
||||
public class YablSessionInformation extends SessionInformation { |
||||
private String identifier; |
||||
private InetSocketAddress address; |
||||
private String SOAPtoURL; |
||||
private ClientHandshake clientHandshake; |
||||
} |
@ -0,0 +1,192 @@ |
||||
package eu.chargetime.ocpp; |
||||
|
||||
import eu.chargetime.ocpp.model.SessionInformation; |
||||
import eu.chargetime.ocpp.wss.WssFactoryBuilder; |
||||
import org.java_websocket.WebSocket; |
||||
import org.java_websocket.drafts.Draft; |
||||
import org.java_websocket.handshake.ClientHandshake; |
||||
import org.java_websocket.server.WebSocketServer; |
||||
import org.slf4j.Logger; |
||||
import org.slf4j.LoggerFactory; |
||||
|
||||
import java.io.IOException; |
||||
import java.net.ConnectException; |
||||
import java.net.InetSocketAddress; |
||||
import java.util.Arrays; |
||||
import java.util.List; |
||||
import java.util.Map; |
||||
import java.util.concurrent.ConcurrentHashMap; |
||||
|
||||
public class YablWebSocketListener implements Listener { |
||||
private static final Logger logger = LoggerFactory.getLogger(WebSocketListener.class); |
||||
|
||||
private static final int TIMEOUT_IN_MILLIS = 10000; |
||||
|
||||
private final ISessionFactory sessionFactory; |
||||
private final List<Draft> drafts; |
||||
|
||||
private final JSONConfiguration configuration; |
||||
private volatile WebSocketServer server; |
||||
private WssFactoryBuilder wssFactoryBuilder; |
||||
private final Map<WebSocket, WebSocketReceiver> sockets; |
||||
private volatile boolean closed = true; |
||||
private boolean handleRequestAsync; |
||||
|
||||
public YablWebSocketListener( |
||||
ISessionFactory sessionFactory, JSONConfiguration configuration, Draft... drafts) { |
||||
this.sessionFactory = sessionFactory; |
||||
this.configuration = configuration; |
||||
this.drafts = Arrays.asList(drafts); |
||||
this.sockets = new ConcurrentHashMap<>(); |
||||
} |
||||
|
||||
public YablWebSocketListener(ISessionFactory sessionFactory, Draft... drafts) { |
||||
this(sessionFactory, JSONConfiguration.get(), drafts); |
||||
} |
||||
|
||||
@Override |
||||
public void open(String hostname, int port, ListenerEvents handler) { |
||||
server = |
||||
new WebSocketServer(new InetSocketAddress(hostname, port), drafts) { |
||||
@Override |
||||
public void onOpen(WebSocket webSocket, ClientHandshake clientHandshake) { |
||||
logger.debug( |
||||
"On connection open (resource descriptor: {})", |
||||
clientHandshake.getResourceDescriptor()); |
||||
|
||||
WebSocketReceiver receiver = |
||||
new WebSocketReceiver( |
||||
new WebSocketReceiverEvents() { |
||||
@Override |
||||
public boolean isClosed() { |
||||
return closed; |
||||
} |
||||
|
||||
@Override |
||||
public void close() { |
||||
webSocket.close(); |
||||
} |
||||
|
||||
@Override |
||||
public void relay(String message) { |
||||
webSocket.send(message); |
||||
} |
||||
}); |
||||
|
||||
sockets.put(webSocket, receiver); |
||||
|
||||
SessionInformation information = |
||||
YablSessionInformation.builder() |
||||
.identifier(clientHandshake.getResourceDescriptor()) |
||||
.address(webSocket.getRemoteSocketAddress()) |
||||
.clientHandshake(clientHandshake) |
||||
.build(); |
||||
|
||||
handler.newSession( |
||||
sessionFactory.createSession(new JSONCommunicator(receiver)), information); |
||||
} |
||||
|
||||
@Override |
||||
public void onClose(WebSocket webSocket, int code, String reason, boolean remote) { |
||||
logger.debug( |
||||
"On connection close (resource descriptor: {}, code: {}, reason: {}, remote: {})", |
||||
webSocket.getResourceDescriptor(), |
||||
code, |
||||
reason, |
||||
remote); |
||||
|
||||
WebSocketReceiver receiver = sockets.get(webSocket); |
||||
if (receiver != null) { |
||||
receiver.disconnect(); |
||||
sockets.remove(webSocket); |
||||
} else { |
||||
logger.debug("Receiver for socket not found: {}", webSocket); |
||||
} |
||||
} |
||||
|
||||
@Override |
||||
public void onMessage(WebSocket webSocket, String message) { |
||||
sockets.get(webSocket).relay(message); |
||||
} |
||||
|
||||
@Override |
||||
public void onError(WebSocket webSocket, Exception ex) { |
||||
String resourceDescriptor = |
||||
(webSocket != null) |
||||
? webSocket.getResourceDescriptor() |
||||
: "not defined (webSocket is null)"; |
||||
|
||||
if (ex instanceof ConnectException) { |
||||
logger.error( |
||||
"On error (resource descriptor: " + resourceDescriptor + ") triggered caused by:", |
||||
ex); |
||||
} else { |
||||
logger.error( |
||||
"On error (resource descriptor: " + resourceDescriptor + ") triggered:", ex); |
||||
} |
||||
} |
||||
|
||||
@Override |
||||
public void onStart() { |
||||
logger.debug("Server socket bound"); |
||||
} |
||||
}; |
||||
|
||||
if (wssFactoryBuilder != null) { |
||||
server.setWebSocketFactory(wssFactoryBuilder.build()); |
||||
} |
||||
|
||||
configure(); |
||||
server.start(); |
||||
closed = false; |
||||
} |
||||
|
||||
void configure() { |
||||
server.setReuseAddr(configuration.getParameter(JSONConfiguration.REUSE_ADDR_PARAMETER, true)); |
||||
server.setTcpNoDelay( |
||||
configuration.getParameter(JSONConfiguration.TCP_NO_DELAY_PARAMETER, false)); |
||||
server.setConnectionLostTimeout( |
||||
configuration.getParameter(JSONConfiguration.PING_INTERVAL_PARAMETER, 60)); |
||||
} |
||||
|
||||
void enableWSS(WssFactoryBuilder wssFactoryBuilder) { |
||||
if (server != null) { |
||||
throw new IllegalStateException("Cannot enable WSS on already running server"); |
||||
} |
||||
|
||||
this.wssFactoryBuilder = wssFactoryBuilder; |
||||
} |
||||
|
||||
@Override |
||||
public void close() { |
||||
|
||||
if (server == null) { |
||||
return; |
||||
} |
||||
|
||||
try { |
||||
server.stop(TIMEOUT_IN_MILLIS); |
||||
sockets.clear(); |
||||
} catch (InterruptedException e) { |
||||
// Do second try
|
||||
try { |
||||
server.stop(); |
||||
} catch (IOException | InterruptedException ex) { |
||||
logger.error("Failed to close listener", ex); |
||||
} |
||||
} finally { |
||||
closed = true; |
||||
server = null; |
||||
} |
||||
} |
||||
|
||||
@Override |
||||
public boolean isClosed() { |
||||
return closed; |
||||
} |
||||
|
||||
@Override |
||||
public void setAsyncRequestHandler(boolean async) { |
||||
this.handleRequestAsync = async; |
||||
} |
||||
} |
@ -0,0 +1 @@ |
||||
|
@ -0,0 +1,13 @@ |
||||
package com.yablochkov.ocppstub; |
||||
|
||||
import org.junit.jupiter.api.Test; |
||||
import org.springframework.boot.test.context.SpringBootTest; |
||||
|
||||
@SpringBootTest |
||||
class OcppstubApplicationTests { |
||||
|
||||
@Test |
||||
void contextLoads() { |
||||
} |
||||
|
||||
} |
Loading…
Reference in new issue