Last active
September 7, 2021 23:27
-
-
Save itsecurityco/5a3f6f486fc2a413e62cdcd0052fc686 to your computer and use it in GitHub Desktop.
Simple Kotlin application to communicate with a PLC via Modbus
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* @author: Juan Escobar ([email protected]) */ | |
package net.dreamlab.modbuscoils | |
import androidx.appcompat.app.AppCompatActivity | |
import android.os.Bundle | |
import android.os.StrictMode | |
import android.util.Log | |
import android.view.View | |
import io.ktor.network.selector.* | |
import io.ktor.network.sockets.* | |
import io.ktor.utils.io.* | |
import kotlinx.coroutines.Dispatchers | |
import kotlinx.coroutines.runBlocking | |
import java.net.InetSocketAddress | |
class MainActivity : AppCompatActivity() { | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.activity_main) | |
StrictMode.setThreadPolicy( | |
StrictMode.ThreadPolicy.Builder().permitAll().build()) | |
} | |
/* https://stackoverflow.com/a/51404278/2067290 */ | |
private fun byteArrayOfInts(vararg ints: Int) = ByteArray(ints.size) { pos -> ints[pos].toByte() } | |
/* Called when the user taps the ON button */ | |
fun turnOnLight(view: View) { | |
runBlocking { | |
val socket = aSocket(ActorSelectorManager(Dispatchers.IO)).tcp().connect(InetSocketAddress("plc_address", 502)) | |
val output = socket.openWriteChannel(autoFlush = true) | |
val packet = byteArrayOfInts(0x00,0x01,0x00,0x00,0x00,0x06,0xff,0x05,0x00,0x00,0xff,0x00) | |
output.writeFully(packet) | |
socket.close() | |
} | |
} | |
/* Called when the user taps the OFF button */ | |
fun turnOffLight(view: View) { | |
runBlocking { | |
val socket = aSocket(ActorSelectorManager(Dispatchers.IO)).tcp().connect(InetSocketAddress("ip_address", 502)) | |
val output = socket.openWriteChannel(autoFlush = true) | |
val packet = byteArrayOfInts(0x00,0x01,0x00,0x00,0x00,0x06,0xff,0x05,0x00,0x00,0x00,0x00) | |
output.writeFully(packet) | |
socket.close() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment