Beremiz_service.py
author Edouard Tisserant <edouard@beremiz.fr>
Fri, 28 Feb 2025 16:53:33 +0100 (3 weeks ago)
changeset 4124 6220f357a726
parent 4121 ef48f96ccf06
permissions -rwxr-xr-x
IDE: enforce CRA to WAMP connector, using known PSK as credentials. TLS support is WIP.
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
     1
#!/usr/bin/env python
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
     2
# -*- coding: utf-8 -*-
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
     3
1571
486f94a8032c fix license notices in source files and license files under GPLv2+
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1458
diff changeset
     4
# This file is part of Beremiz, a Integrated Development Environment for
486f94a8032c fix license notices in source files and license files under GPLv2+
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1458
diff changeset
     5
# programming IEC 61131-3 automates supporting plcopen standard and CanFestival.
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
     6
#
1571
486f94a8032c fix license notices in source files and license files under GPLv2+
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1458
diff changeset
     7
# Copyright (C) 2007: Edouard TISSERANT and Laurent BESSARD
1680
6db967480b7d make run Beremiz and PLCOpen Editor, if full path contain non-lating
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1598
diff changeset
     8
# Copyright (C) 2017: Andrey Skvortsov
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
     9
#
1571
486f94a8032c fix license notices in source files and license files under GPLv2+
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1458
diff changeset
    10
# See COPYING file for copyrights details.
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
    11
#
1571
486f94a8032c fix license notices in source files and license files under GPLv2+
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1458
diff changeset
    12
# This program is free software; you can redistribute it and/or
486f94a8032c fix license notices in source files and license files under GPLv2+
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1458
diff changeset
    13
# modify it under the terms of the GNU General Public License
486f94a8032c fix license notices in source files and license files under GPLv2+
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1458
diff changeset
    14
# as published by the Free Software Foundation; either version 2
486f94a8032c fix license notices in source files and license files under GPLv2+
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1458
diff changeset
    15
# of the License, or (at your option) any later version.
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
    16
#
1571
486f94a8032c fix license notices in source files and license files under GPLv2+
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1458
diff changeset
    17
# This program is distributed in the hope that it will be useful,
486f94a8032c fix license notices in source files and license files under GPLv2+
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1458
diff changeset
    18
# but WITHOUT ANY WARRANTY; without even the implied warranty of
486f94a8032c fix license notices in source files and license files under GPLv2+
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1458
diff changeset
    19
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
486f94a8032c fix license notices in source files and license files under GPLv2+
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1458
diff changeset
    20
# GNU General Public License for more details.
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
    21
#
1571
486f94a8032c fix license notices in source files and license files under GPLv2+
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1458
diff changeset
    22
# You should have received a copy of the GNU General Public License
486f94a8032c fix license notices in source files and license files under GPLv2+
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1458
diff changeset
    23
# along with this program; if not, write to the Free Software
486f94a8032c fix license notices in source files and license files under GPLv2+
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1458
diff changeset
    24
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
    25
1826
91796f408540 fix usage of python2-only print statement
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1790
diff changeset
    26
1732
94ffe74e6895 clean-up: fix PEP8 E401 multiple imports on one line
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1730
diff changeset
    27
import os
94ffe74e6895 clean-up: fix PEP8 E401 multiple imports on one line
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1730
diff changeset
    28
import sys
94ffe74e6895 clean-up: fix PEP8 E401 multiple imports on one line
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1730
diff changeset
    29
import getopt
1783
3311eea28d56 clean-up: fix PEP8 E402 module level import not at top of file
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1780
diff changeset
    30
import threading
2644
769fefae7c81 Add --on-plc-start --on-plc-stop and --status-change to runtime command line, calling given command respectively on start stop or any event. Command line string is python formated (to eventually include status with {}) before being split (supports quoted strings) and passed to Popen for non-blocking execution.
Edouard Tisserant
parents: 2601
diff changeset
    31
import shlex
3282
725d3e9ac913 Runtime: Handle errors in user's python code more gracefully : make exceptions and allow repair.
Edouard Tisserant
parents: 2738
diff changeset
    32
import traceback
3420
da8cceaa247d Runtime : force using monotonic time in Timer (threading). Prevent watchdog to trigger when changing system time.
Edouard Tisserant
parents: 3282
diff changeset
    33
import threading
3800
a5a6ee271e65 WIP python3 support for runtime
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3793
diff changeset
    34
from threading import Thread, Semaphore, Lock, current_thread
3752
9f6f46dbe3ae removed Python2 modules
GP Orcullo <kinsamanka@gmail.com>
parents: 3750
diff changeset
    35
import builtins
3585
efdefbad49eb runtime: fix bugs introduced in previous commit, and refactor some code
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3584
diff changeset
    36
from functools import partial
2270
d9175daf6522 Refactoring. Separated PLC Object, PYRO Server and MainWorker :
Edouard Tisserant
parents: 2249
diff changeset
    37
d9175daf6522 Refactoring. Separated PLC Object, PYRO Server and MainWorker :
Edouard Tisserant
parents: 2249
diff changeset
    38
import runtime
3884
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
    39
from runtime.eRPCServer import eRPCServer as RPCServer
2000
9fa2f8ede5d6 Fixed random segfault happening when loading new PLC in runtime, when using Xenonai.
Edouard Tisserant
parents: 1999
diff changeset
    40
from runtime.xenomai import TryPreloadXenomai
2270
d9175daf6522 Refactoring. Separated PLC Object, PYRO Server and MainWorker :
Edouard Tisserant
parents: 2249
diff changeset
    41
from runtime import LogMessageAndException
2416
1ca207782dde Use predefined constants for PlcStatus instead of string literals
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 2349
diff changeset
    42
from runtime import PlcStatus
2585
fc6f441582cb Now default_evaluator is provided by runtime package
Edouard Tisserant
parents: 2537
diff changeset
    43
from runtime import default_evaluator
2492
7dd551ac2fa0 check_sources.sh makes me become even less productive
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 2489
diff changeset
    44
from runtime.Stunnel import ensurePSK
1783
3311eea28d56 clean-up: fix PEP8 E402 module level import not at top of file
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1780
diff changeset
    45
import util.paths as paths
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
    46
3420
da8cceaa247d Runtime : force using monotonic time in Timer (threading). Prevent watchdog to trigger when changing system time.
Edouard Tisserant
parents: 3282
diff changeset
    47
# In case system time is ajusted, it is better to use
da8cceaa247d Runtime : force using monotonic time in Timer (threading). Prevent watchdog to trigger when changing system time.
Edouard Tisserant
parents: 3282
diff changeset
    48
# monotonic timers for timers and other timeout based operations.
da8cceaa247d Runtime : force using monotonic time in Timer (threading). Prevent watchdog to trigger when changing system time.
Edouard Tisserant
parents: 3282
diff changeset
    49
# hot-patch threading module to force using monitonic time for all 
da8cceaa247d Runtime : force using monotonic time in Timer (threading). Prevent watchdog to trigger when changing system time.
Edouard Tisserant
parents: 3282
diff changeset
    50
# Thread/Timer/Event/Condition
da8cceaa247d Runtime : force using monotonic time in Timer (threading). Prevent watchdog to trigger when changing system time.
Edouard Tisserant
parents: 3282
diff changeset
    51
da8cceaa247d Runtime : force using monotonic time in Timer (threading). Prevent watchdog to trigger when changing system time.
Edouard Tisserant
parents: 3282
diff changeset
    52
from runtime.monotonic_time import monotonic
da8cceaa247d Runtime : force using monotonic time in Timer (threading). Prevent watchdog to trigger when changing system time.
Edouard Tisserant
parents: 3282
diff changeset
    53
threading._time = monotonic
da8cceaa247d Runtime : force using monotonic time in Timer (threading). Prevent watchdog to trigger when changing system time.
Edouard Tisserant
parents: 3282
diff changeset
    54
2644
769fefae7c81 Add --on-plc-start --on-plc-stop and --status-change to runtime command line, calling given command respectively on start stop or any event. Command line string is python formated (to eventually include status with {}) before being split (supports quoted strings) and passed to Popen for non-blocking execution.
Edouard Tisserant
parents: 2601
diff changeset
    55
try:
769fefae7c81 Add --on-plc-start --on-plc-stop and --status-change to runtime command line, calling given command respectively on start stop or any event. Command line string is python formated (to eventually include status with {}) before being split (supports quoted strings) and passed to Popen for non-blocking execution.
Edouard Tisserant
parents: 2601
diff changeset
    56
    from runtime.spawn_subprocess import Popen
769fefae7c81 Add --on-plc-start --on-plc-stop and --status-change to runtime command line, calling given command respectively on start stop or any event. Command line string is python formated (to eventually include status with {}) before being split (supports quoted strings) and passed to Popen for non-blocking execution.
Edouard Tisserant
parents: 2601
diff changeset
    57
except ImportError:
769fefae7c81 Add --on-plc-start --on-plc-stop and --status-change to runtime command line, calling given command respectively on start stop or any event. Command line string is python formated (to eventually include status with {}) before being split (supports quoted strings) and passed to Popen for non-blocking execution.
Edouard Tisserant
parents: 2601
diff changeset
    58
    from subprocess import Popen
1736
7e61baa047f0 clean-up: fix PEP8 E302 expected 2 blank lines, found 1
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1734
diff changeset
    59
2294
da288f63612f Make Beremiz_service print version information
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 2249
diff changeset
    60
def version():
da288f63612f Make Beremiz_service print version information
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 2249
diff changeset
    61
    from version import app_version
da288f63612f Make Beremiz_service print version information
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 2249
diff changeset
    62
    print("Beremiz_service: ", app_version)
da288f63612f Make Beremiz_service print version information
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 2249
diff changeset
    63
da288f63612f Make Beremiz_service print version information
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 2249
diff changeset
    64
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
    65
def usage():
2294
da288f63612f Make Beremiz_service print version information
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 2249
diff changeset
    66
    version()
1826
91796f408540 fix usage of python2-only print statement
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1790
diff changeset
    67
    print("""
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
    68
Usage of Beremiz PLC execution service :\n
644
b511cab580eb Better naming of IP address related variables in Beremiz_service.py, Ignore errors that occur on shutdown in Zeroconf.py, fixed discovery dialog crash due to asynchronous call from zeroconf
Edouard Tisserant
parents: 641
diff changeset
    69
%s {[-n servicename] [-i IP] [-p port] [-x enabletaskbar] [-a autostart]|-h|--help} working_dir
2323
33a0dbabccd3 Runtime : Ensure that a random PSK secret compatible with stunnel is generated if -s commandline switch is used. Stunnel service is restarted after generation, using spawn_subprocess. TODO : give stunnel restart command as a commandline parameter.
Edouard Tisserant
parents: 2321
diff changeset
    70
  -n  service name (default:None, zeroconf discovery disabled)
2221
e03f7649bfb3 WAMP: now config and secret given in project files always override those given in commandline. Also made extensions web customisations happen before registration of web interface.
Edouard Tisserant
parents: 2220
diff changeset
    71
  -i  IP address of interface to bind to (default:localhost)
e03f7649bfb3 WAMP: now config and secret given in project files always override those given in commandline. Also made extensions web customisations happen before registration of web interface.
Edouard Tisserant
parents: 2220
diff changeset
    72
  -p  port number default:3000
e03f7649bfb3 WAMP: now config and secret given in project files always override those given in commandline. Also made extensions web customisations happen before registration of web interface.
Edouard Tisserant
parents: 2220
diff changeset
    73
  -h  print this help text and quit
e03f7649bfb3 WAMP: now config and secret given in project files always override those given in commandline. Also made extensions web customisations happen before registration of web interface.
Edouard Tisserant
parents: 2220
diff changeset
    74
  -a  autostart PLC (0:disable 1:enable) (default:0)
e03f7649bfb3 WAMP: now config and secret given in project files always override those given in commandline. Also made extensions web customisations happen before registration of web interface.
Edouard Tisserant
parents: 2220
diff changeset
    75
  -x  enable/disable wxTaskbarIcon (0:disable 1:enable) (default:1)
e03f7649bfb3 WAMP: now config and secret given in project files always override those given in commandline. Also made extensions web customisations happen before registration of web interface.
Edouard Tisserant
parents: 2220
diff changeset
    76
  -t  enable/disable Twisted web interface (0:disable 1:enable) (default:1)
e03f7649bfb3 WAMP: now config and secret given in project files always override those given in commandline. Also made extensions web customisations happen before registration of web interface.
Edouard Tisserant
parents: 2220
diff changeset
    77
  -w  web server port or "off" to disable web server (default:8009)
4112
ef2620af8ad0 Python runtime: change meaning of -s and -c options in CLI
Edouard Tisserant <edouard@beremiz.fr>
parents: 4071
diff changeset
    78
  -c  WAMP client config file or Configuration directory containing "wamconf.json" (default:Wamp disabled, config dir is working_dir)
ef2620af8ad0 Python runtime: change meaning of -s and -c options in CLI
Edouard Tisserant <edouard@beremiz.fr>
parents: 4071
diff changeset
    79
      Note: Wamp config is overriden by wampconf.json given in project files.
ef2620af8ad0 Python runtime: change meaning of -s and -c options in CLI
Edouard Tisserant <edouard@beremiz.fr>
parents: 4071
diff changeset
    80
  -s  PSK secret file or existing KeyStore directory containing "psk.txt" (default:PSK disabled, KeyStore is working_dir)
2221
e03f7649bfb3 WAMP: now config and secret given in project files always override those given in commandline. Also made extensions web customisations happen before registration of web interface.
Edouard Tisserant
parents: 2220
diff changeset
    81
  -e  python extension (absolute path .py)
1434
6e0cd0ceabb7 Added runtime side trace buffer, handled in a separate thread, limited to 1MB, and dropped after 3 seconds if not used by IDE. GetTraceVariables is not anymore blocking on next PLC cycle
Edouard Tisserant
parents: 1270
diff changeset
    82
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
    83
           working_dir - directory where are stored PLC files
1826
91796f408540 fix usage of python2-only print statement
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1790
diff changeset
    84
""" % sys.argv[0])
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
    85
1749
d73b64672238 clean-up: fix PEP8 E305 expected 2 blank lines after class or function definition
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1747
diff changeset
    86
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
    87
try:
2644
769fefae7c81 Add --on-plc-start --on-plc-stop and --status-change to runtime command line, calling given command respectively on start stop or any event. Command line string is python formated (to eventually include status with {}) before being split (supports quoted strings) and passed to Popen for non-blocking execution.
Edouard Tisserant
parents: 2601
diff changeset
    88
    opts, argv = getopt.getopt(sys.argv[1:], "i:p:n:x:t:a:w:c:e:s:h", ["help", "version", "status-change=", "on-plc-start=", "on-plc-stop="])
2303
03ea6837a0b4 Use Python 3 compatible syntax for exceptions
Yegor Yefremov <yegorslists@googlemail.com>
parents: 2294
diff changeset
    89
except getopt.GetoptError as err:
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
    90
    # print help information and exit:
1826
91796f408540 fix usage of python2-only print statement
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1790
diff changeset
    91
    print(str(err))  # will print something like "option -a not recognized"
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
    92
    usage()
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
    93
    sys.exit(2)
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
    94
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
    95
# default values
2311
bef2b4b87370 Beremiz_service now binds both pyro and nevow ports to interface given with '-i' argument.
Edouard Tisserant
parents: 2305
diff changeset
    96
interface = ''
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
    97
port = 3000
1439
a68cd4253259 Added stub code for runtime WAMP client. Added runtime command line switch to select WAMP url and Nevow web site port. Web port is now fixed, next port number is not tested if bind fails.
Edouard Tisserant
parents: 1438
diff changeset
    98
webport = 8009
2324
1cf3768ebf85 Automatically get PSK and ID when connecting to PYRO[S], so that future connection through PYROS can use that same key. Also fixed case to UPPER for *PSK.
Edouard Tisserant
parents: 2323
diff changeset
    99
PSKpath = None
4112
ef2620af8ad0 Python runtime: change meaning of -s and -c options in CLI
Edouard Tisserant <edouard@beremiz.fr>
parents: 4071
diff changeset
   100
KeyStore = None
ef2620af8ad0 Python runtime: change meaning of -s and -c options in CLI
Edouard Tisserant <edouard@beremiz.fr>
parents: 4071
diff changeset
   101
ConfDir = None
1893
971de876b1af WAMP runtime : changes from dporopat and agregorcic, adding CRA (-s) and changed way to load WAMP conf (-c)
Edouard Tisserant
parents: 1889
diff changeset
   102
wampconf = None
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   103
servicename = None
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   104
autostart = False
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   105
enablewx = True
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   106
havewx = False
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   107
enabletwisted = True
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   108
havetwisted = False
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   109
1742
92932cd370a4 clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1741
diff changeset
   110
extensions = []
2644
769fefae7c81 Add --on-plc-start --on-plc-stop and --status-change to runtime command line, calling given command respectively on start stop or any event. Command line string is python formated (to eventually include status with {}) before being split (supports quoted strings) and passed to Popen for non-blocking execution.
Edouard Tisserant
parents: 2601
diff changeset
   111
statuschange = []
769fefae7c81 Add --on-plc-start --on-plc-stop and --status-change to runtime command line, calling given command respectively on start stop or any event. Command line string is python formated (to eventually include status with {}) before being split (supports quoted strings) and passed to Popen for non-blocking execution.
Edouard Tisserant
parents: 2601
diff changeset
   112
def status_change_call_factory(wanted, args):
769fefae7c81 Add --on-plc-start --on-plc-stop and --status-change to runtime command line, calling given command respectively on start stop or any event. Command line string is python formated (to eventually include status with {}) before being split (supports quoted strings) and passed to Popen for non-blocking execution.
Edouard Tisserant
parents: 2601
diff changeset
   113
    def status_change_call(status):
769fefae7c81 Add --on-plc-start --on-plc-stop and --status-change to runtime command line, calling given command respectively on start stop or any event. Command line string is python formated (to eventually include status with {}) before being split (supports quoted strings) and passed to Popen for non-blocking execution.
Edouard Tisserant
parents: 2601
diff changeset
   114
        if wanted is None or status is wanted:
769fefae7c81 Add --on-plc-start --on-plc-stop and --status-change to runtime command line, calling given command respectively on start stop or any event. Command line string is python formated (to eventually include status with {}) before being split (supports quoted strings) and passed to Popen for non-blocking execution.
Edouard Tisserant
parents: 2601
diff changeset
   115
            cmd = shlex.split(args.format(status))
769fefae7c81 Add --on-plc-start --on-plc-stop and --status-change to runtime command line, calling given command respectively on start stop or any event. Command line string is python formated (to eventually include status with {}) before being split (supports quoted strings) and passed to Popen for non-blocking execution.
Edouard Tisserant
parents: 2601
diff changeset
   116
            Popen(cmd)
769fefae7c81 Add --on-plc-start --on-plc-stop and --status-change to runtime command line, calling given command respectively on start stop or any event. Command line string is python formated (to eventually include status with {}) before being split (supports quoted strings) and passed to Popen for non-blocking execution.
Edouard Tisserant
parents: 2601
diff changeset
   117
    return status_change_call
1437
04177743b066 Added Beremiz_service.py command line switch to load python extention for runtime independently from PLC program
Edouard Tisserant
parents: 1434
diff changeset
   118
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   119
for o, a in opts:
2294
da288f63612f Make Beremiz_service print version information
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 2249
diff changeset
   120
    if o == "-h" or o == "--help":
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   121
        usage()
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   122
        sys.exit()
2294
da288f63612f Make Beremiz_service print version information
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 2249
diff changeset
   123
    if o == "--version":
da288f63612f Make Beremiz_service print version information
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 2249
diff changeset
   124
        version()
da288f63612f Make Beremiz_service print version information
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 2249
diff changeset
   125
        sys.exit()
2644
769fefae7c81 Add --on-plc-start --on-plc-stop and --status-change to runtime command line, calling given command respectively on start stop or any event. Command line string is python formated (to eventually include status with {}) before being split (supports quoted strings) and passed to Popen for non-blocking execution.
Edouard Tisserant
parents: 2601
diff changeset
   126
    if o == "--on-plc-start":
769fefae7c81 Add --on-plc-start --on-plc-stop and --status-change to runtime command line, calling given command respectively on start stop or any event. Command line string is python formated (to eventually include status with {}) before being split (supports quoted strings) and passed to Popen for non-blocking execution.
Edouard Tisserant
parents: 2601
diff changeset
   127
        statuschange.append(status_change_call_factory(PlcStatus.Started, a))
769fefae7c81 Add --on-plc-start --on-plc-stop and --status-change to runtime command line, calling given command respectively on start stop or any event. Command line string is python formated (to eventually include status with {}) before being split (supports quoted strings) and passed to Popen for non-blocking execution.
Edouard Tisserant
parents: 2601
diff changeset
   128
    elif o == "--on-plc-stop":
769fefae7c81 Add --on-plc-start --on-plc-stop and --status-change to runtime command line, calling given command respectively on start stop or any event. Command line string is python formated (to eventually include status with {}) before being split (supports quoted strings) and passed to Popen for non-blocking execution.
Edouard Tisserant
parents: 2601
diff changeset
   129
        statuschange.append(status_change_call_factory(PlcStatus.Stopped, a))
769fefae7c81 Add --on-plc-start --on-plc-stop and --status-change to runtime command line, calling given command respectively on start stop or any event. Command line string is python formated (to eventually include status with {}) before being split (supports quoted strings) and passed to Popen for non-blocking execution.
Edouard Tisserant
parents: 2601
diff changeset
   130
    elif o == "--status-change":
769fefae7c81 Add --on-plc-start --on-plc-stop and --status-change to runtime command line, calling given command respectively on start stop or any event. Command line string is python formated (to eventually include status with {}) before being split (supports quoted strings) and passed to Popen for non-blocking execution.
Edouard Tisserant
parents: 2601
diff changeset
   131
        statuschange.append(status_change_call_factory(None, a))
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   132
    elif o == "-i":
2311
bef2b4b87370 Beremiz_service now binds both pyro and nevow ports to interface given with '-i' argument.
Edouard Tisserant
parents: 2305
diff changeset
   133
        if len(a.split(".")) == 4:
bef2b4b87370 Beremiz_service now binds both pyro and nevow ports to interface given with '-i' argument.
Edouard Tisserant
parents: 2305
diff changeset
   134
            interface = a
bef2b4b87370 Beremiz_service now binds both pyro and nevow ports to interface given with '-i' argument.
Edouard Tisserant
parents: 2305
diff changeset
   135
        elif a == "localhost":
bef2b4b87370 Beremiz_service now binds both pyro and nevow ports to interface given with '-i' argument.
Edouard Tisserant
parents: 2305
diff changeset
   136
            interface = '127.0.0.1'
644
b511cab580eb Better naming of IP address related variables in Beremiz_service.py, Ignore errors that occur on shutdown in Zeroconf.py, fixed discovery dialog crash due to asynchronous call from zeroconf
Edouard Tisserant
parents: 641
diff changeset
   137
        else:
b511cab580eb Better naming of IP address related variables in Beremiz_service.py, Ignore errors that occur on shutdown in Zeroconf.py, fixed discovery dialog crash due to asynchronous call from zeroconf
Edouard Tisserant
parents: 641
diff changeset
   138
            usage()
b511cab580eb Better naming of IP address related variables in Beremiz_service.py, Ignore errors that occur on shutdown in Zeroconf.py, fixed discovery dialog crash due to asynchronous call from zeroconf
Edouard Tisserant
parents: 641
diff changeset
   139
            sys.exit()
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   140
    elif o == "-p":
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   141
        # port: port that the service runs on
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   142
        port = int(a)
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   143
    elif o == "-n":
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   144
        servicename = a
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   145
    elif o == "-x":
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   146
        enablewx = int(a)
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   147
    elif o == "-t":
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   148
        enabletwisted = int(a)
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   149
    elif o == "-a":
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   150
        autostart = int(a)
1439
a68cd4253259 Added stub code for runtime WAMP client. Added runtime command line switch to select WAMP url and Nevow web site port. Web port is now fixed, next port number is not tested if bind fails.
Edouard Tisserant
parents: 1438
diff changeset
   151
    elif o == "-w":
a68cd4253259 Added stub code for runtime WAMP client. Added runtime command line switch to select WAMP url and Nevow web site port. Web port is now fixed, next port number is not tested if bind fails.
Edouard Tisserant
parents: 1438
diff changeset
   152
        webport = None if a == "off" else int(a)
a68cd4253259 Added stub code for runtime WAMP client. Added runtime command line switch to select WAMP url and Nevow web site port. Web port is now fixed, next port number is not tested if bind fails.
Edouard Tisserant
parents: 1438
diff changeset
   153
    elif o == "-c":
4112
ef2620af8ad0 Python runtime: change meaning of -s and -c options in CLI
Edouard Tisserant <edouard@beremiz.fr>
parents: 4071
diff changeset
   154
        if a == "off":
ef2620af8ad0 Python runtime: change meaning of -s and -c options in CLI
Edouard Tisserant <edouard@beremiz.fr>
parents: 4071
diff changeset
   155
            wampconf = None 
ef2620af8ad0 Python runtime: change meaning of -s and -c options in CLI
Edouard Tisserant <edouard@beremiz.fr>
parents: 4071
diff changeset
   156
        elif os.path.isdir(a):
ef2620af8ad0 Python runtime: change meaning of -s and -c options in CLI
Edouard Tisserant <edouard@beremiz.fr>
parents: 4071
diff changeset
   157
            ConfDir = a
ef2620af8ad0 Python runtime: change meaning of -s and -c options in CLI
Edouard Tisserant <edouard@beremiz.fr>
parents: 4071
diff changeset
   158
            _PSKpath = os.path.join(a, "wampconf.json")
ef2620af8ad0 Python runtime: change meaning of -s and -c options in CLI
Edouard Tisserant <edouard@beremiz.fr>
parents: 4071
diff changeset
   159
            if os.path.isfile(_PSKpath):
ef2620af8ad0 Python runtime: change meaning of -s and -c options in CLI
Edouard Tisserant <edouard@beremiz.fr>
parents: 4071
diff changeset
   160
                wampconf = _PSKpath
4121
ef48f96ccf06 python runtime: fix behaviour of -c when given file do not exist yet
Edouard Tisserant <edouard@beremiz.fr>
parents: 4117
diff changeset
   161
        elif os.path.isfile(a) or os.path.isdir(paths.AbsDir(a)):
4112
ef2620af8ad0 Python runtime: change meaning of -s and -c options in CLI
Edouard Tisserant <edouard@beremiz.fr>
parents: 4071
diff changeset
   162
            wampconf = a
4121
ef48f96ccf06 python runtime: fix behaviour of -c when given file do not exist yet
Edouard Tisserant <edouard@beremiz.fr>
parents: 4117
diff changeset
   163
            ConfDir = paths.AbsDir(a)
1893
971de876b1af WAMP runtime : changes from dporopat and agregorcic, adding CRA (-s) and changed way to load WAMP conf (-c)
Edouard Tisserant
parents: 1889
diff changeset
   164
    elif o == "-s":
4112
ef2620af8ad0 Python runtime: change meaning of -s and -c options in CLI
Edouard Tisserant <edouard@beremiz.fr>
parents: 4071
diff changeset
   165
        if a == "off":
ef2620af8ad0 Python runtime: change meaning of -s and -c options in CLI
Edouard Tisserant <edouard@beremiz.fr>
parents: 4071
diff changeset
   166
            PSKpath = None 
ef2620af8ad0 Python runtime: change meaning of -s and -c options in CLI
Edouard Tisserant <edouard@beremiz.fr>
parents: 4071
diff changeset
   167
        elif os.path.isdir(a):
ef2620af8ad0 Python runtime: change meaning of -s and -c options in CLI
Edouard Tisserant <edouard@beremiz.fr>
parents: 4071
diff changeset
   168
            KeyStore = a
ef2620af8ad0 Python runtime: change meaning of -s and -c options in CLI
Edouard Tisserant <edouard@beremiz.fr>
parents: 4071
diff changeset
   169
            _PSKpath = os.path.join(a, "psk.txt")
ef2620af8ad0 Python runtime: change meaning of -s and -c options in CLI
Edouard Tisserant <edouard@beremiz.fr>
parents: 4071
diff changeset
   170
            if os.path.isfile(_PSKpath):
ef2620af8ad0 Python runtime: change meaning of -s and -c options in CLI
Edouard Tisserant <edouard@beremiz.fr>
parents: 4071
diff changeset
   171
                PSKpath = _PSKpath
4114
8a9986e26dfc python runtime: fix behaviour of -s CLI option when given file doesn't exist.
Edouard Tisserant <edouard@beremiz.fr>
parents: 4113
diff changeset
   172
        elif os.path.isfile(a) or os.path.isdir(paths.AbsDir(a)):
4112
ef2620af8ad0 Python runtime: change meaning of -s and -c options in CLI
Edouard Tisserant <edouard@beremiz.fr>
parents: 4071
diff changeset
   173
            PSKpath = a
4114
8a9986e26dfc python runtime: fix behaviour of -s CLI option when given file doesn't exist.
Edouard Tisserant <edouard@beremiz.fr>
parents: 4113
diff changeset
   174
            KeyStore = paths.AbsDir(a)
4112
ef2620af8ad0 Python runtime: change meaning of -s and -c options in CLI
Edouard Tisserant <edouard@beremiz.fr>
parents: 4071
diff changeset
   175
1437
04177743b066 Added Beremiz_service.py command line switch to load python extention for runtime independently from PLC program
Edouard Tisserant
parents: 1434
diff changeset
   176
    elif o == "-e":
1955
a1ea9856013a Attempt to make BitBuket's version of pep8 and pylint happy.
Edouard Tisserant
parents: 1953
diff changeset
   177
        fnameanddirname = list(os.path.split(os.path.realpath(a)))
a1ea9856013a Attempt to make BitBuket's version of pep8 and pylint happy.
Edouard Tisserant
parents: 1953
diff changeset
   178
        fnameanddirname.reverse()
a1ea9856013a Attempt to make BitBuket's version of pep8 and pylint happy.
Edouard Tisserant
parents: 1953
diff changeset
   179
        extensions.append(fnameanddirname)
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   180
    else:
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   181
        usage()
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   182
        sys.exit()
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   183
1783
3311eea28d56 clean-up: fix PEP8 E402 module level import not at top of file
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1780
diff changeset
   184
1680
6db967480b7d make run Beremiz and PLCOpen Editor, if full path contain non-lating
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1598
diff changeset
   185
beremiz_dir = paths.AbsDir(__file__)
1434
6e0cd0ceabb7 Added runtime side trace buffer, handled in a separate thread, limited to 1MB, and dropped after 3 seconds if not used by IDE. GetTraceVariables is not anymore blocking on next PLC cycle
Edouard Tisserant
parents: 1270
diff changeset
   186
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   187
if len(argv) > 1:
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   188
    usage()
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   189
    sys.exit()
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   190
elif len(argv) == 1:
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   191
    WorkingDir = argv[0]
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   192
    os.chdir(WorkingDir)
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   193
elif len(argv) == 0:
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   194
    WorkingDir = os.getcwd()
1742
92932cd370a4 clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1741
diff changeset
   195
    argv = [WorkingDir]
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   196
2459
21164625b393 Merged. Some changes that should already have been incuded during previous merge (mostly about PlcStatus) have been included this time.
Edouard Tisserant
parents: 2429 2450
diff changeset
   197
builtins.__dict__['_'] = lambda x: x
2319
0a951f528c69 Useless __name__ == '__main__' tests.
Edouard Tisserant
parents: 2315
diff changeset
   198
# TODO: add a cmdline parameter if Trying Preloading Xenomai makes problem
0a951f528c69 Useless __name__ == '__main__' tests.
Edouard Tisserant
parents: 2315
diff changeset
   199
TryPreloadXenomai()
0a951f528c69 Useless __name__ == '__main__' tests.
Edouard Tisserant
parents: 2315
diff changeset
   200
version()
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   201
1736
7e61baa047f0 clean-up: fix PEP8 E302 expected 2 blank lines, found 1
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1734
diff changeset
   202
1595
b3cc68dd037d add internatialization support for Beremiz_service.py
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1594
diff changeset
   203
def Bpath(*args):
1740
b789b695b5c6 clean-up: fix PEP8 E231 missing whitespace after ':' or ','
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1739
diff changeset
   204
    return os.path.join(beremiz_dir, *args)
1595
b3cc68dd037d add internatialization support for Beremiz_service.py
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1594
diff changeset
   205
1736
7e61baa047f0 clean-up: fix PEP8 E302 expected 2 blank lines, found 1
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1734
diff changeset
   206
3731
549763a28934 Runtime: move LC_NUMERIC locale setting to Beremiz_service.py.
Edouard Tisserant
parents: 3440
diff changeset
   207
import locale
549763a28934 Runtime: move LC_NUMERIC locale setting to Beremiz_service.py.
Edouard Tisserant
parents: 3440
diff changeset
   208
# Matiec's standard library relies on libC's locale-dependent
549763a28934 Runtime: move LC_NUMERIC locale setting to Beremiz_service.py.
Edouard Tisserant
parents: 3440
diff changeset
   209
# string to/from number convertions, but IEC-61131 counts
549763a28934 Runtime: move LC_NUMERIC locale setting to Beremiz_service.py.
Edouard Tisserant
parents: 3440
diff changeset
   210
# on '.' for decimal point. Therefore locale is reset to "C" */
549763a28934 Runtime: move LC_NUMERIC locale setting to Beremiz_service.py.
Edouard Tisserant
parents: 3440
diff changeset
   211
locale.setlocale(locale.LC_NUMERIC, "C")
549763a28934 Runtime: move LC_NUMERIC locale setting to Beremiz_service.py.
Edouard Tisserant
parents: 3440
diff changeset
   212
1595
b3cc68dd037d add internatialization support for Beremiz_service.py
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1594
diff changeset
   213
def SetupI18n():
b3cc68dd037d add internatialization support for Beremiz_service.py
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1594
diff changeset
   214
    # Get folder containing translation files
1740
b789b695b5c6 clean-up: fix PEP8 E231 missing whitespace after ':' or ','
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1739
diff changeset
   215
    localedir = os.path.join(beremiz_dir, "locale")
1595
b3cc68dd037d add internatialization support for Beremiz_service.py
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1594
diff changeset
   216
    # Get the default language
b3cc68dd037d add internatialization support for Beremiz_service.py
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1594
diff changeset
   217
    langid = wx.LANGUAGE_DEFAULT
b3cc68dd037d add internatialization support for Beremiz_service.py
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1594
diff changeset
   218
    # Define translation domain (name of translation files)
b3cc68dd037d add internatialization support for Beremiz_service.py
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1594
diff changeset
   219
    domain = "Beremiz"
b3cc68dd037d add internatialization support for Beremiz_service.py
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1594
diff changeset
   220
b3cc68dd037d add internatialization support for Beremiz_service.py
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1594
diff changeset
   221
    # Define locale for wx
2431
6923074540dd python3 support: pylint, W1648 # (bad-python3-import) Module moved in Python 3
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 2427
diff changeset
   222
    loc = builtins.__dict__.get('loc', None)
1595
b3cc68dd037d add internatialization support for Beremiz_service.py
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1594
diff changeset
   223
    if loc is None:
2349
645eb1bce0a5 Suppress message box in case current locale is unsupported or missing in wx
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 2294
diff changeset
   224
        wx.LogGui.EnableLogging(False)
1595
b3cc68dd037d add internatialization support for Beremiz_service.py
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1594
diff changeset
   225
        loc = wx.Locale(langid)
2349
645eb1bce0a5 Suppress message box in case current locale is unsupported or missing in wx
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 2294
diff changeset
   226
        wx.LogGui.EnableLogging(True)
2431
6923074540dd python3 support: pylint, W1648 # (bad-python3-import) Module moved in Python 3
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 2427
diff changeset
   227
        builtins.__dict__['loc'] = loc
1595
b3cc68dd037d add internatialization support for Beremiz_service.py
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1594
diff changeset
   228
        # Define location for searching translation files
b3cc68dd037d add internatialization support for Beremiz_service.py
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1594
diff changeset
   229
    loc.AddCatalogLookupPathPrefix(localedir)
b3cc68dd037d add internatialization support for Beremiz_service.py
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1594
diff changeset
   230
    # Define locale domain
b3cc68dd037d add internatialization support for Beremiz_service.py
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1594
diff changeset
   231
    loc.AddCatalog(domain)
b3cc68dd037d add internatialization support for Beremiz_service.py
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1594
diff changeset
   232
3800
a5a6ee271e65 WIP python3 support for runtime
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3793
diff changeset
   233
    builtins.__dict__['_'] = wx.GetTranslation
1595
b3cc68dd037d add internatialization support for Beremiz_service.py
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1594
diff changeset
   234
1749
d73b64672238 clean-up: fix PEP8 E305 expected 2 blank lines after class or function definition
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1747
diff changeset
   235
1919
ccea0fa6ea91 Another set of meaningless changes to satisfy PEP8 and PyLint.
Edouard Tisserant
parents: 1916
diff changeset
   236
# Life is hard... have a candy.
ccea0fa6ea91 Another set of meaningless changes to satisfy PEP8 and PyLint.
Edouard Tisserant
parents: 1916
diff changeset
   237
# pylint: disable=wrong-import-position,wrong-import-order
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   238
if enablewx:
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   239
    try:
1451
94e620cbd9de Added Ronan Bignaux (genesis) patch to use wxversion. Fixed side effects with sys.path. Other cosmetic fixes about path included.
Edouard Tisserant
parents: 1447
diff changeset
   240
        import wx
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   241
        havewx = True
1780
c52d1460cea8 clean-up: fix PEP8 E722 do not use bare except'
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1773
diff changeset
   242
    except ImportError:
1826
91796f408540 fix usage of python2-only print statement
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1790
diff changeset
   243
        print("Wx unavailable !")
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   244
        havewx = False
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   245
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   246
    if havewx:
1451
94e620cbd9de Added Ronan Bignaux (genesis) patch to use wxversion. Fixed side effects with sys.path. Other cosmetic fixes about path included.
Edouard Tisserant
parents: 1447
diff changeset
   247
        import re
3307
eeec6e0ea269 More WxPython 3.x->4.x API update
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3282
diff changeset
   248
        import wx.adv
1590
cdf95900d44f add python-wxgtk3.0 support to Beremiz_service.py
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1571
diff changeset
   249
3793
9958cf865da0 IDE: fixed/remove checks wxPython versions
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3766
diff changeset
   250
        app = wx.App(redirect=False)
4071
d0be57df5f8d runtime: make standard output more silent.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3884
diff changeset
   251
        app.GTKSuppressDiagnostics()
1590
cdf95900d44f add python-wxgtk3.0 support to Beremiz_service.py
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1571
diff changeset
   252
        app.SetTopWindow(wx.Frame(None, -1))
1434
6e0cd0ceabb7 Added runtime side trace buffer, handled in a separate thread, limited to 1MB, and dropped after 3 seconds if not used by IDE. GetTraceVariables is not anymore blocking on next PLC cycle
Edouard Tisserant
parents: 1270
diff changeset
   253
1595
b3cc68dd037d add internatialization support for Beremiz_service.py
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1594
diff changeset
   254
        default_locale = None
b3cc68dd037d add internatialization support for Beremiz_service.py
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1594
diff changeset
   255
        SetupI18n()
1434
6e0cd0ceabb7 Added runtime side trace buffer, handled in a separate thread, limited to 1MB, and dropped after 3 seconds if not used by IDE. GetTraceVariables is not anymore blocking on next PLC cycle
Edouard Tisserant
parents: 1270
diff changeset
   256
1067
4f460c1dffb5 Added exception hook to Beremiz_service, so that exception go in PLC log. Extended Beremiz.py exception hook to threads. Stripped images embedded in Beremiz_service.py, user real images instead.
Edouard Tisserant
parents: 1051
diff changeset
   257
        defaulticon = wx.Image(Bpath("images", "brz.png"))
4f460c1dffb5 Added exception hook to Beremiz_service, so that exception go in PLC log. Extended Beremiz.py exception hook to threads. Stripped images embedded in Beremiz_service.py, user real images instead.
Edouard Tisserant
parents: 1051
diff changeset
   258
        starticon = wx.Image(Bpath("images", "icoplay24.png"))
4f460c1dffb5 Added exception hook to Beremiz_service, so that exception go in PLC log. Extended Beremiz.py exception hook to threads. Stripped images embedded in Beremiz_service.py, user real images instead.
Edouard Tisserant
parents: 1051
diff changeset
   259
        stopicon = wx.Image(Bpath("images", "icostop24.png"))
1434
6e0cd0ceabb7 Added runtime side trace buffer, handled in a separate thread, limited to 1MB, and dropped after 3 seconds if not used by IDE. GetTraceVariables is not anymore blocking on next PLC cycle
Edouard Tisserant
parents: 1270
diff changeset
   260
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   261
        class ParamsEntryDialog(wx.TextEntryDialog):
1434
6e0cd0ceabb7 Added runtime side trace buffer, handled in a separate thread, limited to 1MB, and dropped after 3 seconds if not used by IDE. GetTraceVariables is not anymore blocking on next PLC cycle
Edouard Tisserant
parents: 1270
diff changeset
   262
1744
69dfdb26f600 clean-up: fix PEP8 E251 unexpected spaces around keyword / parameter equals
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1742
diff changeset
   263
            def __init__(self, parent, message, caption=_("Please enter text"), defaultValue="",
1767
c74815729afd clean-up: fix PEP8 E127 continuation line over-indented for visual indent
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1766
diff changeset
   264
                         style=wx.OK | wx.CANCEL | wx.CENTRE, pos=wx.DefaultPosition):
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   265
                wx.TextEntryDialog.__init__(self, parent, message, caption, defaultValue, style, pos)
1434
6e0cd0ceabb7 Added runtime side trace buffer, handled in a separate thread, limited to 1MB, and dropped after 3 seconds if not used by IDE. GetTraceVariables is not anymore blocking on next PLC cycle
Edouard Tisserant
parents: 1270
diff changeset
   266
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   267
                self.Tests = []
2177
10aa87518401 Drop support for wxPython 2.6 and below
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 2002
diff changeset
   268
                self.Bind(wx.EVT_BUTTON, self.OnOK, id=self.GetAffirmativeId())
1434
6e0cd0ceabb7 Added runtime side trace buffer, handled in a separate thread, limited to 1MB, and dropped after 3 seconds if not used by IDE. GetTraceVariables is not anymore blocking on next PLC cycle
Edouard Tisserant
parents: 1270
diff changeset
   269
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   270
            def OnOK(self, event):
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   271
                value = self.GetValue()
1739
ec153828ded2 clean-up: fix PEP8 E203 whitespace before ':' and whitespace before ','
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1738
diff changeset
   272
                texts = {"value": value}
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   273
                for function, message in self.Tests:
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   274
                    if not function(value):
1745
f9d32913bad4 clean-up: fix PEP8 E227 missing whitespace around bitwise or shift operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1744
diff changeset
   275
                        message = wx.MessageDialog(self, message % texts, _("Error"), wx.OK | wx.ICON_ERROR)
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   276
                        message.ShowModal()
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   277
                        message.Destroy()
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   278
                        return
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   279
                self.EndModal(wx.ID_OK)
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   280
                event.Skip()
1434
6e0cd0ceabb7 Added runtime side trace buffer, handled in a separate thread, limited to 1MB, and dropped after 3 seconds if not used by IDE. GetTraceVariables is not anymore blocking on next PLC cycle
Edouard Tisserant
parents: 1270
diff changeset
   281
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   282
            def GetValue(self):
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   283
                return self.GetSizer().GetItem(1).GetWindow().GetValue()
1434
6e0cd0ceabb7 Added runtime side trace buffer, handled in a separate thread, limited to 1MB, and dropped after 3 seconds if not used by IDE. GetTraceVariables is not anymore blocking on next PLC cycle
Edouard Tisserant
parents: 1270
diff changeset
   284
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   285
            def SetTests(self, tests):
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   286
                self.Tests = tests
1434
6e0cd0ceabb7 Added runtime side trace buffer, handled in a separate thread, limited to 1MB, and dropped after 3 seconds if not used by IDE. GetTraceVariables is not anymore blocking on next PLC cycle
Edouard Tisserant
parents: 1270
diff changeset
   287
3307
eeec6e0ea269 More WxPython 3.x->4.x API update
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3282
diff changeset
   288
        class BeremizTaskBarIcon(wx.adv.TaskBarIcon):
3766
f99def63cdd8 Update to wx.NewIdRef()
GP Orcullo <kinsamanka@gmail.com>
parents: 3752
diff changeset
   289
            TBMENU_START = wx.NewIdRef()
f99def63cdd8 Update to wx.NewIdRef()
GP Orcullo <kinsamanka@gmail.com>
parents: 3752
diff changeset
   290
            TBMENU_STOP = wx.NewIdRef()
f99def63cdd8 Update to wx.NewIdRef()
GP Orcullo <kinsamanka@gmail.com>
parents: 3752
diff changeset
   291
            TBMENU_CHANGE_NAME = wx.NewIdRef()
f99def63cdd8 Update to wx.NewIdRef()
GP Orcullo <kinsamanka@gmail.com>
parents: 3752
diff changeset
   292
            TBMENU_CHANGE_PORT = wx.NewIdRef()
f99def63cdd8 Update to wx.NewIdRef()
GP Orcullo <kinsamanka@gmail.com>
parents: 3752
diff changeset
   293
            TBMENU_CHANGE_INTERFACE = wx.NewIdRef()
f99def63cdd8 Update to wx.NewIdRef()
GP Orcullo <kinsamanka@gmail.com>
parents: 3752
diff changeset
   294
            TBMENU_LIVE_SHELL = wx.NewIdRef()
f99def63cdd8 Update to wx.NewIdRef()
GP Orcullo <kinsamanka@gmail.com>
parents: 3752
diff changeset
   295
            TBMENU_WXINSPECTOR = wx.NewIdRef()
3884
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
   296
            # TBMENU_CHANGE_WD = wx.NewIdRef()
3766
f99def63cdd8 Update to wx.NewIdRef()
GP Orcullo <kinsamanka@gmail.com>
parents: 3752
diff changeset
   297
            TBMENU_QUIT = wx.NewIdRef()
1434
6e0cd0ceabb7 Added runtime side trace buffer, handled in a separate thread, limited to 1MB, and dropped after 3 seconds if not used by IDE. GetTraceVariables is not anymore blocking on next PLC cycle
Edouard Tisserant
parents: 1270
diff changeset
   298
3884
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
   299
            def __init__(self, rpc_server):
3307
eeec6e0ea269 More WxPython 3.x->4.x API update
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3282
diff changeset
   300
                wx.adv.TaskBarIcon.__init__(self)
3884
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
   301
                self.rpc_server = rpc_server
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   302
                # Set the image
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   303
                self.UpdateIcon(None)
1434
6e0cd0ceabb7 Added runtime side trace buffer, handled in a separate thread, limited to 1MB, and dropped after 3 seconds if not used by IDE. GetTraceVariables is not anymore blocking on next PLC cycle
Edouard Tisserant
parents: 1270
diff changeset
   304
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   305
                # bind some events
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   306
                self.Bind(wx.EVT_MENU, self.OnTaskBarStartPLC, id=self.TBMENU_START)
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   307
                self.Bind(wx.EVT_MENU, self.OnTaskBarStopPLC, id=self.TBMENU_STOP)
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   308
                self.Bind(wx.EVT_MENU, self.OnTaskBarChangeName, id=self.TBMENU_CHANGE_NAME)
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   309
                self.Bind(wx.EVT_MENU, self.OnTaskBarChangeInterface, id=self.TBMENU_CHANGE_INTERFACE)
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   310
                self.Bind(wx.EVT_MENU, self.OnTaskBarLiveShell, id=self.TBMENU_LIVE_SHELL)
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   311
                self.Bind(wx.EVT_MENU, self.OnTaskBarWXInspector, id=self.TBMENU_WXINSPECTOR)
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   312
                self.Bind(wx.EVT_MENU, self.OnTaskBarChangePort, id=self.TBMENU_CHANGE_PORT)
3884
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
   313
                # self.Bind(wx.EVT_MENU, self.OnTaskBarChangeWorkingDir, id=self.TBMENU_CHANGE_WD)
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   314
                self.Bind(wx.EVT_MENU, self.OnTaskBarQuit, id=self.TBMENU_QUIT)
1434
6e0cd0ceabb7 Added runtime side trace buffer, handled in a separate thread, limited to 1MB, and dropped after 3 seconds if not used by IDE. GetTraceVariables is not anymore blocking on next PLC cycle
Edouard Tisserant
parents: 1270
diff changeset
   315
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   316
            def CreatePopupMenu(self):
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   317
                """
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   318
                This method is called by the base class when it needs to popup
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   319
                the menu for the default EVT_RIGHT_DOWN event.  Just create
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   320
                the menu how you want it and return it from this function,
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   321
                the base class takes care of the rest.
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   322
                """
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   323
                menu = wx.Menu()
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   324
                menu.Append(self.TBMENU_START, _("Start PLC"))
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   325
                menu.Append(self.TBMENU_STOP, _("Stop PLC"))
2270
d9175daf6522 Refactoring. Separated PLC Object, PYRO Server and MainWorker :
Edouard Tisserant
parents: 2249
diff changeset
   326
                menu.AppendSeparator()
d9175daf6522 Refactoring. Separated PLC Object, PYRO Server and MainWorker :
Edouard Tisserant
parents: 2249
diff changeset
   327
                menu.Append(self.TBMENU_CHANGE_NAME, _("Change Name"))
d9175daf6522 Refactoring. Separated PLC Object, PYRO Server and MainWorker :
Edouard Tisserant
parents: 2249
diff changeset
   328
                menu.Append(self.TBMENU_CHANGE_INTERFACE, _("Change IP of interface to bind"))
d9175daf6522 Refactoring. Separated PLC Object, PYRO Server and MainWorker :
Edouard Tisserant
parents: 2249
diff changeset
   329
                menu.Append(self.TBMENU_CHANGE_PORT, _("Change Port Number"))
3884
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
   330
                # menu.Append(self.TBMENU_CHANGE_WD, _("Change working directory"))
2270
d9175daf6522 Refactoring. Separated PLC Object, PYRO Server and MainWorker :
Edouard Tisserant
parents: 2249
diff changeset
   331
                menu.AppendSeparator()
d9175daf6522 Refactoring. Separated PLC Object, PYRO Server and MainWorker :
Edouard Tisserant
parents: 2249
diff changeset
   332
                menu.Append(self.TBMENU_LIVE_SHELL, _("Launch a live Python shell"))
d9175daf6522 Refactoring. Separated PLC Object, PYRO Server and MainWorker :
Edouard Tisserant
parents: 2249
diff changeset
   333
                menu.Append(self.TBMENU_WXINSPECTOR, _("Launch WX GUI inspector"))
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   334
                menu.AppendSeparator()
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   335
                menu.Append(self.TBMENU_QUIT, _("Quit"))
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   336
                return menu
1434
6e0cd0ceabb7 Added runtime side trace buffer, handled in a separate thread, limited to 1MB, and dropped after 3 seconds if not used by IDE. GetTraceVariables is not anymore blocking on next PLC cycle
Edouard Tisserant
parents: 1270
diff changeset
   337
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   338
            def MakeIcon(self, img):
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   339
                """
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   340
                The various platforms have different requirements for the
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   341
                icon size...
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   342
                """
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   343
                if "wxMSW" in wx.PlatformInfo:
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   344
                    img = img.Scale(16, 16)
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   345
                elif "wxGTK" in wx.PlatformInfo:
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   346
                    img = img.Scale(22, 22)
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   347
                # wxMac can be any size upto 128x128, so leave the source img alone....
3307
eeec6e0ea269 More WxPython 3.x->4.x API update
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3282
diff changeset
   348
                icon = wx.Icon(img.ConvertToBitmap())
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   349
                return icon
1434
6e0cd0ceabb7 Added runtime side trace buffer, handled in a separate thread, limited to 1MB, and dropped after 3 seconds if not used by IDE. GetTraceVariables is not anymore blocking on next PLC cycle
Edouard Tisserant
parents: 1270
diff changeset
   350
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   351
            def OnTaskBarStartPLC(self, evt):
2270
d9175daf6522 Refactoring. Separated PLC Object, PYRO Server and MainWorker :
Edouard Tisserant
parents: 2249
diff changeset
   352
                runtime.GetPLCObjectSingleton().StartPLC()
1434
6e0cd0ceabb7 Added runtime side trace buffer, handled in a separate thread, limited to 1MB, and dropped after 3 seconds if not used by IDE. GetTraceVariables is not anymore blocking on next PLC cycle
Edouard Tisserant
parents: 1270
diff changeset
   353
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   354
            def OnTaskBarStopPLC(self, evt):
2270
d9175daf6522 Refactoring. Separated PLC Object, PYRO Server and MainWorker :
Edouard Tisserant
parents: 2249
diff changeset
   355
                runtime.GetPLCObjectSingleton().StopPLC()
1434
6e0cd0ceabb7 Added runtime side trace buffer, handled in a separate thread, limited to 1MB, and dropped after 3 seconds if not used by IDE. GetTraceVariables is not anymore blocking on next PLC cycle
Edouard Tisserant
parents: 1270
diff changeset
   356
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   357
            def OnTaskBarChangeInterface(self, evt):
3884
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
   358
                ip_addr = self.rpc_server.ip_addr
1593
6a27490fed96 don't crash on trying to change IP interface for Beremiz_service using taskbar icon if IP wasn't previously
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1592
diff changeset
   359
                ip_addr = '' if ip_addr is None else ip_addr
1730
64d8f52bc8c8 clean-up for PEP8: fix W291 trailing whitespace
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1680
diff changeset
   360
                dlg = ParamsEntryDialog(None, _("Enter the IP of the interface to bind"), defaultValue=ip_addr)
2439
f0a040f1de1b Fix pep8 warning: W605 invalid escape sequence ?x?
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 2431
diff changeset
   361
                dlg.SetTests([(re.compile(r'\d{1,3}(?:\.\d{1,3}){3}$').match, _("IP is not valid!")),
1767
c74815729afd clean-up: fix PEP8 E127 continuation line over-indented for visual indent
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1766
diff changeset
   362
                              (lambda x:len([x for x in x.split(".") if 0 <= int(x) <= 255]) == 4,
1773
38fde37c3766 clean-up: fix PEP8 E124 closing bracket does not match visual indentation
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1767
diff changeset
   363
                               _("IP is not valid!"))])
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   364
                if dlg.ShowModal() == wx.ID_OK:
3884
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
   365
                    self.rpc_server.ip_addr = dlg.GetValue()
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
   366
                    self.rpc_server.Restart()
1434
6e0cd0ceabb7 Added runtime side trace buffer, handled in a separate thread, limited to 1MB, and dropped after 3 seconds if not used by IDE. GetTraceVariables is not anymore blocking on next PLC cycle
Edouard Tisserant
parents: 1270
diff changeset
   367
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   368
            def OnTaskBarChangePort(self, evt):
3884
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
   369
                dlg = ParamsEntryDialog(None, _("Enter a port number "), defaultValue=str(self.rpc_server.port))
3752
9f6f46dbe3ae removed Python2 modules
GP Orcullo <kinsamanka@gmail.com>
parents: 3750
diff changeset
   370
                dlg.SetTests([(str.isdigit, _("Port number must be an integer!")), (lambda port: 0 <= int(port) <= 65535, _("Port number must be 0 <= port <= 65535!"))])
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   371
                if dlg.ShowModal() == wx.ID_OK:
3884
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
   372
                    self.rpc_server.port = int(dlg.GetValue())
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
   373
                    self.rpc_server.Restart()
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
   374
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
   375
            # def OnTaskBarChangeWorkingDir(self, evt):
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
   376
            #     dlg = wx.DirDialog(None, _("Choose a working directory "), self.rpc_server.workdir, wx.DD_NEW_DIR_BUTTON)
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
   377
            #     if dlg.ShowModal() == wx.ID_OK:
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
   378
            #         self.rpc_server.workdir = dlg.GetPath()
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
   379
            #         self.rpc_server.Restart()
1434
6e0cd0ceabb7 Added runtime side trace buffer, handled in a separate thread, limited to 1MB, and dropped after 3 seconds if not used by IDE. GetTraceVariables is not anymore blocking on next PLC cycle
Edouard Tisserant
parents: 1270
diff changeset
   380
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   381
            def OnTaskBarChangeName(self, evt):
3884
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
   382
                _servicename = self.rpc_server.servicename
2321
0a3103cd825d Small cosmetic change to enhance readability and avoid confusion.
Edouard Tisserant
parents: 2319
diff changeset
   383
                _servicename = '' if _servicename is None else _servicename
0a3103cd825d Small cosmetic change to enhance readability and avoid confusion.
Edouard Tisserant
parents: 2319
diff changeset
   384
                dlg = ParamsEntryDialog(None, _("Enter a name "), defaultValue=_servicename)
3800
a5a6ee271e65 WIP python3 support for runtime
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3793
diff changeset
   385
                dlg.SetTests([(lambda name: len(name) != 0, _("Name must not be null!"))])
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   386
                if dlg.ShowModal() == wx.ID_OK:
3884
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
   387
                    self.rpc_server.servicename = dlg.GetValue()
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
   388
                    self.rpc_server.Restart()
1434
6e0cd0ceabb7 Added runtime side trace buffer, handled in a separate thread, limited to 1MB, and dropped after 3 seconds if not used by IDE. GetTraceVariables is not anymore blocking on next PLC cycle
Edouard Tisserant
parents: 1270
diff changeset
   389
959
046aeae0d71c Python shell and wx inspector now both available even when PLC not started
Edouard Tisserant
parents: 867
diff changeset
   390
            def _LiveShellLocals(self):
2270
d9175daf6522 Refactoring. Separated PLC Object, PYRO Server and MainWorker :
Edouard Tisserant
parents: 2249
diff changeset
   391
                return {"locals": runtime.GetPLCObjectSingleton().python_runtime_vars}
1434
6e0cd0ceabb7 Added runtime side trace buffer, handled in a separate thread, limited to 1MB, and dropped after 3 seconds if not used by IDE. GetTraceVariables is not anymore blocking on next PLC cycle
Edouard Tisserant
parents: 1270
diff changeset
   392
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   393
            def OnTaskBarLiveShell(self, evt):
959
046aeae0d71c Python shell and wx inspector now both available even when PLC not started
Edouard Tisserant
parents: 867
diff changeset
   394
                from wx import py
046aeae0d71c Python shell and wx inspector now both available even when PLC not started
Edouard Tisserant
parents: 867
diff changeset
   395
                frame = py.crust.CrustFrame(**self._LiveShellLocals())
046aeae0d71c Python shell and wx inspector now both available even when PLC not started
Edouard Tisserant
parents: 867
diff changeset
   396
                frame.Show()
1434
6e0cd0ceabb7 Added runtime side trace buffer, handled in a separate thread, limited to 1MB, and dropped after 3 seconds if not used by IDE. GetTraceVariables is not anymore blocking on next PLC cycle
Edouard Tisserant
parents: 1270
diff changeset
   397
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   398
            def OnTaskBarWXInspector(self, evt):
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   399
                # Activate the widget inspection tool
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   400
                from wx.lib.inspection import InspectionTool
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   401
                if not InspectionTool().initialized:
959
046aeae0d71c Python shell and wx inspector now both available even when PLC not started
Edouard Tisserant
parents: 867
diff changeset
   402
                    InspectionTool().Init(**self._LiveShellLocals())
046aeae0d71c Python shell and wx inspector now both available even when PLC not started
Edouard Tisserant
parents: 867
diff changeset
   403
046aeae0d71c Python shell and wx inspector now both available even when PLC not started
Edouard Tisserant
parents: 867
diff changeset
   404
                wnd = wx.GetApp()
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   405
                InspectionTool().Show(wnd, True)
1434
6e0cd0ceabb7 Added runtime side trace buffer, handled in a separate thread, limited to 1MB, and dropped after 3 seconds if not used by IDE. GetTraceVariables is not anymore blocking on next PLC cycle
Edouard Tisserant
parents: 1270
diff changeset
   406
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   407
            def OnTaskBarQuit(self, evt):
1121
d3838e8f1b90 Fixed Beremiz_service not closing on Windows
Laurent Bessard
parents: 1067
diff changeset
   408
                if wx.Platform == '__WXMSW__':
3884
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
   409
                    Thread(target=self.rpc_server.Quit).start()
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   410
                self.RemoveIcon()
1121
d3838e8f1b90 Fixed Beremiz_service not closing on Windows
Laurent Bessard
parents: 1067
diff changeset
   411
                wx.CallAfter(wx.GetApp().ExitMainLoop)
1434
6e0cd0ceabb7 Added runtime side trace buffer, handled in a separate thread, limited to 1MB, and dropped after 3 seconds if not used by IDE. GetTraceVariables is not anymore blocking on next PLC cycle
Edouard Tisserant
parents: 1270
diff changeset
   412
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   413
            def UpdateIcon(self, plcstatus):
2416
1ca207782dde Use predefined constants for PlcStatus instead of string literals
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 2349
diff changeset
   414
                if plcstatus is PlcStatus.Started:
1067
4f460c1dffb5 Added exception hook to Beremiz_service, so that exception go in PLC log. Extended Beremiz.py exception hook to threads. Stripped images embedded in Beremiz_service.py, user real images instead.
Edouard Tisserant
parents: 1051
diff changeset
   415
                    currenticon = self.MakeIcon(starticon)
2416
1ca207782dde Use predefined constants for PlcStatus instead of string literals
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 2349
diff changeset
   416
                elif plcstatus is PlcStatus.Stopped:
1067
4f460c1dffb5 Added exception hook to Beremiz_service, so that exception go in PLC log. Extended Beremiz.py exception hook to threads. Stripped images embedded in Beremiz_service.py, user real images instead.
Edouard Tisserant
parents: 1051
diff changeset
   417
                    currenticon = self.MakeIcon(stopicon)
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   418
                else:
1067
4f460c1dffb5 Added exception hook to Beremiz_service, so that exception go in PLC log. Extended Beremiz.py exception hook to threads. Stripped images embedded in Beremiz_service.py, user real images instead.
Edouard Tisserant
parents: 1051
diff changeset
   419
                    currenticon = self.MakeIcon(defaulticon)
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   420
                self.SetIcon(currenticon, "Beremiz Service")
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   421
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   422
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   423
if not os.path.isdir(WorkingDir):
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   424
    os.mkdir(WorkingDir)
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   425
1736
7e61baa047f0 clean-up: fix PEP8 E302 expected 2 blank lines, found 1
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1734
diff changeset
   426
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   427
if enabletwisted:
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   428
    import warnings
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   429
    with warnings.catch_warnings():
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   430
        warnings.simplefilter("ignore")
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   431
        try:
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   432
            if havewx:
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   433
                from twisted.internet import wxreactor
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   434
                wxreactor.install()
3617
c3aae4c95bc1 Runtime: work around 1s delay added when using twisted reactor's callLater.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3585
diff changeset
   435
                from twisted.internet import reactor
c3aae4c95bc1 Runtime: work around 1s delay added when using twisted reactor's callLater.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3585
diff changeset
   436
                reactor.registerWxApp(app)
c3aae4c95bc1 Runtime: work around 1s delay added when using twisted reactor's callLater.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3585
diff changeset
   437
            else:
c3aae4c95bc1 Runtime: work around 1s delay added when using twisted reactor's callLater.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3585
diff changeset
   438
                # from twisted.internet import pollreactor
c3aae4c95bc1 Runtime: work around 1s delay added when using twisted reactor's callLater.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3585
diff changeset
   439
                # pollreactor.install()
c3aae4c95bc1 Runtime: work around 1s delay added when using twisted reactor's callLater.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3585
diff changeset
   440
                from twisted.internet import reactor
1434
6e0cd0ceabb7 Added runtime side trace buffer, handled in a separate thread, limited to 1MB, and dropped after 3 seconds if not used by IDE. GetTraceVariables is not anymore blocking on next PLC cycle
Edouard Tisserant
parents: 1270
diff changeset
   441
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   442
            havetwisted = True
1780
c52d1460cea8 clean-up: fix PEP8 E722 do not use bare except'
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1773
diff changeset
   443
        except ImportError:
1826
91796f408540 fix usage of python2-only print statement
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1790
diff changeset
   444
            print(_("Twisted unavailable."))
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   445
            havetwisted = False
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   446
1438
19ebe96b41c0 Moved twisted/nevow/athena away from Berermiz_service.py + some minor cleanup
Edouard Tisserant
parents: 1437
diff changeset
   447
pyruntimevars = {}
19ebe96b41c0 Moved twisted/nevow/athena away from Berermiz_service.py + some minor cleanup
Edouard Tisserant
parents: 1437
diff changeset
   448
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   449
if havewx:
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   450
    wx_eval_lock = Semaphore(0)
835
8145be14a2ae Fixed runtime GUI freeze when stopping PLC from the menu. Added -x 2 argument to Beremiz_service.py to restrict content of systray icon menu.
Edouard Tisserant
parents: 719
diff changeset
   451
1438
19ebe96b41c0 Moved twisted/nevow/athena away from Berermiz_service.py + some minor cleanup
Edouard Tisserant
parents: 1437
diff changeset
   452
    def statuschangeTskBar(status):
1740
b789b695b5c6 clean-up: fix PEP8 E231 missing whitespace after ':' or ','
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1739
diff changeset
   453
        wx.CallAfter(taskbar_instance.UpdateIcon, status)
1434
6e0cd0ceabb7 Added runtime side trace buffer, handled in a separate thread, limited to 1MB, and dropped after 3 seconds if not used by IDE. GetTraceVariables is not anymore blocking on next PLC cycle
Edouard Tisserant
parents: 1270
diff changeset
   454
1438
19ebe96b41c0 Moved twisted/nevow/athena away from Berermiz_service.py + some minor cleanup
Edouard Tisserant
parents: 1437
diff changeset
   455
    statuschange.append(statuschangeTskBar)
19ebe96b41c0 Moved twisted/nevow/athena away from Berermiz_service.py + some minor cleanup
Edouard Tisserant
parents: 1437
diff changeset
   456
867
06495975e8a4 Added caching for python eval (avoid compiling when same code called, but still execute). Cleaned up some evaluator related code.
Edouard Tisserant
parents: 850
diff changeset
   457
    def wx_evaluator(obj, *args, **kwargs):
1740
b789b695b5c6 clean-up: fix PEP8 E231 missing whitespace after ':' or ','
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1739
diff changeset
   458
        tocall, args, kwargs = obj.call
867
06495975e8a4 Added caching for python eval (avoid compiling when same code called, but still execute). Cleaned up some evaluator related code.
Edouard Tisserant
parents: 850
diff changeset
   459
        obj.res = default_evaluator(tocall, *args, **kwargs)
06495975e8a4 Added caching for python eval (avoid compiling when same code called, but still execute). Cleaned up some evaluator related code.
Edouard Tisserant
parents: 850
diff changeset
   460
        wx_eval_lock.release()
1434
6e0cd0ceabb7 Added runtime side trace buffer, handled in a separate thread, limited to 1MB, and dropped after 3 seconds if not used by IDE. GetTraceVariables is not anymore blocking on next PLC cycle
Edouard Tisserant
parents: 1270
diff changeset
   461
3800
a5a6ee271e65 WIP python3 support for runtime
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3793
diff changeset
   462
    main_thread_id = current_thread().ident
867
06495975e8a4 Added caching for python eval (avoid compiling when same code called, but still execute). Cleaned up some evaluator related code.
Edouard Tisserant
parents: 850
diff changeset
   463
    def evaluator(tocall, *args, **kwargs):
3584
8a54fd58a552 Runtime: wx.app.mainLoop and twisted reactor now share main thread with runtime.Worker.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3443
diff changeset
   464
        # To prevent deadlocks, check if current thread is not one already main
3800
a5a6ee271e65 WIP python3 support for runtime
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3793
diff changeset
   465
        current_id = current_thread().ident
2489
27e4fd37fea6 Fix previous commit : Using wx.CallAfter shouldn't have been necessary, and was a symptom of failing evaluator's deadlock detection.
Edouard Tisserant
parents: 2484
diff changeset
   466
3584
8a54fd58a552 Runtime: wx.app.mainLoop and twisted reactor now share main thread with runtime.Worker.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3443
diff changeset
   467
        if main_thread_id != current_id:
2484
2318a7cde101 Fixed deadlock when using Wx together with Twisted in runtime.
Edouard Tisserant
parents: 2476
diff changeset
   468
            o = type('', (object,), dict(call=(tocall, args, kwargs), res=None))
2318a7cde101 Fixed deadlock when using Wx together with Twisted in runtime.
Edouard Tisserant
parents: 2476
diff changeset
   469
            wx.CallAfter(wx_evaluator, o)
2318a7cde101 Fixed deadlock when using Wx together with Twisted in runtime.
Edouard Tisserant
parents: 2476
diff changeset
   470
            wx_eval_lock.acquire()
2318a7cde101 Fixed deadlock when using Wx together with Twisted in runtime.
Edouard Tisserant
parents: 2476
diff changeset
   471
            return o.res
2318a7cde101 Fixed deadlock when using Wx together with Twisted in runtime.
Edouard Tisserant
parents: 2476
diff changeset
   472
        else:
3584
8a54fd58a552 Runtime: wx.app.mainLoop and twisted reactor now share main thread with runtime.Worker.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3443
diff changeset
   473
            # avoid dead lock if called from main : do job immediately
2484
2318a7cde101 Fixed deadlock when using Wx together with Twisted in runtime.
Edouard Tisserant
parents: 2476
diff changeset
   474
            return default_evaluator(tocall, *args, **kwargs)
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   475
else:
2270
d9175daf6522 Refactoring. Separated PLC Object, PYRO Server and MainWorker :
Edouard Tisserant
parents: 2249
diff changeset
   476
    evaluator = default_evaluator
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   477
1916
b69bea00765a Small pep8 conformity enforcement.
Edouard Tisserant
parents: 1907
diff changeset
   478
# Exception hooks
1736
7e61baa047f0 clean-up: fix PEP8 E302 expected 2 blank lines, found 1
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1734
diff changeset
   479
1906
60edd0c901f1 Trying to get better logging/display of exceptions at runtime's startup
Edouard Tisserant
parents: 1905
diff changeset
   480
1067
4f460c1dffb5 Added exception hook to Beremiz_service, so that exception go in PLC log. Extended Beremiz.py exception hook to threads. Stripped images embedded in Beremiz_service.py, user real images instead.
Edouard Tisserant
parents: 1051
diff changeset
   481
def LogException(*exp):
1919
ccea0fa6ea91 Another set of meaningless changes to satisfy PEP8 and PyLint.
Edouard Tisserant
parents: 1916
diff changeset
   482
    LogMessageAndException("", exp)
1749
d73b64672238 clean-up: fix PEP8 E305 expected 2 blank lines after class or function definition
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1747
diff changeset
   483
1955
a1ea9856013a Attempt to make BitBuket's version of pep8 and pylint happy.
Edouard Tisserant
parents: 1953
diff changeset
   484
1067
4f460c1dffb5 Added exception hook to Beremiz_service, so that exception go in PLC log. Extended Beremiz.py exception hook to threads. Stripped images embedded in Beremiz_service.py, user real images instead.
Edouard Tisserant
parents: 1051
diff changeset
   485
sys.excepthook = LogException
1736
7e61baa047f0 clean-up: fix PEP8 E302 expected 2 blank lines, found 1
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1734
diff changeset
   486
7e61baa047f0 clean-up: fix PEP8 E302 expected 2 blank lines, found 1
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1734
diff changeset
   487
1067
4f460c1dffb5 Added exception hook to Beremiz_service, so that exception go in PLC log. Extended Beremiz.py exception hook to threads. Stripped images embedded in Beremiz_service.py, user real images instead.
Edouard Tisserant
parents: 1051
diff changeset
   488
def installThreadExcepthook():
4f460c1dffb5 Added exception hook to Beremiz_service, so that exception go in PLC log. Extended Beremiz.py exception hook to threads. Stripped images embedded in Beremiz_service.py, user real images instead.
Edouard Tisserant
parents: 1051
diff changeset
   489
    init_old = threading.Thread.__init__
1750
acf02488f37f clean-up: fix PEP8 E306 expected 1 blank line before a nested definition, found X
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1749
diff changeset
   490
1067
4f460c1dffb5 Added exception hook to Beremiz_service, so that exception go in PLC log. Extended Beremiz.py exception hook to threads. Stripped images embedded in Beremiz_service.py, user real images instead.
Edouard Tisserant
parents: 1051
diff changeset
   491
    def init(self, *args, **kwargs):
4f460c1dffb5 Added exception hook to Beremiz_service, so that exception go in PLC log. Extended Beremiz.py exception hook to threads. Stripped images embedded in Beremiz_service.py, user real images instead.
Edouard Tisserant
parents: 1051
diff changeset
   492
        init_old(self, *args, **kwargs)
4f460c1dffb5 Added exception hook to Beremiz_service, so that exception go in PLC log. Extended Beremiz.py exception hook to threads. Stripped images embedded in Beremiz_service.py, user real images instead.
Edouard Tisserant
parents: 1051
diff changeset
   493
        run_old = self.run
1750
acf02488f37f clean-up: fix PEP8 E306 expected 1 blank line before a nested definition, found X
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1749
diff changeset
   494
1067
4f460c1dffb5 Added exception hook to Beremiz_service, so that exception go in PLC log. Extended Beremiz.py exception hook to threads. Stripped images embedded in Beremiz_service.py, user real images instead.
Edouard Tisserant
parents: 1051
diff changeset
   495
        def run_with_except_hook(*args, **kw):
4f460c1dffb5 Added exception hook to Beremiz_service, so that exception go in PLC log. Extended Beremiz.py exception hook to threads. Stripped images embedded in Beremiz_service.py, user real images instead.
Edouard Tisserant
parents: 1051
diff changeset
   496
            try:
4f460c1dffb5 Added exception hook to Beremiz_service, so that exception go in PLC log. Extended Beremiz.py exception hook to threads. Stripped images embedded in Beremiz_service.py, user real images instead.
Edouard Tisserant
parents: 1051
diff changeset
   497
                run_old(*args, **kw)
4f460c1dffb5 Added exception hook to Beremiz_service, so that exception go in PLC log. Extended Beremiz.py exception hook to threads. Stripped images embedded in Beremiz_service.py, user real images instead.
Edouard Tisserant
parents: 1051
diff changeset
   498
            except (KeyboardInterrupt, SystemExit):
4f460c1dffb5 Added exception hook to Beremiz_service, so that exception go in PLC log. Extended Beremiz.py exception hook to threads. Stripped images embedded in Beremiz_service.py, user real images instead.
Edouard Tisserant
parents: 1051
diff changeset
   499
                raise
1780
c52d1460cea8 clean-up: fix PEP8 E722 do not use bare except'
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1773
diff changeset
   500
            except Exception:
1067
4f460c1dffb5 Added exception hook to Beremiz_service, so that exception go in PLC log. Extended Beremiz.py exception hook to threads. Stripped images embedded in Beremiz_service.py, user real images instead.
Edouard Tisserant
parents: 1051
diff changeset
   501
                sys.excepthook(*sys.exc_info())
4f460c1dffb5 Added exception hook to Beremiz_service, so that exception go in PLC log. Extended Beremiz.py exception hook to threads. Stripped images embedded in Beremiz_service.py, user real images instead.
Edouard Tisserant
parents: 1051
diff changeset
   502
        self.run = run_with_except_hook
4f460c1dffb5 Added exception hook to Beremiz_service, so that exception go in PLC log. Extended Beremiz.py exception hook to threads. Stripped images embedded in Beremiz_service.py, user real images instead.
Edouard Tisserant
parents: 1051
diff changeset
   503
    threading.Thread.__init__ = init
1749
d73b64672238 clean-up: fix PEP8 E305 expected 2 blank lines after class or function definition
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1747
diff changeset
   504
d73b64672238 clean-up: fix PEP8 E305 expected 2 blank lines after class or function definition
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1747
diff changeset
   505
1067
4f460c1dffb5 Added exception hook to Beremiz_service, so that exception go in PLC log. Extended Beremiz.py exception hook to threads. Stripped images embedded in Beremiz_service.py, user real images instead.
Edouard Tisserant
parents: 1051
diff changeset
   506
installThreadExcepthook()
2222
8ac0f1af5589 WAMP : complains about failure to start WAMP only if it was successfully imported.
Edouard Tisserant
parents: 2221
diff changeset
   507
havewamp = False
1067
4f460c1dffb5 Added exception hook to Beremiz_service, so that exception go in PLC log. Extended Beremiz.py exception hook to threads. Stripped images embedded in Beremiz_service.py, user real images instead.
Edouard Tisserant
parents: 1051
diff changeset
   508
1446
4963e3816641 Split runtime's twisted modules import and setup to ease runtime extensions hotpatching
Edouard Tisserant
parents: 1439
diff changeset
   509
if havetwisted:
1739
ec153828ded2 clean-up: fix PEP8 E203 whitespace before ':' and whitespace before ','
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1738
diff changeset
   510
    if webport is not None:
1446
4963e3816641 Split runtime's twisted modules import and setup to ease runtime extensions hotpatching
Edouard Tisserant
parents: 1439
diff changeset
   511
        try:
1872
866fb3ab8778 fix pylint error "(undefined-variable) Undefined variable 'X'"
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1850
diff changeset
   512
            import runtime.NevowServer as NS  # pylint: disable=ungrouped-imports
2669
be233279d179 BACnet and Modbus: Remove additional loading and unloading, use the one already in place for extensions.
Edouard Tisserant
parents: 2659
diff changeset
   513
            NS.WorkingDir = WorkingDir
2216
8ae29ec2d1dc Fix misc typos in exception handling code.
Edouard Tisserant
parents: 2213
diff changeset
   514
        except Exception:
2213
73b7034693b9 Better logging of Nevow Server import in case of exception.
Edouard Tisserant
parents: 2212
diff changeset
   515
            LogMessageAndException(_("Nevow/Athena import failed :"))
1446
4963e3816641 Split runtime's twisted modules import and setup to ease runtime extensions hotpatching
Edouard Tisserant
parents: 1439
diff changeset
   516
            webport = None
2669
be233279d179 BACnet and Modbus: Remove additional loading and unloading, use the one already in place for extensions.
Edouard Tisserant
parents: 2659
diff changeset
   517
2220
985f234b0d09 Moved Wamp configuration file selection logic into runtime/wampclient.py. Added Wamp CRA secret file upload and download. Slightly reworked code for config and secret file loading and saving.
Edouard Tisserant
parents: 2216
diff changeset
   518
    try:
985f234b0d09 Moved Wamp configuration file selection logic into runtime/wampclient.py. Added Wamp CRA secret file upload and download. Slightly reworked code for config and secret file loading and saving.
Edouard Tisserant
parents: 2216
diff changeset
   519
        import runtime.WampClient as WC  # pylint: disable=ungrouped-imports
985f234b0d09 Moved Wamp configuration file selection logic into runtime/wampclient.py. Added Wamp CRA secret file upload and download. Slightly reworked code for config and secret file loading and saving.
Edouard Tisserant
parents: 2216
diff changeset
   520
        WC.WorkingDir = WorkingDir
2222
8ac0f1af5589 WAMP : complains about failure to start WAMP only if it was successfully imported.
Edouard Tisserant
parents: 2221
diff changeset
   521
        havewamp = True
2220
985f234b0d09 Moved Wamp configuration file selection logic into runtime/wampclient.py. Added Wamp CRA secret file upload and download. Slightly reworked code for config and secret file loading and saving.
Edouard Tisserant
parents: 2216
diff changeset
   522
    except Exception:
985f234b0d09 Moved Wamp configuration file selection logic into runtime/wampclient.py. Added Wamp CRA secret file upload and download. Slightly reworked code for config and secret file loading and saving.
Edouard Tisserant
parents: 2216
diff changeset
   523
        LogMessageAndException(_("WAMP import failed :"))
1446
4963e3816641 Split runtime's twisted modules import and setup to ease runtime extensions hotpatching
Edouard Tisserant
parents: 1439
diff changeset
   524
1437
04177743b066 Added Beremiz_service.py command line switch to load python extention for runtime independently from PLC program
Edouard Tisserant
parents: 1434
diff changeset
   525
# Load extensions
1905
87c908079bc6 Changed way to deal with extensions arguments (-e) so that path and filename are stored independently and accessible for extensions themselves.
Edouard Tisserant
parents: 1901
diff changeset
   526
for extention_file, extension_folder in extensions:
1437
04177743b066 Added Beremiz_service.py command line switch to load python extention for runtime independently from PLC program
Edouard Tisserant
parents: 1434
diff changeset
   527
    sys.path.append(extension_folder)
3750
f62625418bff automated conversion using 2to3-3.9 tool
GP Orcullo <kinsamanka@gmail.com>
parents: 3738
diff changeset
   528
    exec(compile(open(os.path.join(extension_folder, extention_file), "rb").read(), os.path.join(extension_folder, extention_file), 'exec'), locals())
1437
04177743b066 Added Beremiz_service.py command line switch to load python extention for runtime independently from PLC program
Edouard Tisserant
parents: 1434
diff changeset
   529
2323
33a0dbabccd3 Runtime : Ensure that a random PSK secret compatible with stunnel is generated if -s commandline switch is used. Stunnel service is restarted after generation, using spawn_subprocess. TODO : give stunnel restart command as a commandline parameter.
Edouard Tisserant
parents: 2321
diff changeset
   530
# Service name is used as an ID for stunnel's PSK
33a0dbabccd3 Runtime : Ensure that a random PSK secret compatible with stunnel is generated if -s commandline switch is used. Stunnel service is restarted after generation, using spawn_subprocess. TODO : give stunnel restart command as a commandline parameter.
Edouard Tisserant
parents: 2321
diff changeset
   531
# Some extension may set 'servicename' to a computed ID or Serial Number
33a0dbabccd3 Runtime : Ensure that a random PSK secret compatible with stunnel is generated if -s commandline switch is used. Stunnel service is restarted after generation, using spawn_subprocess. TODO : give stunnel restart command as a commandline parameter.
Edouard Tisserant
parents: 2321
diff changeset
   532
# instead of using commandline '-n'
2324
1cf3768ebf85 Automatically get PSK and ID when connecting to PYRO[S], so that future connection through PYROS can use that same key. Also fixed case to UPPER for *PSK.
Edouard Tisserant
parents: 2323
diff changeset
   533
if servicename is not None and PSKpath is not None:
1cf3768ebf85 Automatically get PSK and ID when connecting to PYRO[S], so that future connection through PYROS can use that same key. Also fixed case to UPPER for *PSK.
Edouard Tisserant
parents: 2323
diff changeset
   534
    ensurePSK(servicename, PSKpath)
2270
d9175daf6522 Refactoring. Separated PLC Object, PYRO Server and MainWorker :
Edouard Tisserant
parents: 2249
diff changeset
   535
d9175daf6522 Refactoring. Separated PLC Object, PYRO Server and MainWorker :
Edouard Tisserant
parents: 2249
diff changeset
   536
runtime.CreatePLCObjectSingleton(
d9175daf6522 Refactoring. Separated PLC Object, PYRO Server and MainWorker :
Edouard Tisserant
parents: 2249
diff changeset
   537
    WorkingDir, argv, statuschange, evaluator, pyruntimevars)
d9175daf6522 Refactoring. Separated PLC Object, PYRO Server and MainWorker :
Edouard Tisserant
parents: 2249
diff changeset
   538
3884
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
   539
rpc_server = RPCServer(servicename, interface, port)
2270
d9175daf6522 Refactoring. Separated PLC Object, PYRO Server and MainWorker :
Edouard Tisserant
parents: 2249
diff changeset
   540
d9175daf6522 Refactoring. Separated PLC Object, PYRO Server and MainWorker :
Edouard Tisserant
parents: 2249
diff changeset
   541
if havewx:
3884
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
   542
    taskbar_instance = BeremizTaskBarIcon(rpc_server)
2270
d9175daf6522 Refactoring. Separated PLC Object, PYRO Server and MainWorker :
Edouard Tisserant
parents: 2249
diff changeset
   543
1446
4963e3816641 Split runtime's twisted modules import and setup to ease runtime extensions hotpatching
Edouard Tisserant
parents: 1439
diff changeset
   544
if havetwisted:
1739
ec153828ded2 clean-up: fix PEP8 E203 whitespace before ':' and whitespace before ','
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents: 1738
diff changeset
   545
    if webport is not None:
1446
4963e3816641 Split runtime's twisted modules import and setup to ease runtime extensions hotpatching
Edouard Tisserant
parents: 1439
diff changeset
   546
        try:
2311
bef2b4b87370 Beremiz_service now binds both pyro and nevow ports to interface given with '-i' argument.
Edouard Tisserant
parents: 2305
diff changeset
   547
            website = NS.RegisterWebsite(interface, webport)
1446
4963e3816641 Split runtime's twisted modules import and setup to ease runtime extensions hotpatching
Edouard Tisserant
parents: 1439
diff changeset
   548
            pyruntimevars["website"] = website
1906
60edd0c901f1 Trying to get better logging/display of exceptions at runtime's startup
Edouard Tisserant
parents: 1905
diff changeset
   549
        except Exception:
60edd0c901f1 Trying to get better logging/display of exceptions at runtime's startup
Edouard Tisserant
parents: 1905
diff changeset
   550
            LogMessageAndException(_("Nevow Web service failed. "))
1446
4963e3816641 Split runtime's twisted modules import and setup to ease runtime extensions hotpatching
Edouard Tisserant
parents: 1439
diff changeset
   551
2222
8ac0f1af5589 WAMP : complains about failure to start WAMP only if it was successfully imported.
Edouard Tisserant
parents: 2221
diff changeset
   552
    if havewamp:
8ac0f1af5589 WAMP : complains about failure to start WAMP only if it was successfully imported.
Edouard Tisserant
parents: 2221
diff changeset
   553
        try:
4117
49e297aaf694 python runtime: use given service name (-n CLI option) as CRA ID by default.
Edouard Tisserant <edouard@beremiz.fr>
parents: 4114
diff changeset
   554
            WC.RegisterWampClient(wampconf, PSKpath, ConfDir, KeyStore, servicename)
2222
8ac0f1af5589 WAMP : complains about failure to start WAMP only if it was successfully imported.
Edouard Tisserant
parents: 2221
diff changeset
   555
            WC.RegisterWebSettings(NS)
8ac0f1af5589 WAMP : complains about failure to start WAMP only if it was successfully imported.
Edouard Tisserant
parents: 2221
diff changeset
   556
        except Exception:
8ac0f1af5589 WAMP : complains about failure to start WAMP only if it was successfully imported.
Edouard Tisserant
parents: 2221
diff changeset
   557
            LogMessageAndException(_("WAMP client startup failed. "))
1446
4963e3816641 Split runtime's twisted modules import and setup to ease runtime extensions hotpatching
Edouard Tisserant
parents: 1439
diff changeset
   558
3884
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
   559
rpc_server_thread = None
3584
8a54fd58a552 Runtime: wx.app.mainLoop and twisted reactor now share main thread with runtime.Worker.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3443
diff changeset
   560
2738
58f2e3f22934 Runtime: Fix exception "Worker is disabled" when connecting while PLC runtime is starting.
Edouard Tisserant
parents: 2669
diff changeset
   561
def FirstWorkerJob():
58f2e3f22934 Runtime: Fix exception "Worker is disabled" when connecting while PLC runtime is starting.
Edouard Tisserant
parents: 2669
diff changeset
   562
    """
3884
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
   563
    RPC through rpc/wamp/UI may lead to delegation to Worker,
2738
58f2e3f22934 Runtime: Fix exception "Worker is disabled" when connecting while PLC runtime is starting.
Edouard Tisserant
parents: 2669
diff changeset
   564
    then this function ensures that Worker is already
3884
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
   565
    created when rpc starts
2738
58f2e3f22934 Runtime: Fix exception "Worker is disabled" when connecting while PLC runtime is starting.
Edouard Tisserant
parents: 2669
diff changeset
   566
    """
3884
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
   567
    global rpc_server_thread, rpc_server
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
   568
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
   569
    rpc_thread_started = Lock()
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
   570
    rpc_thread_started.acquire()
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
   571
    rpc_server_thread = Thread(target=rpc_server.Loop,
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
   572
                         kwargs=dict(when_ready=rpc_thread_started.release),
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
   573
                         name="RPCThread")
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
   574
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
   575
    rpc_server_thread.start()
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
   576
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
   577
    # Wait for rpc thread to be effective
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
   578
    rpc_thread_started.acquire()
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
   579
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
   580
    rpc_server.PrintServerInfo()
2738
58f2e3f22934 Runtime: Fix exception "Worker is disabled" when connecting while PLC runtime is starting.
Edouard Tisserant
parents: 2669
diff changeset
   581
58f2e3f22934 Runtime: Fix exception "Worker is disabled" when connecting while PLC runtime is starting.
Edouard Tisserant
parents: 2669
diff changeset
   582
    # Beremiz IDE detects LOCAL:// runtime is ready by looking
58f2e3f22934 Runtime: Fix exception "Worker is disabled" when connecting while PLC runtime is starting.
Edouard Tisserant
parents: 2669
diff changeset
   583
    # for self.workdir in the daemon's stdout.
3843
832bcf1b5b60 Runtime/win32: no sys.stdout with pythonw.exe
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3803
diff changeset
   584
    if sys.stdout:
832bcf1b5b60 Runtime/win32: no sys.stdout with pythonw.exe
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3803
diff changeset
   585
        sys.stdout.write(_("Current working directory :") + WorkingDir + "\n")
832bcf1b5b60 Runtime/win32: no sys.stdout with pythonw.exe
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3803
diff changeset
   586
        sys.stdout.flush()
2738
58f2e3f22934 Runtime: Fix exception "Worker is disabled" when connecting while PLC runtime is starting.
Edouard Tisserant
parents: 2669
diff changeset
   587
3584
8a54fd58a552 Runtime: wx.app.mainLoop and twisted reactor now share main thread with runtime.Worker.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3443
diff changeset
   588
    runtime.GetPLCObjectSingleton().AutoLoad(autostart)
8a54fd58a552 Runtime: wx.app.mainLoop and twisted reactor now share main thread with runtime.Worker.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3443
diff changeset
   589
3617
c3aae4c95bc1 Runtime: work around 1s delay added when using twisted reactor's callLater.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3585
diff changeset
   590
if havetwisted and havewx:
c3aae4c95bc1 Runtime: work around 1s delay added when using twisted reactor's callLater.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3585
diff changeset
   591
c3aae4c95bc1 Runtime: work around 1s delay added when using twisted reactor's callLater.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3585
diff changeset
   592
    waker_func = wx.CallAfter
3585
efdefbad49eb runtime: fix bugs introduced in previous commit, and refactor some code
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3584
diff changeset
   593
efdefbad49eb runtime: fix bugs introduced in previous commit, and refactor some code
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3584
diff changeset
   594
    # This orders ui loop to signal when ready on Stdout
efdefbad49eb runtime: fix bugs introduced in previous commit, and refactor some code
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3584
diff changeset
   595
    waker_func(print,"UI thread started successfully.")
efdefbad49eb runtime: fix bugs introduced in previous commit, and refactor some code
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3584
diff changeset
   596
3617
c3aae4c95bc1 Runtime: work around 1s delay added when using twisted reactor's callLater.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3585
diff changeset
   597
    # interleaved worker copes with wxreactor by delegating all asynchronous
c3aae4c95bc1 Runtime: work around 1s delay added when using twisted reactor's callLater.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3585
diff changeset
   598
    # calls to wx's mainloop
3642
cd3d15e8ef42 Runtime: fix PLC not terminating when being Repaired (i.e purged).
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3617
diff changeset
   599
    runtime.MainWorker.interleave(waker_func, reactor.stop, FirstWorkerJob)
3585
efdefbad49eb runtime: fix bugs introduced in previous commit, and refactor some code
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3584
diff changeset
   600
efdefbad49eb runtime: fix bugs introduced in previous commit, and refactor some code
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3584
diff changeset
   601
    try:
3617
c3aae4c95bc1 Runtime: work around 1s delay added when using twisted reactor's callLater.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3585
diff changeset
   602
        reactor.run(installSignalHandlers=False)
3585
efdefbad49eb runtime: fix bugs introduced in previous commit, and refactor some code
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3584
diff changeset
   603
    except KeyboardInterrupt:
efdefbad49eb runtime: fix bugs introduced in previous commit, and refactor some code
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3584
diff changeset
   604
        pass
efdefbad49eb runtime: fix bugs introduced in previous commit, and refactor some code
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3584
diff changeset
   605
efdefbad49eb runtime: fix bugs introduced in previous commit, and refactor some code
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3584
diff changeset
   606
    runtime.MainWorker.stop()
efdefbad49eb runtime: fix bugs introduced in previous commit, and refactor some code
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3584
diff changeset
   607
3617
c3aae4c95bc1 Runtime: work around 1s delay added when using twisted reactor's callLater.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3585
diff changeset
   608
elif havewx:
c3aae4c95bc1 Runtime: work around 1s delay added when using twisted reactor's callLater.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3585
diff changeset
   609
c3aae4c95bc1 Runtime: work around 1s delay added when using twisted reactor's callLater.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3585
diff changeset
   610
    try:
c3aae4c95bc1 Runtime: work around 1s delay added when using twisted reactor's callLater.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3585
diff changeset
   611
        app.MainLoop
c3aae4c95bc1 Runtime: work around 1s delay added when using twisted reactor's callLater.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3585
diff changeset
   612
    except KeyboardInterrupt:
c3aae4c95bc1 Runtime: work around 1s delay added when using twisted reactor's callLater.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3585
diff changeset
   613
        pass
c3aae4c95bc1 Runtime: work around 1s delay added when using twisted reactor's callLater.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3585
diff changeset
   614
c3aae4c95bc1 Runtime: work around 1s delay added when using twisted reactor's callLater.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3585
diff changeset
   615
elif havetwisted:
2738
58f2e3f22934 Runtime: Fix exception "Worker is disabled" when connecting while PLC runtime is starting.
Edouard Tisserant
parents: 2669
diff changeset
   616
1994
1fdc32be71b8 Rework of runtime non-real-time threading, and shared object dynamic loading :
Edouard Tisserant
parents: 1988
diff changeset
   617
    ui_thread_started = Lock()
1fdc32be71b8 Rework of runtime non-real-time threading, and shared object dynamic loading :
Edouard Tisserant
parents: 1988
diff changeset
   618
    ui_thread_started.acquire()
3617
c3aae4c95bc1 Runtime: work around 1s delay added when using twisted reactor's callLater.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3585
diff changeset
   619
c3aae4c95bc1 Runtime: work around 1s delay added when using twisted reactor's callLater.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3585
diff changeset
   620
    reactor.callLater(0, ui_thread_started.release)
c3aae4c95bc1 Runtime: work around 1s delay added when using twisted reactor's callLater.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3585
diff changeset
   621
c3aae4c95bc1 Runtime: work around 1s delay added when using twisted reactor's callLater.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3585
diff changeset
   622
    ui_thread = Thread(
c3aae4c95bc1 Runtime: work around 1s delay added when using twisted reactor's callLater.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3585
diff changeset
   623
        target=partial(reactor.run, installSignalHandlers=False),
c3aae4c95bc1 Runtime: work around 1s delay added when using twisted reactor's callLater.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3585
diff changeset
   624
        name="UIThread")
1984
081265cda5b1 Intermediate state while implementing runtime worker to ensure that PLCObject Load and Unload methods always run main thread.
Edouard Tisserant
parents: 1955
diff changeset
   625
    ui_thread.start()
081265cda5b1 Intermediate state while implementing runtime worker to ensure that PLCObject Load and Unload methods always run main thread.
Edouard Tisserant
parents: 1955
diff changeset
   626
1994
1fdc32be71b8 Rework of runtime non-real-time threading, and shared object dynamic loading :
Edouard Tisserant
parents: 1988
diff changeset
   627
    ui_thread_started.acquire()
1fdc32be71b8 Rework of runtime non-real-time threading, and shared object dynamic loading :
Edouard Tisserant
parents: 1988
diff changeset
   628
    print("UI thread started successfully.")
3617
c3aae4c95bc1 Runtime: work around 1s delay added when using twisted reactor's callLater.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3585
diff changeset
   629
    try:
c3aae4c95bc1 Runtime: work around 1s delay added when using twisted reactor's callLater.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3585
diff changeset
   630
        # blocking worker loop
c3aae4c95bc1 Runtime: work around 1s delay added when using twisted reactor's callLater.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3585
diff changeset
   631
        runtime.MainWorker.runloop(FirstWorkerJob)
c3aae4c95bc1 Runtime: work around 1s delay added when using twisted reactor's callLater.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3585
diff changeset
   632
    except KeyboardInterrupt:
c3aae4c95bc1 Runtime: work around 1s delay added when using twisted reactor's callLater.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3585
diff changeset
   633
        pass
3585
efdefbad49eb runtime: fix bugs introduced in previous commit, and refactor some code
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3584
diff changeset
   634
else:
efdefbad49eb runtime: fix bugs introduced in previous commit, and refactor some code
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3584
diff changeset
   635
    try:
3584
8a54fd58a552 Runtime: wx.app.mainLoop and twisted reactor now share main thread with runtime.Worker.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3443
diff changeset
   636
        # blocking worker loop
8a54fd58a552 Runtime: wx.app.mainLoop and twisted reactor now share main thread with runtime.Worker.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3443
diff changeset
   637
        runtime.MainWorker.runloop(FirstWorkerJob)
3585
efdefbad49eb runtime: fix bugs introduced in previous commit, and refactor some code
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3584
diff changeset
   638
    except KeyboardInterrupt:
efdefbad49eb runtime: fix bugs introduced in previous commit, and refactor some code
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3584
diff changeset
   639
        pass
efdefbad49eb runtime: fix bugs introduced in previous commit, and refactor some code
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3584
diff changeset
   640
1984
081265cda5b1 Intermediate state while implementing runtime worker to ensure that PLCObject Load and Unload methods always run main thread.
Edouard Tisserant
parents: 1955
diff changeset
   641
3884
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
   642
rpc_server.Quit()
34da877021d5 Replace PYRO with ERPC. Work In Progress.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3843
diff changeset
   643
rpc_server_thread.join()
2270
d9175daf6522 Refactoring. Separated PLC Object, PYRO Server and MainWorker :
Edouard Tisserant
parents: 2249
diff changeset
   644
2669
be233279d179 BACnet and Modbus: Remove additional loading and unloading, use the one already in place for extensions.
Edouard Tisserant
parents: 2659
diff changeset
   645
plcobj = runtime.GetPLCObjectSingleton()
3282
725d3e9ac913 Runtime: Handle errors in user's python code more gracefully : make exceptions and allow repair.
Edouard Tisserant
parents: 2738
diff changeset
   646
try:
725d3e9ac913 Runtime: Handle errors in user's python code more gracefully : make exceptions and allow repair.
Edouard Tisserant
parents: 2738
diff changeset
   647
    plcobj.StopPLC()
725d3e9ac913 Runtime: Handle errors in user's python code more gracefully : make exceptions and allow repair.
Edouard Tisserant
parents: 2738
diff changeset
   648
    plcobj.UnLoadPLC()
725d3e9ac913 Runtime: Handle errors in user's python code more gracefully : make exceptions and allow repair.
Edouard Tisserant
parents: 2738
diff changeset
   649
except:
725d3e9ac913 Runtime: Handle errors in user's python code more gracefully : make exceptions and allow repair.
Edouard Tisserant
parents: 2738
diff changeset
   650
    print(traceback.format_exc())
2270
d9175daf6522 Refactoring. Separated PLC Object, PYRO Server and MainWorker :
Edouard Tisserant
parents: 2249
diff changeset
   651
2595
a0d2741a6722 Ensure Beremiz_service.py quits properly when Main Worker stops and wa are using Wx and/or Twisted.
Edouard Tisserant
parents: 2585
diff changeset
   652
if havetwisted:
a0d2741a6722 Ensure Beremiz_service.py quits properly when Main Worker stops and wa are using Wx and/or Twisted.
Edouard Tisserant
parents: 2585
diff changeset
   653
    reactor.stop()
3617
c3aae4c95bc1 Runtime: work around 1s delay added when using twisted reactor's callLater.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3585
diff changeset
   654
    if not havewx:
c3aae4c95bc1 Runtime: work around 1s delay added when using twisted reactor's callLater.
Edouard Tisserant <edouard.tisserant@gmail.com>
parents: 3585
diff changeset
   655
        ui_thread.join()
2595
a0d2741a6722 Ensure Beremiz_service.py quits properly when Main Worker stops and wa are using Wx and/or Twisted.
Edouard Tisserant
parents: 2585
diff changeset
   656
elif havewx:
a0d2741a6722 Ensure Beremiz_service.py quits properly when Main Worker stops and wa are using Wx and/or Twisted.
Edouard Tisserant
parents: 2585
diff changeset
   657
    app.ExitMainLoop()
a0d2741a6722 Ensure Beremiz_service.py quits properly when Main Worker stops and wa are using Wx and/or Twisted.
Edouard Tisserant
parents: 2585
diff changeset
   658
641
b4eae24d05bf Fixed encoding of Beremiz_service.py
Edouard Tisserant
parents: 622
diff changeset
   659
sys.exit(0)