complete overhaul: now using MQTT protocol

This commit is contained in:
Evert Prants 2020-10-04 16:25:08 +03:00
parent bc0cef6fe3
commit 7278c4deec
Signed by: evert
GPG Key ID: 1688DA83D222D0B5
23 changed files with 701 additions and 249 deletions

3
.gitignore vendored
View File

@ -1,4 +1,7 @@
/bin/ /bin/
/target/
/.settings/ /.settings/
/.classpath /.classpath
/.project /.project
/.idea
/*.iml

View File

@ -1,8 +0,0 @@
name: RedstoneOutput
main: ee.lunasqu.redstoneoutput.Main
version: 1.0
api-version: 1.13
commands:
rspi:
description: Control the remote connection for RedstoneOutput
usage: /<command> start|stop|status

75
pom.xml Normal file
View File

@ -0,0 +1,75 @@
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>ee.lunasqu</groupId>
<artifactId>Interaqqt</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<name>Interaqqt</name>
<url>https://lunasqu.ee/</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<repositories>
<repository>
<id>spigot-repo</id>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.16.3-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>1.2.0</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>7</source>
<target>7</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,90 +0,0 @@
package ee.lunasqu.redstoneoutput;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitRunnable;
import ee.lunasqu.redstoneoutput.events.ConnectionEstablishedEvent;
import ee.lunasqu.redstoneoutput.events.DisconnectedEvent;
public class Connection extends BukkitRunnable {
private Socket socket;
private BufferedWriter writer;
private BufferedReader reader;
private boolean alive;
public Connection(String addr, int port) {
try {
socket = new Socket(addr, port);
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
Bukkit.getPluginManager().callEvent(new DisconnectedEvent());
return;
}
// Successful connection
Bukkit.getPluginManager().callEvent(new ConnectionEstablishedEvent());
alive = true;
}
public boolean sendStateChange (int power, String key, String value) {
if (!alive) return false;
try {
writer.write(power + ":" + key + ":" + value + "\r\n");
writer.flush();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
public void die () {
this.alive = false;
if (!socket.isClosed()) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public boolean isAlive() {
return this.alive;
}
@Override
public void run() {
if (!this.alive) {
if (!this.isCancelled()) this.cancel();
return;
}
try {
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (!alive) break;
}
alive = false;
if (!socket.isClosed()) {
socket.close();
}
} catch (Exception e) {
e.printStackTrace();
}
Bukkit.getPluginManager().callEvent(new DisconnectedEvent());
this.cancel();
}
}

View File

@ -1,70 +0,0 @@
package ee.lunasqu.redstoneoutput;
import java.util.Arrays;
import java.util.List;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.Sign;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockRedstoneEvent;
import ee.lunasqu.redstoneoutput.events.ConnectionEstablishedEvent;
import ee.lunasqu.redstoneoutput.events.DisconnectedEvent;
public class EventListener implements Listener {
private static Material[] SIGNS = {
Material.ACACIA_SIGN, Material.ACACIA_WALL_SIGN,
Material.BIRCH_SIGN, Material.BIRCH_WALL_SIGN,
Material.CRIMSON_SIGN, Material.CRIMSON_WALL_SIGN,
Material.DARK_OAK_SIGN, Material.DARK_OAK_WALL_SIGN,
Material.JUNGLE_SIGN, Material.JUNGLE_WALL_SIGN,
Material.OAK_SIGN, Material.OAK_WALL_SIGN,
Material.SPRUCE_SIGN, Material.SPRUCE_WALL_SIGN
};
@EventHandler
public void onRedstone(BlockRedstoneEvent e) {
Block b = e.getBlock();
Location[] sides = {
b.getLocation().add(new Location(b.getWorld(), 0, 1.0, 0)),
b.getLocation().add(new Location(b.getWorld(), -1.0, 0, 0)),
b.getLocation().add(new Location(b.getWorld(), 1.0, 0, 0)),
b.getLocation().add(new Location(b.getWorld(), 0, 0, 1.0)),
b.getLocation().add(new Location(b.getWorld(), 0, 0, -1.0))
};
Sign sign = null;
List<Material> checklist = Arrays.asList(EventListener.SIGNS);
for (Location p : sides) {
Block test = b.getWorld().getBlockAt(p);
if (checklist.contains(test.getType())) {
Sign i = (Sign) test.getState();
String l = i.getLine(0);
if (l.equalsIgnoreCase("[Output]")) {
sign = i;
break;
}
}
}
if (sign == null) return;
String key = sign.getLine(1);
String value = sign.getLine(2);
Connection t = Main.plugin.getConnection();
if (t == null) return;
t.sendStateChange(e.getNewCurrent(), key, value);
}
@EventHandler
public void onConnClose(DisconnectedEvent e) {
Main.plugin.getLogger().info("Connection to remote failed.");
}
@EventHandler
public void onConnEstab(ConnectionEstablishedEvent e) {
Main.plugin.getLogger().info("Connection to remote established!");
}
}

View File

@ -1,40 +0,0 @@
package ee.lunasqu.redstoneoutput;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
public class Main extends JavaPlugin {
private FileConfiguration config;
public static Main plugin;
public Connection service;
public Connection getConnection() {
if (service == null || !service.isAlive()) return null;
return service;
}
@Override
public void onEnable() {
config = this.getConfig();
config.addDefault("host", "127.0.0.1");
config.addDefault("port", 62002);
config.options().copyDefaults(true);
this.saveConfig();
plugin = this;
getServer().getPluginManager().registerEvents(new EventListener(), this);
this.getCommand("rspi").setExecutor(new RemoteCommand());
this.connect();
}
@Override
public void onDisable() {
if (service != null && service.isAlive()) service.die();
}
public void connect () {
service = new Connection(this.config.getString("host"), this.config.getInt("port"));
service.runTaskAsynchronously(this);
}
}

View File

@ -1,37 +0,0 @@
package ee.lunasqu.redstoneoutput;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
public class RemoteCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command arg1, String arg2, String[] arguments) {
switch (arguments[0]) {
case "status":
if (Main.plugin.getConnection() != null) {
sender.sendMessage("The connection is established.");
} else {
sender.sendMessage("The connection is closed.");
}
return true;
case "start":
if (Main.plugin.getConnection() != null) {
sender.sendMessage("The connection is already established!");
return false;
}
sender.sendMessage("Connection has been attempted!");
Main.plugin.connect();
return true;
case "stop":
if (Main.plugin.getConnection() == null) {
sender.sendMessage("The connection is already closed!");
return false;
}
sender.sendMessage("Connection has been closed!");
Main.plugin.getConnection().die();
return true;
}
return false;
}
}

View File

@ -0,0 +1,7 @@
package ee.lunasqu.interaqqt;
public interface IConnection {
public boolean sendStateChange(String key, String value);
public boolean isAlive();
public void die();
}

View File

@ -0,0 +1,166 @@
package ee.lunasqu.interaqqt;
import ee.lunasqu.interaqqt.events.listeners.RightClickAdder;
import ee.lunasqu.interaqqt.triggers.BlockTrigger;
import ee.lunasqu.interaqqt.triggers.BlockTriggers;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.UUID;
public class MQTTCommand implements CommandExecutor {
private static String[] TT = new String[]{"high", "low", "high-low"};
private boolean list (CommandSender sender, String[] arguments) {
if (arguments[1].equalsIgnoreCase("triggers")) {
BlockTriggers triggers = Main.plugin.getTriggers();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(ChatColor.LIGHT_PURPLE + "List of triggers:");
for (BlockTrigger trig : triggers.getTriggerList()) {
stringBuilder.append("\n");
stringBuilder.append(ChatColor.DARK_GREEN + "[*] " + ChatColor.GREEN + "\"" + trig.getName() + "\" ");
stringBuilder.append(ChatColor.BLUE + trig.getBlock().getWorld().getName() + " <");
stringBuilder.append(trig.getBlock().getX() + ", " + trig.getBlock().getY() + ", " + trig.getBlock().getZ() + "> ");
stringBuilder.append(ChatColor.GOLD + trig.getMqttTrigger() + " ");
stringBuilder.append(ChatColor.RED + TT[trig.getType()] + " ");
stringBuilder.append(ChatColor.BLUE + trig.getData());
}
sender.sendMessage(stringBuilder.toString());
return true;
}
sender.sendMessage("/mqtt list triggers | commands");
return true;
}
private boolean management (CommandSender sender, String[] arguments) {
RightClickAdder adder = Main.plugin.getAdder();
BlockTriggers triggers = Main.plugin.getTriggers();
Player p = sender.getServer().getPlayer(sender.getName());
if (arguments[0].equalsIgnoreCase("cancel")) {
if (p == null) {
sender.sendMessage(ChatColor.RED + "This command cannot be used from the console.");
return true;
}
adder.removeTriggerRequest(p.getUniqueId());
sender.sendMessage(ChatColor.GOLD + "Adding of trigger was cancelled.");
return true;
}
if (arguments.length < 2) {
return false;
}
if (arguments[1].equalsIgnoreCase("trigger")) {
if (arguments[0].equalsIgnoreCase("remove") && arguments.length == 3) {
triggers.removeBlock(arguments[2]);
sender.sendMessage(ChatColor.GREEN + "Trigger removed.");
return true;
}
if (p == null) {
sender.sendMessage(ChatColor.RED + "This command cannot be used from the console.");
return true;
}
if (arguments.length < 5) {
sender.sendMessage("/mqtt add trigger <name> <MQTT topic> <high | low | high-low> <binary | power | <value>>");
return true;
}
String name = arguments[2];
String topic = arguments[3];
String condition = arguments[4];
String value = arguments[5];
if (triggers.getTriggerByName(name) != null) {
sender.sendMessage(ChatColor.RED + "Trigger by that name already exists.");
return true;
}
if (name.isEmpty() || topic.isEmpty() || condition.isEmpty() || value.isEmpty()) return false;
int type = 0;
switch (condition.toLowerCase()) {
case "high":
type = 0;
break;
case "low":
type = 1;
break;
case "hilo":
case "highlow":
case "high-low":
type = 2;
break;
default:
sender.sendMessage(ChatColor.RED + "Invalid condition type. Supported types: high, low, high-low");
return true;
}
BlockTrigger t = new BlockTrigger(name, topic, type, value);
adder.addTriggerRequest(p.getUniqueId(), t);
sender.sendMessage(ChatColor.GOLD + "Right-click a block you wish to add as a trigger. /mqtt cancel to cancel.");
return true;
}
sender.sendMessage("/mqtt add trigger | command");
return false;
}
@Override
public boolean onCommand(CommandSender sender, Command arg1, String arg2, String[] arguments) {
if (!sender.hasPermission("mqtt.manage")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this command.");
return true;
}
if (arguments.length == 0) return false;
switch (arguments[0].toLowerCase()) {
case "status":
if (Main.plugin.getConnection() != null) {
sender.sendMessage(ChatColor.GREEN + "The connection is established.");
} else {
sender.sendMessage(ChatColor.RED + "The connection is closed.");
}
break;
case "start":
if (Main.plugin.getConnection() != null) {
sender.sendMessage(ChatColor.RED + "The connection is already established!");
break;
}
sender.sendMessage(ChatColor.GREEN + "Connection has been attempted!");
Main.plugin.connect();
break;
case "stop":
if (Main.plugin.getConnection() == null) {
sender.sendMessage(ChatColor.RED + "The connection is already closed!");
break;
}
sender.sendMessage(ChatColor.GOLD + "Connection has been closed!");
Main.plugin.getConnection().die();
break;
case "reload":
Main.plugin.getTriggers().loadConfiguration();
sender.sendMessage(ChatColor.GREEN + "Configuration has been reloaded!");
break;
case "cancel":
case "remove":
case "add":
return management(sender, arguments);
case "list":
return list(sender, arguments);
default:
return false;
}
return true;
}
}

View File

@ -0,0 +1,58 @@
package ee.lunasqu.interaqqt;
import ee.lunasqu.interaqqt.events.ConnectionEstablishedEvent;
import ee.lunasqu.interaqqt.events.DisconnectedEvent;
import org.bukkit.Bukkit;
import org.eclipse.paho.client.mqttv3.*;
public class MQTTConnection implements IConnection {
IMqttClient publisher;
public MQTTConnection (String host, String id) {
MqttConnectOptions opts = new MqttConnectOptions();
opts.setAutomaticReconnect(true);
opts.setCleanSession(true);
opts.setConnectionTimeout(10);
try {
this.publisher = new MqttClient(host, id);
this.publisher.connect();
} catch (MqttException e) {
Bukkit.getPluginManager().callEvent(new DisconnectedEvent());
e.printStackTrace();
}
Bukkit.getPluginManager().callEvent(new ConnectionEstablishedEvent());
}
@Override
public boolean sendStateChange(String key, String value) {
if (!this.isAlive()) return false;
MqttMessage msg = new MqttMessage(value.getBytes());
msg.setQos(1);
msg.setRetained(true);
try {
this.publisher.publish(key, msg);
} catch (MqttException e) {
e.printStackTrace();
return false;
}
return true;
}
@Override
public boolean isAlive() {
return this.publisher.isConnected();
}
@Override
public void die() {
if (this.publisher != null && this.publisher.isConnected()) {
try {
this.publisher.disconnect();
} catch (MqttException e) {
e.printStackTrace();
}
}
Bukkit.getPluginManager().callEvent(new DisconnectedEvent());
}
}

View File

@ -0,0 +1,68 @@
package ee.lunasqu.interaqqt;
import ee.lunasqu.interaqqt.events.listeners.ConnectionListener;
import ee.lunasqu.interaqqt.events.listeners.RedstoneListener;
import ee.lunasqu.interaqqt.events.listeners.RightClickAdder;
import ee.lunasqu.interaqqt.triggers.BlockTrigger;
import ee.lunasqu.interaqqt.triggers.BlockTriggers;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.serialization.ConfigurationSerialization;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.UUID;
public class Main extends JavaPlugin {
public static Main plugin;
private FileConfiguration config;
private IConnection service;
private BlockTriggers triggers;
private RightClickAdder adder;
public RightClickAdder getAdder() {
return adder;
}
public BlockTriggers getTriggers() {
return triggers;
}
public IConnection getConnection() {
if (service == null || !service.isAlive()) return null;
return service;
}
@Override
public void onEnable() {
config = this.getConfig();
config.addDefault("publisher", UUID.randomUUID().toString());
config.addDefault("host", "127.0.0.1");
config.addDefault("port", 1883);
config.options().copyDefaults(true);
this.saveConfig();
plugin = this;
this.triggers = new BlockTriggers();
this.adder = new RightClickAdder();
ConfigurationSerialization.registerClass(BlockTrigger.class);
this.triggers.loadConfiguration();
getServer().getPluginManager().registerEvents(new RedstoneListener(), this);
getServer().getPluginManager().registerEvents(new ConnectionListener(), this);
getServer().getPluginManager().registerEvents(adder, this);
this.getCommand("mqtt").setExecutor(new MQTTCommand());
this.connect();
}
@Override
public void onDisable() {
if (service != null && service.isAlive()) service.die();
}
public void connect () {
String host = "tcp://" + this.config.getString("host") + ":" + this.config.getInt("port");
this.service = new MQTTConnection(host, config.getString("publisher"));
}
}

View File

@ -1,4 +1,4 @@
package ee.lunasqu.redstoneoutput.events; package ee.lunasqu.interaqqt.events;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.event.Event; import org.bukkit.event.Event;

View File

@ -1,4 +1,4 @@
package ee.lunasqu.redstoneoutput.events; package ee.lunasqu.interaqqt.events;
public class ConnectionEstablishedEvent extends BaseEvent { public class ConnectionEstablishedEvent extends BaseEvent {

View File

@ -1,4 +1,4 @@
package ee.lunasqu.redstoneoutput.events; package ee.lunasqu.interaqqt.events;
public class DisconnectedEvent extends BaseEvent { public class DisconnectedEvent extends BaseEvent {

View File

@ -1,4 +1,4 @@
package ee.lunasqu.redstoneoutput.events; package ee.lunasqu.interaqqt.events;
public class InputEvent extends BaseEvent { public class InputEvent extends BaseEvent {
private String key; private String key;

View File

@ -0,0 +1,20 @@
package ee.lunasqu.interaqqt.events.listeners;
import ee.lunasqu.interaqqt.Main;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import ee.lunasqu.interaqqt.events.ConnectionEstablishedEvent;
import ee.lunasqu.interaqqt.events.DisconnectedEvent;
public class ConnectionListener implements Listener {
@EventHandler
public void onConnClose(DisconnectedEvent e) {
Main.plugin.getLogger().info("Connection to remote failed.");
}
@EventHandler
public void onConnEstablished(ConnectionEstablishedEvent e) {
Main.plugin.getLogger().info("Connection to remote established!");
}
}

View File

@ -0,0 +1,18 @@
package ee.lunasqu.interaqqt.events.listeners;
import ee.lunasqu.interaqqt.Main;
import ee.lunasqu.interaqqt.triggers.BlockTriggers;
import org.bukkit.Location;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockRedstoneEvent;
public class RedstoneListener implements Listener {
@EventHandler
public void onRedstone(BlockRedstoneEvent e) {
if (e.getOldCurrent() == e.getNewCurrent()) return;
Location location = e.getBlock().getLocation();
BlockTriggers triggers = Main.plugin.getTriggers();
triggers.triggerLocation(location, e.getNewCurrent());
}
}

View File

@ -0,0 +1,52 @@
package ee.lunasqu.interaqqt.events.listeners;
import ee.lunasqu.interaqqt.Main;
import ee.lunasqu.interaqqt.triggers.BlockTrigger;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import java.util.HashMap;
import java.util.UUID;
public class RightClickAdder implements Listener {
HashMap<UUID, BlockTrigger> triggerHashMap = new HashMap<UUID, BlockTrigger>();
@EventHandler
public void onRightClick(PlayerInteractEvent event) {
Player p = event.getPlayer();
UUID id = p.getUniqueId();
if (triggerHashMap.containsKey(id)) {
if (p.isSneaking()) {
p.sendRawMessage(ChatColor.RED + "Adding of trigger cancelled!");
triggerHashMap.remove(id);
return;
}
BlockTrigger trigger = triggerHashMap.get(id);
trigger.setBlock(event.getClickedBlock().getLocation());
p.sendRawMessage(ChatColor.GREEN + "Trigger added to block!");
Main.plugin.getTriggers().addBlock(trigger);
triggerHashMap.remove(id);
}
}
public void onPlayerLeave(PlayerQuitEvent event) {
if (triggerHashMap.containsKey(event.getPlayer().getUniqueId())) {
triggerHashMap.remove(event.getPlayer().getUniqueId());
}
}
public void addTriggerRequest (UUID playerId, BlockTrigger trigger) {
triggerHashMap.put(playerId, trigger);
}
public void removeTriggerRequest (UUID playerId) {
if (triggerHashMap.containsKey(playerId)) {
triggerHashMap.remove(playerId);
}
}
}

View File

@ -0,0 +1,90 @@
package ee.lunasqu.interaqqt.triggers;
import org.bukkit.Location;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import java.util.HashMap;
import java.util.Map;
public class BlockTrigger implements ConfigurationSerializable {
private String name;
private Location block;
private String mqttTrigger;
private int type;
private String data;
public BlockTrigger (String name, String mqttTrigger, int type, String data) {
this.name = name;
this.mqttTrigger = mqttTrigger;
this.type = type;
this.data = data;
}
public BlockTrigger (String name, Location block, String mqttTrigger, int type, String data) {
this.name = name;
this.block = block;
this.mqttTrigger = mqttTrigger;
this.type = type;
this.data = data;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Location getBlock() {
return block;
}
public void setBlock(Location block) {
this.block = block;
}
public String getMqttTrigger() {
return mqttTrigger;
}
public void setMqttTrigger(String mqttTrigger) {
this.mqttTrigger = mqttTrigger;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String toString () {
return String.format("%s|%s|%s|%d|%s", name, mqttTrigger, block, type, data);
}
@Override
public Map<String, Object> serialize() {
Map<String,Object> map = new HashMap<String,Object>();
map.put("name", name);
map.put("trigger", mqttTrigger);
map.put("pos", block);
map.put("type", type);
map.put("data", data);
return map;
}
public static BlockTrigger deserialize(Map<String, Object> args) {
return new BlockTrigger((String) args.get("name"), (Location) args.get("pos"),
(String) args.get("trigger"), (int) args.get("type"), (String) args.get("data"));
}
}

View File

@ -0,0 +1,127 @@
package ee.lunasqu.interaqqt.triggers;
import ee.lunasqu.interaqqt.Main;
import org.bukkit.Location;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class BlockTriggers {
File triggerConfigFile;
FileConfiguration triggerConfig;
List<BlockTrigger> triggers = new ArrayList<BlockTrigger>();
public void addBlock (String name, Location block, String mqttTrigger, int type, String data) {
triggers.add(new BlockTrigger(name, block, mqttTrigger, type, data));
}
public void addBlock (BlockTrigger trigger) {
if(triggers.contains(trigger)) return;
triggers.add(trigger);
this.saveConfiguration();
}
public void removeBlock (BlockTrigger trigger) {
triggers.remove(trigger);
this.saveConfiguration();
}
public void removeBlock (String name) {
BlockTrigger trigger = this.getTriggerByName(name);
if (trigger == null) return;
this.removeBlock(trigger);
}
public BlockTrigger getTriggerByName (String name) {
for (BlockTrigger t : triggers) {
if (t.getName().equals(name)) return t;
}
return null;
}
public BlockTrigger getTriggerByLocation (Location block) {
for (BlockTrigger t : triggers) {
if (t.getBlock().equals(block)) return t;
}
return null;
}
public List<BlockTrigger> getTriggerList () {
return triggers;
}
public void loadConfiguration() {
triggerConfigFile = new File(Main.plugin.getDataFolder(), "triggers.yml");
if (!triggerConfigFile.exists()) {
triggerConfigFile.getParentFile().mkdirs();
Main.plugin.saveResource("triggers.yml", false);
}
triggerConfig = new YamlConfiguration();
try {
triggerConfig.load(triggerConfigFile);
} catch (IOException | InvalidConfigurationException e) {
e.printStackTrace();
}
Map<String, Object> triggerMap = triggerConfig.getValues(true);
for (Object trig : triggerMap.values()) {
triggers.add((BlockTrigger) trig);
}
}
public void saveConfiguration () {
if (triggerConfig == null) this.loadConfiguration();
Map<String,BlockTrigger> triggerMap = new HashMap<String,BlockTrigger>();
for (BlockTrigger trigger : triggers) {
triggerConfig.set(trigger.getName(), trigger);
}
try {
triggerConfig.save(triggerConfigFile);
} catch (IOException e) {
e.printStackTrace();
}
}
public boolean triggerLocation (Location block, int power) {
BlockTrigger triggerData = getTriggerByLocation(block);
if (triggerData == null) return false;
String send = null;
String data = triggerData.getData();
int type = triggerData.getType();
if (data.equals("power")) {
send = String.valueOf(power);
} else {
send = data;
}
if (type == 0 && power == 0) return false;
if (type == 1 && power > 0) return false;
// Binary value
if (data.equals("binary")) {
if (type == 0 && power > 0) {
send = "1";
} else if (type == 1 && power == 0) {
send = "0";
} else if (type == 2) {
if (power > 0) send = "1";
else send = "0";
}
}
if (send == null) return false;
Main.plugin.getConnection().sendStateChange(triggerData.getMqttTrigger(), send);
return true;
}
}

View File

@ -0,0 +1,4 @@
package ee.lunasqu.interaqqt.triggers;
public class CommandTriggers {
}

View File

@ -0,0 +1,9 @@
name: Interaqqt
main: ee.lunasqu.interaqqt.Main
version: 1.0
api-version: 1.13
commands:
mqtt:
description: Control the MQTT connection for Interaqqt
usage: /<command> add | remove | start | stop | status
permission: mqtt.manage

View File