Wednesday, February 1, 2023

Contoh Mengakses PLC Dengan Java - IV

 


13. Start and stop a PLC

import PLCCom.*;

import javax.swing.JOptionPane;

 

public class NewClass {

 

    PLCcomDevice Device;

    //see section 'connect' for declare and connect a PLCcom-Device

 

    //Start PLC

    private void btnwriteRawDataActionPerformed(java.awt.event.ActionEvent evt) {

 

        //execute function

        OperationResult res = Device.StartPLC();

 

        //evaluate results

        if (res.Quality().equals(OperationResult.eQuality.GOOD)) {

            JOptionPane.showMessageDialog(null, "OK", "", JOptionPane.INFORMATION_MESSAGE);

        } else {

            JOptionPane.showMessageDialog(null, res.Message(), "", JOptionPane.ERROR_MESSAGE);

        }

    }

     

    //Stop PLC

    private void btnwriteRawDataActionPerformed(java.awt.event.ActionEvent evt) {

 

        //execute function

        OperationResult res = Device.StopPLC();

 

        //evaluate results

        if (res.Quality().equals(OperationResult.eQuality.GOOD)) {

            JOptionPane.showMessageDialog(null, "OK", "", JOptionPane.INFORMATION_MESSAGE);

        } else {

            JOptionPane.showMessageDialog(null, res.Message(), "", JOptionPane.ERROR_MESSAGE);

        }

    }

}


14. Reading block list from PLC

import PLCCom.*;

import javax.swing.JOptionPane;

 

public class NewClass {

 

    PLCcomDevice Device;

    //see section 'connect' for declare and connect a PLCcom-Device

 

    private void btngetPLCBlockListActionPerformed(java.awt.event.ActionEvent evt) {

 

        eBlockType BlockType = eBlockType.AllBlocks;

        BlockListResult res = Device.GetBlockList(BlockType);

 

        //evaluate results

        if (res.Quality().equals(OperationResult.eQuality.GOOD)) {

            StringBuilder sb = new StringBuilder();

            for (BlockListEntry ble : res.getBlockList()) {

                sb.append(ble.getBlockType().toString());

                sb.append(String.valueOf(ble.getBlockNumber()));

                sb.append(System.getProperty("line.separator"));

            }

            JOptionPane.showMessageDialog(null, "OK", "", JOptionPane.INFORMATION_MESSAGE);

        } else {

            JOptionPane.showMessageDialog(null, res.Message(), "", JOptionPane.ERROR_MESSAGE);

        }

    }

}


15. Get length of block

import PLCCom.*;

import javax.swing.JOptionPane;

 

public class NewClass {

 

    PLCcomDevice Device;

    //see section 'connect' for declare and connect a PLCcom-Device

 

    private void btnBlockLenActionPerformed(java.awt.event.ActionEvent evt) {

 

        //get Len from DB100

        int BlockNumber = 100;

        eBlockType BlockType = eBlockType.AllBlocks;

 

        //evaluate results

        BlockListLengthResult res = Device.GetBlockLenght(BlockType, BlockNumber);

 

        //evaluate results

        if (res.Quality().equals(OperationResult.eQuality.GOOD)) {

            StringBuilder sb = new StringBuilder();

            sb.append(res.getBlockType().toString());

            sb.append(String.valueOf(res.getBlockNumber()));

            sb.append(" Len:");

            sb.append(String.valueOf(res.getBlockLength()));

            JOptionPane.showMessageDialog(null, "OK", "", JOptionPane.INFORMATION_MESSAGE);

        } else {

            JOptionPane.showMessageDialog(null, res.Message(), "", JOptionPane.ERROR_MESSAGE);

        }

    }

}


16. Backup block

import PLCCom.*;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import javax.swing.JFileChooser;

import javax.swing.JOptionPane;

import javax.swing.filechooser.FileFilter;

import javax.swing.filechooser.FileNameExtensionFilter;

 

public class NewClass {

 

    PLCcomDevice Device;

    //see section 'connect' for declare and connect a PLCcom-Device

 

    private void btnBackup_BlockActionPerformed(java.awt.event.ActionEvent evt) {

 

        //Backup OB1

        int BlockNumber = 1;

        eBlockType BlockType = eBlockType.OB;

 

        //open SaveFileDialog

        final JFileChooser dr = new JFileChooser();

        FileFilter filter = new FileNameExtensionFilter("Binary Files *.mc7", "mc7");

        dr.addChoosableFileFilter(filter);

        int returnVal = dr.showSaveDialog(this);

        if (returnVal == JFileChooser.APPROVE_OPTION) {

            //read Block into ReadPLCBlockResult

            ReadPLCBlockResult res = Device.ReadPLCBlock_MC7(BlockType, BlockNumber);

 

            //evaluate results

            if (res.Quality().equals(OperationResult.eQuality.GOOD)) {

                try {

                    //save buffer in specified file

                    File file = new File(dr.getSelectedFile().getAbsolutePath());

 

                    //rename file to .mc7, you can adjust the extension

                    if (!file.getAbsolutePath().endsWith(".mc7")) {

                        file = new File(dr.getSelectedFile().getAbsolutePath() + ".mc7");

                    }

                    // if file doesn´t exists, then create it

                    if (!file.exists()) {

                        file.createNewFile();

                    }

                    FileOutputStream fs = new FileOutputStream(file);

                    fs.write(res.getBuffer());

                    fs.close();

                    JOptionPane.showMessageDialog(null, "Block " + String.valueOf(String.valueOf(BlockType)) + String.valueOf(BlockNumber) + resources.getString("successful_saved") + dr.getSelectedFile().getName(), "", JOptionPane.INFORMATION_MESSAGE);

                } catch (IOException ex) {

                    JOptionPane.showMessageDialog(null, "operation unsuccessful", "", JOptionPane.ERROR_MESSAGE);

                }

                JOptionPane.showMessageDialog(null, "OK", "", JOptionPane.INFORMATION_MESSAGE);

            } else {

                JOptionPane.showMessageDialog(null, res.Message(), "", JOptionPane.ERROR_MESSAGE);

            }

        } else {

            JOptionPane.showMessageDialog(null, "operation aborted", "", JOptionPane.ERROR_MESSAGE);

        }

    }

}


17. Restore block

import PLCCom.*;

import java.io.BufferedInputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStream;

import javax.swing.JFileChooser;

import javax.swing.JOptionPane;

import javax.swing.filechooser.FileFilter;

import javax.swing.filechooser.FileNameExtensionFilter;

 

public class NewClass {

 

    PLCcomDevice Device;

    //see section 'connect' for declare and connect a PLCcom-Device

 

    private void btnRestore_BlockActionPerformed(java.awt.event.ActionEvent evt) {

        final JFileChooser dr = new JFileChooser();

        FileFilter filter = new FileNameExtensionFilter("Binary Files *.mc7, *.bin", "mc7", "bin");

        dr.addChoosableFileFilter(filter);

        int returnVal = dr.showOpenDialog(this);

        if (returnVal == JFileChooser.APPROVE_OPTION) {

            try {

                File file = new File(dr.getSelectedFile().getAbsolutePath());

                if (!file.exists()) {

                    JOptionPane.showMessageDialog(null, "operation unsuccessful, file not exist", "", JOptionPane.ERROR_MESSAGE);

                    return;

                }

                InputStream is = null;

                byte[] buffer = null;

                try {

                    is = new BufferedInputStream(new FileInputStream(file));

                    buffer = new byte[is.available()];

                    is.read(buffer);

                } finally {

                    is.close();

                }

                WritePLCBlockRequest Requestdata = new WritePLCBlockRequest(buffer);

                //Write Buffer into PLC

                OperationResult res = Device.WritePLCBlock_MC7(Requestdata);

 

                //evaluate results

                if (res.Quality().equals(OperationResult.eQuality.GOOD)) {

                    JOptionPane.showMessageDialog(null, "Block " + String.valueOf(Requestdata.getBlockInfo().getHeader().getBlockType()) + String.valueOf(Requestdata.getBlockInfo().getHeader().getBlockNumber()) + "successful saved in PLC! File:" + dr.getSelectedFile().getName(), "", JOptionPane.INFORMATION_MESSAGE);

                } else {

                    JOptionPane.showMessageDialog(null, res.Message(), "", JOptionPane.ERROR_MESSAGE);

                }

            } catch (IOException ex) {

                JOptionPane.showMessageDialog(null, "operation unsuccessful", "", JOptionPane.ERROR_MESSAGE);

            }

        } else {

            JOptionPane.showMessageDialog(null, "operation aborted", "", JOptionPane.ERROR_MESSAGE);

        }

    }

}


18. Delete block

import PLCCom.*;

import javax.swing.JOptionPane;

 

public class NewClass {

 

    PLCcomDevice Device;

    //see section 'connect' for declare and connect a PLCcom-Device

 

    private void btnDeleteBlockActionPerformed(java.awt.event.ActionEvent evt) {

 

        //Delete DB100

        int BlockNumber = 100;

        eBlockType BlockType = eBlockType.DB;

 

        OperationResult res = Device.DeleteBlock(BlockType, BlockNumber);

 

        //evaluate results

        if (res.Quality().equals(OperationResult.eQuality.GOOD)) {

            JOptionPane.showMessageDialog(null, "OK", "", JOptionPane.INFORMATION_MESSAGE);

        } else {

            JOptionPane.showMessageDialog(null, res.Message(), "", JOptionPane.ERROR_MESSAGE);

        }

    }

}


Reference : https://www.plccom.net/en/plccom/for-s7/fors7-code-examples/

Contoh Mengakses PLC Dengan Java - III

 


9. Get or set PLC time

import PLCCom.*;

import java.util.Calendar;

import javax.swing.JOptionPane;

 

public class NewClass {

 

    PLCcomDevice Device;

    //see section 'connect' for declare and connect a PLCcom-Device

 

    //read PLC time

    private void btnGetPLCTimeActionPerformed(java.awt.event.ActionEvent evt) {

 

        //execute function

        PLCClockTimeResult res = Device.GetPLCClockTime();

 

        //evaluate results

        if (res.Quality().equals(OperationResult.eQuality.GOOD)) {

            Calendar c = res.getPLCClockTime();

            JOptionPane.showMessageDialog(null, "OK", "", JOptionPane.INFORMATION_MESSAGE);

        } else {

            JOptionPane.showMessageDialog(null, res.Message(), "", JOptionPane.ERROR_MESSAGE);

        }

    }

     

    //set PLC time

    private void btnSetPLCTimeActionPerformed(java.awt.event.ActionEvent evt) {

        Calendar data = new GregorianCalendar();

        //adjust and set hour

        data.set(Calendar.HOUR_OF_DAY, data.get(Calendar.HOUR_OF_DAY) - 0);

        //execute function

        OperationResult res = Device.SetPLCClockTime(data);

 

        //evaluate results

        if (res.Quality().equals(OperationResult.eQuality.GOOD)) {

            JOptionPane.showMessageDialog(null, "OK", "", JOptionPane.INFORMATION_MESSAGE);

        } else {

            JOptionPane.showMessageDialog(null, res.Message(), "", JOptionPane.ERROR_MESSAGE);

        }

    }

     

}


10. Reading system status list SSL

import PLCCom.*;

import javax.swing.JOptionPane;

 

public class NewClass {

 

    PLCcomDevice Device;

    //see section 'connect' for declare and connect a PLCcom-Device

 

        private void btnReadSSL_SZLActionPerformed(java.awt.event.ActionEvent evt) {

 

        // important!!! please search the id and index information in the plc-documentation

        // You must convert the specified values hex in decimal

        int SSL_ID = 306; //ID 132 (Hex)

        int SSL_Index = 4; //Index 4 (Hex)

        //execute function

        SystemStatusListResult res = Device.GetSystemStatusList(SSL_ID, SSL_Index);

 

        //evaluate results

        if (res.Quality().equals(OperationResult.eQuality.GOOD)) {

            StringBuilder sb = new StringBuilder();

            for (SystemStatusListItemEntry ssle : res.getSZLItemEntrys()) {

                for (byte b : ssle.getBuffer()) {

                    sb.append(String.valueOf(b));

                    sb.append(" ");

                }

                sb.append(System.getProperty("line.separator"));

            }

        JOptionPane.showMessageDialog(null, "OK", "", JOptionPane.INFORMATION_MESSAGE);

        } else {

            JOptionPane.showMessageDialog(null, res.Message(), "", JOptionPane.ERROR_MESSAGE);

        }

    }

}


11. Get diagnostic data

import PLCCom.*;

import javax.swing.JOptionPane;

 

public class NewClass {

 

    PLCcomDevice Device;

    //see section 'connect' for declare and connect a PLCcom-Device

 

    private void btnDiagnoseBufferActionPerformed(java.awt.event.ActionEvent evt) {

 

        //read the diagnosticinfo into DiagnosticInfoResult-object

        //execute function

        DiagnosticInfoResult res = Device.GetDiagnosticInfo();

 

        //evaluate results

        if (res.Quality().equals(OperationResult.eQuality.GOOD)) {

            //step through the entries

            StringBuilder sb = new StringBuilder();

            for (DiagnosticInfoEntry myDiagnosticInfoEntry : res.getDiagnosticInfoEntrys()) {

                sb.append("Timestamp: ");

                sb.append(myDiagnosticInfoEntry.getDiagnosticTimestamp().toString());

                sb.append(" ");

                sb.append("ID: ");

                sb.append(String.valueOf(myDiagnosticInfoEntry.getDiagnosticID()));

                sb.append(" ");

                sb.append("Message: ");

                sb.append(myDiagnosticInfoEntry.getDiagnosticText());

                sb.append(System.getProperty("line.separator"));

            }

            JOptionPane.showMessageDialog(null, "OK", "", JOptionPane.INFORMATION_MESSAGE);

        } else {

            JOptionPane.showMessageDialog(null, res.Message(), "", JOptionPane.ERROR_MESSAGE);

        }

    }

}


12. Send password

import PLCCom.*;

import javax.swing.JOptionPane;

 

public class NewClass {

 

    PLCcomDevice Device;

    //see section 'connect' for declare and connect a PLCcom-Device

 

        private void btnsendPWActionPerformed(java.awt.event.ActionEvent evt) {

 

        OperationResult res = Device.sendPassWord("EnterPW");

        //evaluate results

        if (res.Quality().equals(OperationResult.eQuality.GOOD)) {

            JOptionPane.showMessageDialog(null, "OK", "", JOptionPane.INFORMATION_MESSAGE);

        } else {

            JOptionPane.showMessageDialog(null, res.Message(), "", JOptionPane.ERROR_MESSAGE);

        }

    }

}


Reference : https://www.plccom.net/en/plccom/for-s7/fors7-code-examples/

Contoh Mengakses PLC Dengan Java - I

 

Programmable Logic Controller, disingkat PLC merupakan peralatan elektronik yang dibangun dari mikroprosesor untuk memonitor keadaan dari peralatan input untuk kemudian di analisa sesuai dengan kebutuhan perencana (programmer) untuk mengontrol keadaan output. Sinyal input diberikan kedalam input card.
Ada 2 jenis input card, yaitu :
  • Analog input card
  • Digital input card

Contoh untuk mengakses PLC :

1. Connect to PLC

import PLCCom.*;
import javax.swing.JOptionPane;
 
public class NewClass {
 
    //declare the Device
    PLCcomDevice Device;
 
    private void btnConnectActionPerformed(java.awt.event.ActionEvent evt) {
      //Connecting Device
 
        //create TCP_ISO_Device instance from PLCcomDevice
        Device = new TCP_ISO_Device("192.168.1.2", 0, 2, ePLCType.S7_300_400_compatibel);
        //or create MPI_Device instance from PLCcomDevice
        //Device = new MPI_Device("COM2", 0, 2, eBaudrate.b38400, eSpeed.Speed187k, ePLCType.S7_300_400_compatibel);
        //or create PPI_Device instance from PLCcomDevice
        //Device = new PPI_Device("COM2", 0, 2, eBaudrate.b9600, ePLCType.S7_200_compatibel);
         
        authentication.User("");//Enter User here
        authentication.Serial("");//Enter Serial here
         
        Device.setConnecttimeout(1000);
        Device.setReadtimeout(2000);
        ConnectResult res = Device.Connect();
         
        JOptionPane.showMessageDialog(null, res.Message(), "", JOptionPane.OK_CANCEL_OPTION);
    }
}



import PLCCom.*;
import javax.swing.JOptionPane;
 
public class NewClass {
 
    //declare the Device
    PLCcomDevice Device;
 
    private void btnConnectActionPerformed(java.awt.event.ActionEvent evt) {
      //Connecting Device
 
        //create TCP_ISO_Device instance from PLCcomDevice
        Device = new TCP_ISO_Device("192.168.1.2", 0, 2, ePLCType.S7_300_400_compatibel);
        //or create MPI_Device instance from PLCcomDevice
        //Device = new MPI_Device("COM2", 0, 2, eBaudrate.b38400, eSpeed.Speed187k, ePLCType.S7_300_400_compatibel);
        //or create PPI_Device instance from PLCcomDevice
        //Device = new PPI_Device("COM2", 0, 2, eBaudrate.b9600, ePLCType.S7_200_compatibel);
         
        authentication.User("");//Enter User here
        authentication.Serial("");//Enter Serial here
         
        Device.setConnecttimeout(1000);
        Device.setReadtimeout(2000);
        ConnectResult res = Device.Connect();
         
        JOptionPane.showMessageDialog(null, res.Message(), "", JOptionPane.OK_CANCEL_OPTION);
    }
}
import PLCCom.*;
import javax.swing.JOptionPane;
 
public class NewClass {
 
    //declare the Device
    PLCcomDevice Device;
 
    private void btnConnectActionPerformed(java.awt.event.ActionEvent evt) {
      //Connecting Device
 
        //create TCP_ISO_Device instance from PLCcomDevice
        Device = new TCP_ISO_Device("192.168.1.2", 0, 2, ePLCType.S7_300_400_compatibel);
        //or create MPI_Device instance from PLCcomDevice
        //Device = new MPI_Device("COM2", 0, 2, eBaudrate.b38400, eSpeed.Speed187k, ePLCType.S7_300_400_compatibel);
        //or create PPI_Device instance from PLCcomDevice
        //Device = new PPI_Device("COM2", 0, 2, eBaudrate.b9600, ePLCType.S7_200_compatibel);
         
        authentication.User("");//Enter User here
        authentication.Serial("");//Enter Serial here
         
        Device.setConnecttimeout(1000);
        Device.setReadtimeout(2000);
        ConnectResult res = Device.Connect();
         
        JOptionPane.showMessageDialog(null, res.Message(), "", JOptionPane.OK_CANCEL_OPTION);
    }
}
import PLCCom.*;
import javax.swing.JOptionPane;
 
public class NewClass {
 
    //declare the Device
    PLCcomDevice Device;
 
    private void btnConnectActionPerformed(java.awt.event.ActionEvent evt) {
      //Connecting Device
 
        //create TCP_ISO_Device instance from PLCcomDevice
        Device = new TCP_ISO_Device("192.168.1.2", 0, 2, ePLCType.S7_300_400_compatibel);
        //or create MPI_Device instance from PLCcomDevice
        //Device = new MPI_Device("COM2", 0, 2, eBaudrate.b38400, eSpeed.Speed187k, ePLCType.S7_300_400_compatibel);
        //or create PPI_Device instance from PLCcomDevice
        //Device = new PPI_Device("COM2", 0, 2, eBaudrate.b9600, ePLCType.S7_200_compatibel);
         
        authentication.User("");//Enter User here
        authentication.Serial("");//Enter Serial here
         
        Device.setConnecttimeout(1000);
        Device.setReadtimeout(2000);
        ConnectResult res = Device.Connect();
         
        JOptionPane.showMessageDialog(null, res.Message(), "", JOptionPane.OK_CANCEL_OPTION);
    }
}
2. Disconnect from PLC

untuk memutuskan koneksi ke PLC cukup dengan 1 baris perintah : Device.DisConnect();


3. Automatic connect to PLC

import PLCCom.*;
import javax.swing.JOptionPane;
 
public class NewClass {
 
    //declare the Device
    PLCcomDevice Device;
 
    private void btnConnectActionPerformed(java.awt.event.ActionEvent evt) {
      //Connecting Device
 
        //create TCP_ISO_Device instance from PLCcomDevice
        Device = new TCP_ISO_Device("192.168.1.2", 0, 2, ePLCType.S7_300_400_compatibel);
        //or create MPI_Device instance from PLCcomDevice
        //Device = new MPI_Device("COM2", 0, 2, eBaudrate.b38400, eSpeed.Speed187k, ePLCType.S7_300_400_compatibel);
        //or create PPI_Device instance from PLCcomDevice
        //Device = new PPI_Device("COM2", 0, 2, eBaudrate.b9600, ePLCType.S7_200_compatibel);
        //Enter User here
        authentication.User("");
        //Enter Serial here
        authentication.Serial("");
        Device.setConnecttimeout(1000);
        Device.setReadtimeout(2000);
         
        // Set Auto Connect State
        //The connection is opened automatically when it is needed. 
        //If after the expiry of the given period, no more requests are sent, the connection is automatically closed.
        Device.setAutoConnect(true, 10000));
    }
}


4. Simple reading data from PLC

import PLCCom.*;
 
 public class main {
 
   private void btnreadRawDataActionPerformed(java.awt.event.ActionEvent evt) {
    //set the request parameters
    //in this case => read 10 Bytes from DB1
    ReadDataRequest myReadDataRequest = new ReadDataRequest(eRegion.DataBlock,  //Region
                                                            1,                  //DB / only for datablock operations otherwise 0
                                                            0,                  //read start adress
                                                            eDataType.BYTE,     //desired datatype
                                                            10);                //Quantity of reading values
 
    //read from device
    System.out.println("begin Read...");
    ReadDataResult res = Device.readData(myReadDataRequest);
 
    //evaluate results
    if (res.Quality() == OperationResult.eQuality.GOOD) {
        int Position = 0;
        for (Object item : res.getValues()) {
            ystem.out.println("read Byte " + String.valueOf(Position) + " " + item.toString());
            Position++;
        }
    } else {
        System.out.println("read not successfull! Message: " + res.Message());
    }
 }
}



Reference : https://www.plccom.net/en/plccom/for-s7/fors7-code-examples/

Contoh Mengakses PLC Dengan Java - II

 


5. Simple writing data to PLC

using PLCcom.*;

     

        private PLCcomDevice Device;

        //see section 'connect' for declare and connect a PLCcom-Device

 

        private void btnWrite_Click(object sender, EventArgs e)

        {

             

             

            WriteDataRequest myWriteRequest = new WriteDataRequest(eRegion.DataBlock,       // Region

                                            Integer.valueOf(100),           // DB / only for data block operations  otherwise 0

                                            Integer.valueOf(0),     // write start address

                                            Byte.valueOf(txtBit.getText()));            // Bit/only for bit operations

             

            //set the request parameters 

            //write 4 bytes in DB100

            WriteRequest[] myWriteRequest = new WriteRequest[1];

            myWriteRequest[0] = new WriteRequest();

 

            //add writable Data here

            myWriteRequest.addByte(new byte[] { 11, 12, 13, 14 });

            //write

            WriteDataResult res = Device.writeData(myWriteRequest);

 

            //evaluate results

            txtMessage.Text = DateTime.Now.ToString() + ": " + res[0].Message;

            if (res[0].Quality.Equals(OperationResult.eQuality.GOOD))

            {

                MessageBox.Show("OK", "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }

            else

            {

                MessageBox.Show(res[0].Message, "Result:", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }

        }


6. Optimized reading and writing of data

import PLCCom.*;

 

 public class main {

 //declare the Device

 private PLCcomDevice Device; //see section 'connect' for declare and connect a PLCcom-Device

 

    private void btnOptReadWriteActionPerformed(java.awt.event.ActionEvent evt) {

 

        ReadWriteRequestSet myRequestSet = new ReadWriteRequestSet();

         

        //set optimize options

        myRequestSet.setOperationOrder(eOperationOrder.WRITE_BEVOR_READ);

        myRequestSet.setReadOptimizationMode(eReadOptimizationMode.AUTO);

        myRequestSet.setWriteOptimizationMode(eWriteOptimizationMode.CROSS_AREAS);

         

         

        // declare a ReadRequest object set the request parameters, 

        //in this case => read 10 Bytes from DB1 at Byte 0

        ReadDataRequest myReadDataRequest = new ReadDataRequest(eRegion.DataBlock, // Region

                1, // DB only for datablock operations otherwise 0

                0, // read start adress

                eDataType.BYTE, // desired datatype

                10); // Quantity of reading values

         

        // add the read request to the request set

        myRequestSet.addRequest(myReadDataRequest);

         

        // declare a WriteRequest object set the request parameters, 

        //in this case => write 4 bytes to DB100 at address 0

        WriteDataRequest myWriteRequest = new WriteDataRequest(eRegion.DataBlock, // Region

                100, // DB

                0); // startaddress

         

        // add writable Data here

        // in this case => write 4 bytes in DB100

        myWriteRequest.addByte(new byte[] { 11, 12, 13, 14 });

         

        // add the write request to the request set

        myRequestSet.addRequest(myWriteRequest);

         

        // ....... add more requests to request set

         

        // read, write and getting the results

        ReadWriteResultSet results = Device.readWriteData(myRequestSet);

         

        // evaluate the results of read operations...

        for (ReadDataResult res : results.getReadDataResults()) {

            // for getting read results see chapter simple read

        }

         

        // ...and evaluate the results of write operations

        for (WriteDataResult res : results.getWriteDataResults()) {

            // for getting write results see chapter simple write

        }

 

    }

 }


7. Get basic info from PLC

import PLCCom.*;

import javax.swing.JOptionPane;

 

public class NewClass {

 

    PLCcomDevice Device;

    //see section 'connect' for declare and connect a PLCcom-Device

 

    private void btngetPLCBasicInfoActionPerformed(java.awt.event.ActionEvent evt) {

        //execute function

        BasicInfoResult res = Device.GetBasicInfo();

 

        //evaluate results

        if (res.Quality().equals(OperationResult.eQuality.GOOD)) {

            StringBuilder sb = new StringBuilder();

            sb.append("Device Name: ");

            sb.append(res.Name());

            sb.append(System.getProperty("line.separator"));

            sb.append("Order Number: ");

            sb.append(res.Ordernumber());

            sb.append(System.getProperty("line.separator"));

            sb.append("Module Version: ");

            sb.append(res.ModuleVersion());

            sb.append(System.getProperty("line.separator"));

            sb.append("Firmware Version: ");

            sb.append(res.FirmwareVersion());

            sb.append(System.getProperty("line.separator"));

            JOptionPane.showMessageDialog(null, "OK", "", JOptionPane.INFORMATION_MESSAGE);

        } else {

            JOptionPane.showMessageDialog(null, res.Message(), "", JOptionPane.ERROR_MESSAGE);

        }

    }

}



8. Get mode and state from CPU

import PLCCom.*;

import javax.swing.JOptionPane;

 

public class NewClass {

 

    PLCcomDevice Device;

    //see section 'connect' for declare and connect a PLCcom-Device

 

    private void btngetCPUModeActionPerformed(java.awt.event.ActionEvent evt) {

        //execute function

        CPUModeInfoResult res = Device.GetCPUMode();

 

        //evaluate results

        if (res.Quality().equals(OperationResult.eQuality.GOOD)) {

            StringBuilder sb = new StringBuilder();

            sb.append("CPU Mode = ");

            sb.append(String.valueOf(res.CPUModeInfo()));

            sb.append(System.getProperty("line.separator"));

            sb.append("CPU State = ");

            sb.append(String.valueOf(res.CPUStateInfo()));

            JOptionPane.showMessageDialog(null, "OK", "", JOptionPane.INFORMATION_MESSAGE);

        } else {

            JOptionPane.showMessageDialog(null, res.Message(), "", JOptionPane.ERROR_MESSAGE);

        }

    }

}



Reference : https://www.plccom.net/en/plccom/for-s7/fors7-code-examples/


Thursday, January 26, 2023

Belajar Mysql - Pembuatan Event ( Schedule )

 


Event merupakan pembuatan dan menjadwalkan proses yang akan dilakukan. Ini membutuhkan hak istimewa EVENT untuk skema di mana acara akan dibuat (dan mungkin SUPER bergantung pada nilai DEFINER. Proses tidak akan berjalan kecuali Penjadwal diaktifkan. 

Untuk mengaktifkan supaya event bisa digunakan adalah :

1. Mengaktifkan

SET GLOBAL event_scheduler = ON;

SET @@global.event_scheduler = ON;

SET GLOBAL event_scheduler = 1;

SET @@global.event_scheduler = 1;

2. Men-Aktifkan 

SET GLOBAL event_scheduler = OFF;

SET @@global.event_scheduler = OFF;

SET GLOBAL event_scheduler = 0;

SET @@global.event_scheduler = 0;



1. Membuat Event

Format :

CREATE  [DEFINER = { user | CURRENT_USER }]

    EVENT  [IF NOT EXISTS]

    event_name  ON SCHEDULE schedule

    [ON COMPLETION [NOT] PRESERVE]

    [ENABLE | DISABLE | DISABLE ON SLAVE]

    [COMMENT 'comment']

    DO sql_statement;

schedule:

    AT timestamp [+ INTERVAL interval] ...

  | EVERY interval

    [STARTS timestamp [+ INTERVAL interval] ...]

    [ENDS timestamp [+ INTERVAL interval] ...]

interval:

    quantity {YEAR | QUARTER | MONTH | DAY | HOUR | MINUTE |

              WEEK | SECOND | YEAR_MONTH | DAY_HOUR | DAY_MINUTE |

              DAY_SECOND | HOUR_MINUTE | HOUR_SECOND | MINUTE_SECOND}


Contoh 1 :

CREATE EVENT evtData     ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 HOUR

    DO  UPDATE myschema.mytable SET mycol = mycol + 1;


Contoh 2 :

CREATE EVENT evtData 

    ON SCHEDULE

      EVERY 6 HOUR

    COMMENT 'A sample comment.'

    DO

      UPDATE myschema.mytable SET mycol = mycol + 1;


2. Mengubah Event

Format :

ALTER  [DEFINER = { user | CURRENT_USER }]

    EVENT event_name

    [ON SCHEDULE schedule]

    [ON COMPLETION [NOT] PRESERVE]

    [RENAME TO new_event_name]

    [ENABLE | DISABLE | DISABLE ON SLAVE]

    [COMMENT 'comment']

    [DO event_body]


Contoh :

2.1. Mengubah jam

ALTER EVENT evtData

    ON SCHEDULE

      EVERY 12 HOUR

    STARTS CURRENT_TIMESTAMP + INTERVAL 4 HOUR;


2.2.Mengubah hari

ALTER TABLE evtData

    ON SCHEDULE

      AT CURRENT_TIMESTAMP + INTERVAL 1 DAY

    DO

      TRUNCATE TABLE myschema.mytable;


2.3. Menonaktifkan

ALTER EVENT myevent

    DISABLE;


2.4. Menganti nama 

ALTER EVENT myevent

    RENAME TO yourevent;


2.5. mengarahkan ke database lain

ALTER EVENT olddb.myevent

    RENAME TO newdb.myevent;



3. Menghapus Event

Format :

DROP EVENT [IF EXISTS] event_name


Contoh :

DROP EVENT evtData;


Belajar Mysql - Pembuatan View, Index

 



1. View

1. 1. Membuat View

Format :

CREATE   [OR REPLACE]

    [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}]

    [DEFINER = { user | CURRENT_USER }]

    [SQL SECURITY { DEFINER | INVOKER }]

    VIEW view_name [(column_list)]

    AS select_statement

    [WITH [CASCADED | LOCAL] CHECK OPTION]


Contoh :

CREATE VIEW vTblA (mycol) AS SELECT * From TblA;


1.2. Mengubah View

Format :

ALTER

    [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}]

    [DEFINER = { user | CURRENT_USER }]

    [SQL SECURITY { DEFINER | INVOKER }]

    VIEW view_name [(column_list)]

    AS select_statement

    [WITH [CASCADED | LOCAL] CHECK OPTION]


Contoh :

ALTER VIEW vTblA (mycol) AS SELECT kode, nama From TblA;


1.3. Menghapus View

Format :

DROP VIEW [IF EXISTS]

    view_name [, view_name] ...

    [RESTRICT | CASCADE]


Contoh :

DROP VIEW vTblA;


2.  Index

2.1. Membuat Index

Format :

CREATE [ONLINE|OFFLINE] [UNIQUE|FULLTEXT|SPATIAL] INDEX index_name

    [index_type]

    ON tbl_name (index_col_name,...)

    [index_option] ...

index_col_name:

    col_name [(length)] [ASC | DESC]

index_type:

    USING {BTREE | HASH | RTREE}

index_option:

    KEY_BLOCK_SIZE [=] value

  | index_type

  | WITH PARSER parser_name


Contoh :

CREATE TABLE lookup (id INT) ENGINE = MEMORY;

CREATE INDEX idxData USING BTREE ON tblA (id);


2.2.  Menghapus Index

Format :

DROP INDEX index_name ON tbl_name

    [algorithm_option | lock_option] ...

algorithm_option:

    ALGORITHM [=] {DEFAULT|INPLACE|COPY}

lock_option:

    LOCK [=] {DEFAULT|NONE|SHARED|EXCLUSIVE}


Contoh :

DROP INDEX `PRIMARY` ON idxData;


Belajar Mysql - Pembuatan Server



Definisi server digunakan dengan mesin penyimpanan FEDERATED. Pernyataan CREATE SERVER membuat baris baru di dalam tabel server di dalam database mysql. Pernyataan ini membutuhkan hak istimewa SUPER.

Nama server harus menjadi referensi unik ke server. Definisi server bersifat global dalam lingkup server, tidak mungkin untuk memenuhi syarat definisi server ke database tertentu. nama server memiliki panjang maksimum 64 karakter (nama yang lebih panjang dari 64 karakter akan dipotong secara diam-diam), dan tidak peka huruf besar-kecil. Anda dapat menentukan nama sebagai string yang dikutip. Untuk setiap opsi, Anda harus menentukan karakter literal atau numerik literal. Literal karakter adalah UTF-8, mendukung panjang maksimal 64 karakter dan standarnya adalah string kosong (kosong). String literal dipotong secara diam-diam menjadi 64 karakter. Literal numerik harus berupa angka antara 0 dan 9999, nilai defaultnya adalah 0.

1. Membuat Server

Format :

CREATE SERVER server_name

    FOREIGN DATA WRAPPER wrapper_name

    OPTIONS (option [, option] ...)

option:

  { HOST character-literal

  | DATABASE character-literal

  | USER character-literal

  | PASSWORD character-literal

  | SOCKET character-literal

  | OWNER character-literal

  | PORT numeric-literal }


Contoh :

CREATE SERVER sData

FOREIGN DATA WRAPPER mysql

OPTIONS (USER 'Remote', HOST '192.168.1.106', DATABASE 'dbData');


CREATE TABLE t (s1 INT) ENGINE=FEDERATED CONNECTION='sData';


2. Mengubah Server

Format :

ALTER SERVER  server_name

    OPTIONS (option [, option] ...)


Contoh :

ALTER SERVER sData OPTIONS (USER 'Remote');


3. Menghapus Server

Format :

DROP SERVER [ IF EXISTS ] server_name


Contoh :

DROP SERVER [ IF EXISTS ] sData'


Memunculkan Simbol & Emoji Pada OS Mac

  Memunculkan Simbol & Emoji  1. Buka aplikasi Pages / Notes pada Macbook. 2. Klik pada Menubar Edit --> Pilih Emoji and Symbols a...