Browse Source

Commit initial

Le serveur communique avec le simulateur dom et la BDD.
Possibilité d'allumer/éteindre un équipement avec une commande envoyée sur le serveur, mais seulement une fois.
dev
Guillaume 3 years ago
commit
1e643a992f
  1. 7
      .classpath
  2. 2
      .gitattributes
  3. 17
      .project
  4. 11
      .settings/org.eclipse.jdt.core.prefs
  5. BIN
      bin/dao/CDatabase.class
  6. BIN
      bin/dao/CEquipment.class
  7. BIN
      bin/main/CMain.class
  8. BIN
      bin/net/CClient.class
  9. BIN
      bin/net/CServer.class
  10. BIN
      bin/net/CService.class
  11. BIN
      lib/mysql-connector-java-8.0.15.jar
  12. 47
      src/dao/CDatabase.java
  13. 113
      src/dao/CEquipment.java
  14. 52
      src/main/CMain.java
  15. 109
      src/net/CClient.java
  16. 86
      src/net/CServer.java
  17. 47
      src/net/CService.java

7
.classpath

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/>
<classpathentry kind="lib" path="S:/Eclipse/workspace/ConnectMysql/lib/mysql-connector-java-8.0.15.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>

2
.gitattributes

@ -0,0 +1,2 @@
# Auto detect text files and perform LF normalization
* text=auto

17
.project

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>ServeurDom</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

11
.settings/org.eclipse.jdt.core.prefs

@ -0,0 +1,11 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.8

BIN
bin/dao/CDatabase.class

Binary file not shown.

BIN
bin/dao/CEquipment.class

Binary file not shown.

BIN
bin/main/CMain.class

Binary file not shown.

BIN
bin/net/CClient.class

Binary file not shown.

BIN
bin/net/CServer.class

Binary file not shown.

BIN
bin/net/CService.class

Binary file not shown.

BIN
lib/mysql-connector-java-8.0.15.jar

Binary file not shown.

47
src/dao/CDatabase.java

@ -0,0 +1,47 @@
package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Connection;
import com.mysql.cj.jdbc.Driver;
public class CDatabase {
//Adresse IP et port de la base de donnée
public static final String DB_IP = "localhost";
public static final String DB_PORT = "3306"; //port MySQL par défaut
//Protocole de connexion
public static final String PROTOCOLE = "jdbc:mysql:";
//Nom de la BDD
public static final String DB_NAME = "clicom";
public static final String CONNECTION_STRING = PROTOCOLE + "//" + DB_IP + ":" + DB_PORT + "/" + DB_NAME;
//Identifiants
public static final String LOGIN = "root";
public static final String PASSWORD = "";
// //Chargement de la classe
// Class c = Class.forName("com.mysql.cj.jdbc.Driver");
// Driver pilote = (Driver)c.newInstance();
// //Enregistrement du pilote auprès du DriverManager
//
// //Protocole de connexion
// String protocole = "jdbc:mysql:";
// //Adresse IP de l'hôte de la base et port
// String ip = "localhost";
// String port = "3306"; //port MySQL par défaut
// //Nom de la BDD
// String nomBase = "clicom";
// String conString = protocole + "//" + ip + ":" + port + "/" + nomBase;
// //Identifiants
// String nomConnexion = "root";
// String motDePasse = "";
// public Connection getConnection()
// {
// //Connexion
// Connection con = DriverManager.getConnection(conString, nomConnexion, motDePasse);
// return con;
// }
}

113
src/dao/CEquipment.java

@ -0,0 +1,113 @@
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import main.CMain;
public class CEquipment {
//Méthode d'insertion d'un équipement
public static void insertTest(String nom, String ip, String port, int type, int idEmplacement, String etat,
String positionXY, String commentaire,Connection con)
{
Statement smt;
try {
smt = con.createStatement();
String sql = "insert into equipment(NOM, IP, PORT, TYPE, IDEMPLACEMENT, ETAT, PositionXY, commentaire) values ("
+ "'" + nom + "', '" + ip + "', '" + port + "', " + type + ", " + idEmplacement
+ ", '" + etat + "', '" + positionXY + "', '" + commentaire + "');";
int count = smt.executeUpdate(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//Allumer ou éteindre un équipement
public static List<String> turnOnOffOneEquipment(int id, String etat) throws Exception
{
List<String> equipmentIpPortState = new ArrayList<String>();
//Envoi d'une requête pour récupérer les infos de l'equipement
String sqlQuery = "SELECT * FROM equipment WHERE EquID = " + id;
Statement smt = CMain.con.createStatement();
ResultSet rs = smt.executeQuery(sqlQuery);
updateEquipment(id, etat, "EquID", CMain.con);
while(rs.next())
{
equipmentIpPortState.add(rs.getString("IP") + "+" + rs.getString("port") + etat);
}
System.out.println("id : " + id + ", etat : " + etat);
smt = CMain.con.createStatement();
return equipmentIpPortState;
}
//Allumer ou éteindre plusieurs équipements
public static List<String> turnOnOffMultipleEquipments(int equipmentType, String etat, int roomID) throws SQLException
{
List<String> equipmentsIpPortState = new ArrayList<String>();
//Envoi d'une requête
String sql;
sql = "select * from equipment where type = " + equipmentType;
if(roomID != 0)
{
sql += " and IDEMPLACEMENT = " + roomID;
}
Statement smt = CMain.con.createStatement();
ResultSet rs = smt.executeQuery(sql);
while(rs.next())
{
equipmentsIpPortState.add(rs.getString("IP") + "+" + rs.getString("port") + etat);
updateEquipment(equipmentType, etat, "type", CMain.con);
}
smt = CMain.con.createStatement();
return equipmentsIpPortState;
}
//Modifier l'état d'un équipement
public static void updateEquipment(int idType, String etat, String where, Connection con) throws SQLException
{
String sql;
PreparedStatement preparedSmt = null;
try {
sql = "update equipment set etat = ? where "+ where +" = ?";
preparedSmt = con.prepareStatement(sql);
preparedSmt.setString(1, etat);
preparedSmt.setInt(2, idType);
preparedSmt.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//Récupérer l'état d'un équipement
public static String getEquipmentState(int id) throws SQLException
{
String sqlQuery = "SELECT * FROM equipment WHERE EquID = " + id;
Statement smt = CMain.con.createStatement();
ResultSet rs = smt.executeQuery(sqlQuery);
String state = "";
while(rs.next())
{
state = rs.getString("etat");
}
return state;
}
}

52
src/main/CMain.java

@ -0,0 +1,52 @@
package main;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import net.CClient;
import net.CServer;
import dao.CDatabase;
public class CMain {
public static final int HOUSE_PORT = 39098;
public static final String HOUSE_IP = "192.168.56.1";
public static Connection con = null;
public static void main(String[] args) {
try {
//Chargement de la classe
Class c = Class.forName("com.mysql.cj.jdbc.Driver");
Driver pilote = (Driver)c.newInstance();
//Enregistrement du pilote auprès du DriverManager
DriverManager.registerDriver(pilote);
//Connexion
con = DriverManager.getConnection(CDatabase.CONNECTION_STRING, CDatabase.LOGIN, CDatabase.PASSWORD);
CServer server = new CServer();
/*String etat = "1";
int id = 1;
//CEquipment.insertTest("Luminaire nord", "192.168.0.100", "00010111", 1, 1, "0", "Centre", "", con);
CClient.getInstance(HOUSE_PORT, HOUSE_IP);
//CEquipment.updateEquipment(1, "0", con);
CClient.getInstance().sendCommand(CEquipment.turnOnOffOneEquipment(1, "1"));
//CClient.getInstance().sendCommand(CEquipment.turnOnOffMultipleEquipments(id, 1, etat));
System.out.println(CEquipment.getEquipmentState(id));
CClient.getInstance().closeClient();*/
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

109
src/net/CClient.java

@ -0,0 +1,109 @@
package net;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.sql.Driver;
import java.sql.DriverManager;
import java.util.List;
import main.CMain;
public class CClient extends Socket implements Runnable {
// Singleton de la classe CClient (l'unique instance qui peut être créée).
private static CClient sInstance = null;
private BufferedReader mBr;
private PrintWriter mPw;
public BufferedReader getmBr() {
return mBr;
}
public PrintWriter getmPw() {
return mPw;
}
public static CClient getInstance(int pPort, String pIPAddr) {
if (sInstance == null) {
try {
sInstance = new CClient(pPort, pIPAddr);
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
return sInstance;
}
// Attention : cette méthode ne doit pas être appelée en premier.
public static CClient getInstance() {
if (sInstance == null) {
System.out.println("Appel interdit.");
}
return sInstance;
}
private CClient(int pPort, String pIPAddr) throws IOException {
super(pIPAddr, pPort);
// Création des flux d'E/S.
// Flux d'entrée.
System.out.println("Client : création des flux.");
mBr = new BufferedReader(
new InputStreamReader(
getInputStream()));
// Flux de sortie.
mPw = new PrintWriter(
getOutputStream(), true);
new Thread(this).start();
}
@Override
public void run() {
}
//Méthode pour envoyer les commandes au simulateur domotique
public void sendCommand(List<String> equipments) throws IOException {
//On parcourt la liste d'équipements retournée par les requêtes SQL
System.out.println("Envoie de la commande.");
for(String equipment : equipments)
{
//On sépare la chaîne concaténée de la requête
//Pour récupérer l'IP de l'équipement,
//puis son entrée et l'état voulu
String[] equipmentSplit = equipment.split("\\+");
//On sépare chaque valeur qu'on enverra en octet
String[] ip = equipmentSplit[0].split("\\.");
String[] equipmentOut = equipmentSplit[1].split("");
//On transforme les valeurs en octets
for(String bytes : ip)
{
//System.out.println(bytes);
mPw.print((char)Integer.parseInt(bytes));
}
for(String bytes : equipmentOut)
{
//System.out.println(bits);
mPw.print((char)Integer.parseInt(bytes));
}
mPw.print((char)0);
}
mPw.flush();
}
public void closeClient() throws IOException
{
mPw.close();
mBr.close();
close();
}
}

86
src/net/CServer.java

@ -0,0 +1,86 @@
package net;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.SQLException;
import main.CMain;
import dao.CEquipment;
public class CServer extends ServerSocket implements Runnable{
private static final int PORT = 45000; //Valeur arbitraire
public static boolean SERVER_WAITS = true;
public CServer() throws Exception{
super(PORT);
new Thread(this).start();
//CClient.getInstance(CMain.HOUSE_PORT, CMain.HOUSE_IP);
}
@Override
public void run() {
while(true)
{
try {
System.out.println("Attente d'un client...");
Socket s = accept();
//Permet d'attendre qu'un client se connecte
//Attention cette instruction est bloquante
System.out.println("Un client vient de se connecter");
//A ce stade, un client est connecté. On peut communiqué avec lui grâce à un Socket
//Création d'un flux d'entrée(client vers serveur)
System.out.println("Création des flux d'entrée");
BufferedReader br = new BufferedReader(
new InputStreamReader(
s.getInputStream()));
//Création du flux de sortie(serveur vers client)
System.out.println("Création des flux de sortie");
PrintWriter pw = new PrintWriter(
s.getOutputStream(), true);
String message; String[] command; String result;
//Récupération de la requête du client
System.out.println("Récupération de la requête du client");
message = br.readLine();
command = message.split("\\/");
result = "";
//Traitement de la requête du client(par exemple il s'agit de mettre en majuscules le message du client)
System.out.println("Traitement de la requête client");
if(command[0].equals("getState"))
{
result = CEquipment.getEquipmentState(Integer.parseInt(command[1]));
pw.println(result);
//System.out.println(result);
}else if(command[0].equals("turnOnOffOneEquipment"))
{
CClient.getInstance(CMain.HOUSE_PORT, CMain.HOUSE_IP);
CClient.getInstance().sendCommand(CEquipment.turnOnOffOneEquipment(Integer.parseInt(command[1]), command[2]));
CClient.getInstance().closeClient();
} else if(command[0].equals("turnOnOffMultipleEquipments"))
{
CClient.getInstance(CMain.HOUSE_PORT, CMain.HOUSE_IP);
CClient.getInstance().sendCommand(CEquipment.turnOnOffMultipleEquipments(Integer.parseInt(command[1]), command[2], Integer.parseInt(command[3])));
CClient.getInstance().closeClient();
}
pw.close(); br.close();
}
catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

47
src/net/CService.java

@ -0,0 +1,47 @@
package net;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class CService implements Runnable {
private Socket mSocket; // Socket de service
private BufferedReader mBr; // Flux d'entrée
private PrintWriter mPw; // Flux de sortie
private CServer mServer;
public CService(CServer pServer, Socket pSocket) {
mServer = pServer;
mSocket = pSocket;
try {
System.out.println("Service : création des flux.");
mBr = new BufferedReader(new InputStreamReader(mSocket.getInputStream()));
mPw = new PrintWriter(mSocket.getOutputStream(), true); // true = auto flush
} catch (IOException e) {
System.out.println(e.getMessage());
}
new Thread(this).start();
}
@Override
public void run() {
while (true) {
try {
System.out.println("Service : lecture message du client.");
String lRequest = mBr.readLine();
System.out.println("Service : message reçu : " + lRequest);
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
public void sendMessage(String pMessage) {
mPw.write(pMessage);
}
}
Loading…
Cancel
Save