def write_coils(self, coil_start_address, write_values):
        """ Modbus command : write multiple coils data (function code = 15)

            @Argument :
            coil_start_address (int16) : Coil start address where to write a set of coils data
            write_values (int)    : write value(s) (list-type)
        """

        # Generate modbus TCP message
        try:
            message = modbus_tcp.write_multiple_coils(
                slave_id=self.device_id,
                starting_address=coil_start_address,
                values=write_values)
        except Exception as e:
            print("Error during generate modbus message.")

        # Send message via TCP socket
        try:
            self._connect()
            response = modbus_tcp.send_message(message, self.tcp_socket)
            print("response={}".format(response))
            self._disconnect()
        except Exception as e:
            print("Error during send modbus message.")
            print(e)
예제 #2
0
    def turn_on_room_heating(self, kw: float):
        sums: dict = self.get_possible_sums()
        powers: List[float] = []
        for key in sums:
            if len(powers) == 0:
                powers = sums[key]
            elif sums[key] == kw:
                powers = sums[key]
                break
            elif abs(kw - self.sum_of_powers(sums[key])) < abs(
                    kw - self.sum_of_powers(powers)) and kw - self.sum_of_powers(sums[key]) > 0:
                powers = sums[key]

        for pow in powers:
            self.room_heating[constants.heat_power_per_room.index(pow)] = True
            message = tcp.write_multiple_coils(slave_id=1, starting_address=1,
                                               values=self.room_heating)
            print(tcp.send_message(message, sockRoom))
예제 #3
0
#!/usr/bin/env python
# scripts/examples/simple_client.py
import socket

from umodbus import conf
from umodbus.client import tcp

# Enable values to be signed (default is False).
conf.SIGNED_VALUES = True

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', 502))

# Returns a message or Application Data Unit (ADU) specific for doing
# Modbus TCP/IP.
message = tcp.write_multiple_coils(slave_id=1, address=1, values=[1, 0, 1, 1])

# Response depends on Modbus function code. This particular returns the
# amount of coils written, in this case it isr3.
response = tcp.send_message(message, sock)

sock.close()
예제 #4
0
 def writeBits(self,address,values):
     message = tcp.write_multiple_coils(self.slaveNbr, address, values)
     response = self.__doRequest(message)
     return response
예제 #5
0
#!/usr/bin/env python
# scripts/examples/simple_tcp_client.py
import socket

from umodbus import conf
from umodbus.client import tcp

# Enable values to be signed (default is False).
conf.SIGNED_VALUES = True

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', 502))

# Returns a message or Application Data Unit (ADU) specific for doing
# Modbus TCP/IP.
message = tcp.write_multiple_coils(slave_id=1,
                                   starting_address=1,
                                   values=[1, 0, 1, 1])

# Response depends on Modbus function code. This particular returns the
# amount of coils written, in this case it is.
response = tcp.send_message(message, sock)

sock.close()
예제 #6
0
import socket

from umodbus import conf
from umodbus.client import tcp

conf.SIGNED_VALUES = True

sockWater = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sockWater.connect(('localhost', 501))
message = tcp.write_multiple_coils(slave_id=1, starting_address=0, values=[False])
tcp.send_message(message, sockWater)
sockWater.close()

sockRoom = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sockRoom.connect(('localhost', 500))
message = tcp.write_multiple_coils(slave_id=1, starting_address=1, values=[False, False,False, False,False, False,False])
tcp.send_message(message, sockRoom)
sockRoom.close()
def main():
    host, port = '10.8.8.20', 502
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((host, port))

    iv = 'nvXIK5RtUZpZQdJD'
    helloMsgClient = 'client'
    helloMsgServer = 'server'
    clientkey = RSA.generate(2048)
    clientpukey = clientkey.publickey().exportKey('PEM').decode('ascii')
    clientprkey = clientkey.exportKey('PEM').decode('ascii')
    print('\nClient Public Key:\n\n', clientpukey,
          '\n\n\nClient Private Key:\n\n', clientprkey)
    sign = signData(helloMsgClient.encode(), clientprkey)
    print("\n\nSign:\n\n", sign)
    message = str(clientpukey) + ";" + str(sign)
    print("\n\nRSA Message:\n\n", message)
    sock.sendall(message.encode())

    rsaResponse = sock.recv(3072).strip()
    rsaMsg = rsaResponse.decode()
    serverpukey = rsaMsg.split(';')[0]
    signRcvd = rsaMsg.split(';')[1]
    verify = verifySign(helloMsgServer.encode(), serverpukey, signRcvd)
    if verify:
        print("\n\n---------Received Server RSA Public Key---------\n")
    else:
        raise Exception(
            "\nClient Authentication Failure. RSA public key and sign don't match"
        )
    print('\nRSA Server Public Key:\n\n', serverpukey)

    print(
        "\n\n****************************RSA Exchange Completes and Authentication Done***************************"
    )
    received = sock.recv(3072).strip()
    #print('\nDH key Received:\n{}'.format(received))
    dh_params = load_pem_parameters(received, default_backend())

    if isinstance(dh_params, dh.DHParameters):
        client_keypair = dh_params.generate_private_key()
        request = b'Client public key:' + client_keypair.public_key(
        ).public_bytes(Encoding.PEM, PublicFormat.SubjectPublicKeyInfo)
        sock.sendall(request)
        #print('\nreq',request)
    else:
        print('Bad response')
        sock.close()
        return

    # this means we are still in the game
    received = sock.recv(3072).strip()
    #print('Received:\n{}'.format(received))
    print(
        "\n\n****************************Received Server's public Key****************************\n"
    )
    # check the format of the message (or rather the beginning)
    if bytearray(received)[0:18] == b'Server public key:':
        # get the server's public key from the binary and its proper index to the end
        server_pubkey = load_pem_public_key(bytes(bytearray(received)[18:]),
                                            default_backend())
        if isinstance(server_pubkey, dh.DHPublicKey):
            # calculate the shared secret
            session_key = client_keypair.exchange(server_pubkey)
            # print the shared secret
            #print('Shared Secret\n{}'.format(ba.hexlify(session_key)))
            print(
                "\n****************************Shared Secret key is generated***************************\n"
            )
            print(
                "\n**********************DH Exchange Completes and Session Established**********************"
            )

    conf.SIGNED_VALUES = True
    obtained_key = hkdf_function(session_key)
    print('\n\nDerived Key:\t\t-------->\t', (obtained_key))
    message = tcp.write_multiple_coils(slave_id=1,
                                       starting_address=1,
                                       values=[0, 0, 1, 1, 1])
    digest = getHash(message)
    #print("\n\ndigest_str: ",digest)
    cipher = aes_cbc_encrypt(message, obtained_key, iv, digest)
    print('\nMessage:\t\t-------->\t', (message), type(message))
    print('\nCipher:\t\t\t-------->\t', (cipher), type(cipher))
    #print('derived-------->',obtained_key)
    sock.sendall(cipher.encode('utf-8'))

    mb_responce = sock.recv(1024)
    mb_responce, digest = aes_decrypt(mb_responce, obtained_key, iv)
    localDigest = getHash(mb_responce)
    verify = verifyHash(digest, localDigest)
    if verify == True:
        print("\nResponse:\t\t-------->\t", (mb_responce))
        responce = tcp.parse_response_adu(mb_responce, message)
        print('\nParsed Response:\t-------->\t', (responce))

        message = tcp.read_coils(slave_id=1, starting_address=1, quantity=5)
        print('\n\n\nSecond Message:\t\t-------->\t', (message))
        print('\nMessage(Hexa format):\t-------->\t', (ba.b2a_hex(message)))
        digest = getHash(message)
        cipher = aes_cbc_encrypt(message, obtained_key, iv, digest)
        print('\nCipher:\t\t\t-------->\t', (cipher))

        sock.sendall(cipher.encode('utf-8'))
        mb_responce = sock.recv(1024)
        mb_responce, digest = aes_decrypt(mb_responce, obtained_key, iv)
        localDigest = getHash(mb_responce)
        verify = verifyHash(digest, localDigest)
        if verify == True:
            print("\nResponse:\t\t-------->\t", (mb_responce))
            responce = tcp.parse_response_adu(mb_responce, message)
            print('\nParsed Response:\t-------->\t', (responce))

    #iv11 = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for x in range(16))
    #print('iv11',iv11)

    sock.close()
예제 #8
0
 def room_heating_off(self):
     message = tcp.write_multiple_coils(slave_id=1, starting_address=1,
                                        values=[False, False, False, False, False, False, False])
     tcp.send_message(message, sockRoom)
     self.room_heating = [False, False, False, False, False, False, False]
예제 #9
0
 def water_heater_on_off(self, state: bool):
     message = tcp.write_multiple_coils(slave_id=1, starting_address=1, values=state)
     self.water_heating = bool(tcp.send_message(message, sockWater))