connectors/ERPC/PSK_Adapter.py
author Edouard Tisserant <edouard@beremiz.fr>
Thu, 05 Dec 2024 13:56:59 +0100
changeset 4060 d2f5eb3c7d6e
parent 3908 32eb6e05008a
permissions -rw-r--r--
py_ext: fix CSV Writer

fix POU logic :
- SAVE is a BOOL
- invocation of py_eval on rising edge of SAVE
- remove save python argument

fix python:
- use no encoding for file open (python2)
- re-use detected dialect if any
- use no "rt+" and truncate since no need to re-sniff dialect for output file
- return "OK" instead of "#SUCCESS", preventing POU logic to ACK result
- support creating new line if writing just after last line
- support appending data on short rows

fix example:
- use a HMI:Button to trigger CSV write instead of HMI:Input +1
- reload CSVs on on each new CSV opened in file browser
- add display of CSV write output
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Written by Edouard TISSERANT (C) 2024
# This file is part of Beremiz IDE
# See COPYING file for copyrights details.


"""
The TLS-PSK adapter that handles SSL connections instead of regular sockets,
but using Pre Shared Keys instead of Certificates

Corresponding stunnel.conf on PLC side:

    [ERPCPSK]
    accept = 4000
    connect = 127.0.0.1:3000
    ciphers = PSK
    sslVersion = TLSv1.2
    PSKsecrets = psk.txt

"""

import socket
import ssl

try:
    import sslpsk
except ImportError as e:
    sslpsk = None

from erpc.transport import TCPTransport

class SSLPSKClientTransport(TCPTransport):
    def __init__(self, host, port, psk):
        """ overrides TCPTransport's __init__ to wrap socket in SSl wrapper """
        super(TCPTransport, self).__init__()
        self._host = host
        self._port = port
        self._sock = None
        self._isServer = False

        if sslpsk is None:
             raise ImportError("sslpsk module is not available")

        self.sslpskctx = sslpsk.SSLPSKContext(ssl.PROTOCOL_TLSv1_2)
        self.sslpskctx.set_ciphers('PSK')
        self.sslpskctx.psk = psk
        
        raw_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        raw_sock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)
        raw_sock.connect((self._host, self._port))

        self._sock = self.sslpskctx.wrap_socket(raw_sock, server_side=False)