# HG changeset patch # User Edouard Tisserant # Date 1593763405 -7200 # Node ID a4bae7edca137fc2fce7dc146dbb74741b5d0d00 # Parent 87edf99601ffdca8f02f1308c4cf11ae841db567# Parent 703ebf57508abaae12b5c9dc26cb9cfdd77b453c Merge from default diff -r 703ebf57508a -r a4bae7edca13 BeremizIDE.py --- a/BeremizIDE.py Wed Jul 01 10:36:20 2020 +0200 +++ b/BeremizIDE.py Fri Jul 03 10:03:25 2020 +0200 @@ -103,7 +103,7 @@ } else: faces = { - 'mono': 'Courier', + 'mono': 'FreeMono', 'size': 10, } diff -r 703ebf57508a -r a4bae7edca13 ConfigTreeNode.py --- a/ConfigTreeNode.py Wed Jul 01 10:36:20 2020 +0200 +++ b/ConfigTreeNode.py Fri Jul 03 10:03:25 2020 +0200 @@ -46,6 +46,7 @@ from xmlclass import GenerateParserFromXSDstring from PLCControler import LOCATION_CONFNODE from editors.ConfTreeNodeEditor import ConfTreeNodeEditor +from POULibrary import UserAddressedException _BaseParamsParser = GenerateParserFromXSDstring(""" diff -r 703ebf57508a -r a4bae7edca13 ProjectController.py --- a/ProjectController.py Wed Jul 01 10:36:20 2020 +0200 +++ b/ProjectController.py Fri Jul 03 10:03:25 2020 +0200 @@ -254,7 +254,7 @@ # Setup debug information self.IECdebug_datas = {} - self.DebugTimer = None + self.DebugUpdatePending = False self.ResetIECProgramsAndVariables() # In both new or load scenario, no need to save @@ -276,8 +276,6 @@ self.debug_status = PlcStatus.Stopped def __del__(self): - if self.DebugTimer: - self.DebugTimer.cancel() self.KillDebugThread() def LoadLibraries(self): @@ -1538,7 +1536,6 @@ return debug_status, ticks, buffers def RegisterDebugVarToConnector(self): - self.DebugTimer = None Idxs = [] self.TracedIECPath = [] self.TracedIECTypes = [] @@ -1577,25 +1574,15 @@ self._connector.SetTraceVariablesList([]) self.DebugToken = None self.debug_status, _debug_ticks, _buffers = self.SnapshotAndResetDebugValuesBuffers() + self.DebugUpdatePending = False def IsPLCStarted(self): return self.previous_plcstate == PlcStatus.Started - def ReArmDebugRegisterTimer(self): - if self.DebugTimer is not None: - self.DebugTimer.cancel() - - # Prevent to call RegisterDebugVarToConnector when PLC is not started - # If an output location var is forced it's leads to segmentation fault in runtime - # Links between PLC located variables and real variables are not ready - if self.IsPLCStarted(): - # Timer to prevent rapid-fire when registering many variables - # use wx.CallAfter use keep using same thread. TODO : use wx.Timer - # instead - self.DebugTimer = Timer( - 0.5, wx.CallAfter, args=[self.RegisterDebugVarToConnector]) - # Rearm anti-rapid-fire timer - self.DebugTimer.start() + def AppendDebugUpdate(self): + if not self.DebugUpdatePending : + wx.CallAfter(self.RegisterDebugVarToConnector) + self.DebugUpdatePending = True def GetDebugIECVariableType(self, IECPath): _Idx, IEC_Type = self._IECPathToIdx.get(IECPath, (None, None)) @@ -1625,7 +1612,7 @@ IECdebug_data[0][callableobj] = buffer_list - self.ReArmDebugRegisterTimer() + self.AppendDebugUpdate() return IECdebug_data[1] @@ -1641,12 +1628,12 @@ IECdebug_data[0].itervalues(), False) - self.ReArmDebugRegisterTimer() + self.AppendDebugUpdate() def UnsubscribeAllDebugIECVariable(self): self.IECdebug_datas = {} - self.ReArmDebugRegisterTimer() + self.AppendDebugUpdate() def ForceDebugIECVariable(self, IECPath, fvalue): if IECPath not in self.IECdebug_datas: @@ -1657,7 +1644,7 @@ IECdebug_data[2] = "Forced" IECdebug_data[3] = fvalue - self.ReArmDebugRegisterTimer() + self.AppendDebugUpdate() def ReleaseDebugIECVariable(self, IECPath): if IECPath not in self.IECdebug_datas: @@ -1668,7 +1655,7 @@ IECdebug_data[2] = "Registered" IECdebug_data[3] = None - self.ReArmDebugRegisterTimer() + self.AppendDebugUpdate() def CallWeakcallables(self, IECPath, function_name, *cargs): data_tuple = self.IECdebug_datas.get(IECPath, None) diff -r 703ebf57508a -r a4bae7edca13 XSLTransform.py --- a/XSLTransform.py Wed Jul 01 10:36:20 2020 +0200 +++ b/XSLTransform.py Fri Jul 03 10:03:25 2020 +0200 @@ -22,4 +22,7 @@ # print(self.xslt.error_log) return res + def get_error_log(self): + return self.xslt.error_log + diff -r 703ebf57508a -r a4bae7edca13 controls/CustomStyledTextCtrl.py --- a/controls/CustomStyledTextCtrl.py Wed Jul 01 10:36:20 2020 +0200 +++ b/controls/CustomStyledTextCtrl.py Fri Jul 03 10:03:25 2020 +0200 @@ -40,7 +40,7 @@ else: faces = { 'times': 'Times', - 'mono': 'Courier', + 'mono': 'FreeMono', 'helv': 'Helvetica', 'other': 'new century schoolbook', 'size': 12, diff -r 703ebf57508a -r a4bae7edca13 controls/LogViewer.py --- a/controls/LogViewer.py Wed Jul 01 10:36:20 2020 +0200 +++ b/controls/LogViewer.py Fri Jul 03 10:03:25 2020 +0200 @@ -339,7 +339,7 @@ if wx.Platform == '__WXMSW__': self.Font = wx.Font(8, wx.SWISS, wx.NORMAL, wx.NORMAL, faceName='Courier New') else: - self.Font = wx.Font(10, wx.SWISS, wx.NORMAL, wx.NORMAL, faceName='Courier') + self.Font = wx.Font(10, wx.SWISS, wx.NORMAL, wx.NORMAL, faceName='FreeMono') self.MessagePanel.Bind(wx.EVT_LEFT_UP, self.OnMessagePanelLeftUp) self.MessagePanel.Bind(wx.EVT_RIGHT_UP, self.OnMessagePanelRightUp) self.MessagePanel.Bind(wx.EVT_LEFT_DCLICK, self.OnMessagePanelLeftDCLick) diff -r 703ebf57508a -r a4bae7edca13 editors/ConfTreeNodeEditor.py --- a/editors/ConfTreeNodeEditor.py Wed Jul 01 10:36:20 2020 +0200 +++ b/editors/ConfTreeNodeEditor.py Fri Jul 03 10:03:25 2020 +0200 @@ -48,7 +48,7 @@ else: faces = { 'times': 'Times', - 'mono': 'Courier', + 'mono': 'FreeMono', 'helv': 'Helvetica', 'other': 'new century schoolbook', 'size': 18, diff -r 703ebf57508a -r a4bae7edca13 editors/Viewer.py --- a/editors/Viewer.py Wed Jul 01 10:36:20 2020 +0200 +++ b/editors/Viewer.py Fri Jul 03 10:03:25 2020 +0200 @@ -82,7 +82,7 @@ else: faces = { 'times': 'Times', - 'mono': 'Courier', + 'mono': 'FreeMono', 'helv': 'Helvetica', 'other': 'new century schoolbook', 'size': 10, diff -r 703ebf57508a -r a4bae7edca13 features.py --- a/features.py Wed Jul 01 10:36:20 2020 +0200 +++ b/features.py Fri Jul 03 10:03:25 2020 +0200 @@ -12,7 +12,8 @@ ('Native', 'NativeLib.NativeLibrary', True), ('Python', 'py_ext.PythonLibrary', True), ('Etherlab', 'etherlab.EthercatMaster.EtherlabLibrary', False), - ('SVGUI', 'svgui.SVGUILibrary', False)] + ('SVGUI', 'svgui.SVGUILibrary', False), + ('SVGHMI', 'svghmi.SVGHMILibrary', False)] catalog = [ ('canfestival', _('CANopen support'), _('Map located variables over CANopen'), 'canfestival.canfestival.RootClass'), @@ -22,6 +23,7 @@ ('c_ext', _('C extension'), _('Add C code accessing located variables synchronously'), 'c_ext.CFile'), ('py_ext', _('Python file'), _('Add Python code executed asynchronously'), 'py_ext.PythonFile'), ('wxglade_hmi', _('WxGlade GUI'), _('Add a simple WxGlade based GUI.'), 'wxglade_hmi.WxGladeHMI'), - ('svgui', _('SVGUI'), _('Experimental web based HMI'), 'svgui.SVGUI')] + ('svgui', _('SVGUI'), _('Experimental web based HMI'), 'svgui.SVGUI'), + ('svghmi', _('SVGHMI'), _('SVG based HMI'), 'svghmi.SVGHMI')] file_editors = [] diff -r 703ebf57508a -r a4bae7edca13 svghmi/Makefile --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/svghmi/Makefile Fri Jul 03 10:03:25 2020 +0200 @@ -0,0 +1,26 @@ +#! gmake + +# Makefile to generate XSLT stylesheets from ysl2 files in the same directory + +# This uses YML2. +# hg clone https://pep.foundation/dev/repos/yml2/ + +# It should be just fine if yml2 is cloned just asside beremiz +# otherwise, point yml2path to yml2 source directory +# make yml2path=path/to/yml/dir + +yml2path ?= $(abspath ../../yml2) + +ysl2files := gen_index_xhtml.ysl2 +ysl2includes := $(filter-out $(ysl2files), $(wildcard *.ysl2)) +xsltfiles := $(patsubst %.ysl2, %.xslt, $(ysl2files)) + +all:$(xsltfiles) + +%.xslt: %.ysl2 $(ysl2includes) svghmi.js ../yslt_noindent.yml2 + $(yml2path)/yml2c -I $(yml2path):../ $< -o $@.tmp + xmlstarlet fo $@.tmp > $@ + rm $@.tmp + +clean: + rm -f $(xsltfiles) diff -r 703ebf57508a -r a4bae7edca13 svghmi/README --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/svghmi/README Fri Jul 03 10:03:25 2020 +0200 @@ -0,0 +1,1 @@ +SVG HMI diff -r 703ebf57508a -r a4bae7edca13 svghmi/__init__.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/svghmi/__init__.py Fri Jul 03 10:03:25 2020 +0200 @@ -0,0 +1,10 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# This file is part of Beremiz +# Copyright (C) 2019: Edouard TISSERANT +# +# See COPYING file for copyrights details. + +from __future__ import absolute_import +from svghmi.svghmi import * diff -r 703ebf57508a -r a4bae7edca13 svghmi/default.svg --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/svghmi/default.svg Fri Jul 03 10:03:25 2020 +0200 @@ -0,0 +1,92 @@ + + + + + + + + image/svg+xml + + + + + + + + + This is description for page 0 + +all lines in the form "name: value" +are used as js object definition initializer + +role: "page" +name: "Home" + +after triple opening braces is global JavaScript code + +{{{ +/* JS style Comment */ +alert("Hello World"); +}}} + +after triple closing braces is back to description + + + path: "count" +format: "%4.4d"8888 + diff -r 703ebf57508a -r a4bae7edca13 svghmi/detachable_pages.ysl2 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/svghmi/detachable_pages.ysl2 Fri Jul 03 10:03:25 2020 +0200 @@ -0,0 +1,191 @@ +// detachable_pages.ysl2 +// +// compute what elements are required by pages +// and decide where to cut when removing/attaching +// pages elements on page switch + +const "hmi_pages_descs", "$parsed_widgets/widget[@type = 'Page']"; +const "hmi_pages", "$hmi_elements[@id = $hmi_pages_descs/@id]"; + +const "default_page" choose { + when "count($hmi_pages) > 1" { + choose { + when "$hmi_pages_descs/arg[1]/@value = 'Home'" > Home + otherwise { + error "No Home page defined!"; + } + } + } + when "count($hmi_pages) = 0" { + error "No page defined!"; + } + otherwise > «func:widget($hmi_pages/@id)/arg[1]/@value» +} + +emit "preamble:default-page" { + | + | var default_page = "«$default_page»"; +} + +const "keypads_descs", "$parsed_widgets/widget[@type = 'Keypad']"; +const "keypads", "$hmi_elements[@id = $keypads_descs/@id]"; + +// returns all directly or indirectly refered elements +def "func:refered_elements" { + param "elems"; + const "descend", "$elems/descendant-or-self::svg:*"; + const "clones", "$descend[self::svg:use]"; + const "originals", "//svg:*[concat('#',@id) = $clones/@xlink:href]"; + choose { + when "$originals" + result "$descend | func:refered_elements($originals)"; + otherwise + result "$descend"; + } +} + +def "func:all_related_elements" { + param "page"; + const "page_overlapping_geometry", "func:overlapping_geometry($page)"; + const "page_overlapping_elements", "//svg:*[@id = $page_overlapping_geometry/@Id]"; + const "page_sub_elements", "func:refered_elements($page | $page_overlapping_elements)"; + result "$page_sub_elements"; +} + +def "func:required_elements" { + param "pages"; + choose{ + when "$pages"{ + result """func:all_related_elements($pages[1]) + | func:required_elements($pages[position()!=1])"""; + }otherwise{ + result "/.."; + } + } +} + +const "required_elements", + """//svg:defs/descendant-or-self::svg:* + | func:required_elements($hmi_pages | $keypads)/ancestor-or-self::svg:*"""; + +const "discardable_elements", "//svg:*[not(@id = $required_elements/@id)]"; + +def "func:sumarized_elements" { + param "elements"; + const "short_list", "$elements[not(ancestor::*/@id = $elements/@id)]"; + const "filled_groups", """$short_list/parent::svg:*[ + not(descendant::*[ + not(self::svg:g) and + not(@id = $discardable_elements/@id) and + not(@id = $short_list/descendant-or-self::*[not(self::svg:g)]/@id) + ])]"""; + const "groups_to_add", "$filled_groups[not(ancestor::*/@id = $filled_groups/@id)]"; + result "$groups_to_add | $short_list[not(ancestor::svg:g/@id = $filled_groups/@id)]"; +} + +def "func:detachable_elements" { + param "pages"; + choose{ + when "$pages"{ + result """func:sumarized_elements(func:all_related_elements($pages[1])) + | func:detachable_elements($pages[position()!=1])"""; + }otherwise{ + result "/.."; + } + } +} + +// Avoid nested detachables +const "_detachable_elements", "func:detachable_elements($hmi_pages | $keypads)"; +const "detachable_elements", "$_detachable_elements[not(ancestor::*/@id = $_detachable_elements/@id)]"; + +emit "declarations:detachable-elements" { + | + | var detachable_elements = { + foreach "$detachable_elements"{ + | "«@id»":[id("«@id»"), id("«../@id»")]`if "position()!=last()" > ,` + } + | } +} + +const "forEach_widgets_ids", "$parsed_widgets/widget[@type = 'ForEach']/@id"; +const "forEach_widgets", "$hmi_elements[@id = $forEach_widgets_ids]"; +const "in_forEach_widget_ids", "func:refered_elements($forEach_widgets)[not(@id = $forEach_widgets_ids)]/@id"; + +template "svg:*", mode="page_desc" { + const "desc", "func:widget(@id)"; + const "page", "."; + const "p", "$geometry[@Id = $page/@id]"; + + const "page_all_elements", "func:all_related_elements($page)"; + + const "all_page_widgets","$hmi_elements[@id = $page_all_elements/@id and @id != $page/@id]"; + const "page_managed_widgets","$all_page_widgets[not(@id=$in_forEach_widget_ids)]"; + const "page_relative_widgets", + "$page_managed_widgets[func:is_descendant_path(func:widget(@id)/path/@value, $desc/path/@value)]"; + + // Take closest ancestor in detachable_elements + // since nested detachable elements are filtered out + const "required_detachables", + """func:sumarized_elements($page_all_elements)/ + ancestor-or-self::*[@id = $detachable_elements/@id]"""; + + | "«$desc/arg[1]/@value»": { + //| widget: hmi_widgets["«@id»"], + | bbox: [«$p/@x», «$p/@y», «$p/@w», «$p/@h»], + if "$desc/path/@value" { + if "count($desc/path/@index)=0" + warning > Page id="«$page/@id»" : No match for path "«$desc/path/@value»" in HMI tree + | page_index: «$desc/path/@index», + } + | relative_widgets: [ + foreach "$page_relative_widgets" { + | hmi_widgets["«@id»"]`if "position()!=last()" > ,` + } + | ], + | absolute_widgets: [ + foreach "$page_managed_widgets[not(@id = $page_relative_widgets/@id)]" { + | hmi_widgets["«@id»"]`if "position()!=last()" > ,` + } + | ], + | jumps: [ + foreach "$parsed_widgets/widget[@id = $all_page_widgets/@id and @type='Jump']" { + const "_id","@id"; + const "opts" call "jump_widget_activity" with "hmi_element", "$hmi_elements[@id=$_id]"; + if "string-length($opts)>0" + | hmi_widgets["«@id»"]`if "position()!=last()" > ,` + } + | ], + | required_detachables: { + foreach "$required_detachables" { + | "«@id»": detachable_elements["«@id»"]`if "position()!=last()" > ,` + } + | } + /* TODO generate some code for init() instead */ + apply "$parsed_widgets/widget[@id = $all_page_widgets/@id]", mode="per_page_widget_template"{ + with "page_desc", "$desc"; + } + | }`if "position()!=last()" > ,` +} + +emit "declarations:page-desc" { + | + | var page_desc = { + apply "$hmi_pages", mode="page_desc"; + | } +} + +template "*", mode="per_page_widget_template"; + + +emit "debug:detachable-pages" { + | + | DETACHABLES: + foreach "$detachable_elements"{ + | «@id» + } + | In Foreach: + foreach "$in_forEach_widget_ids"{ + | «.» + } +} diff -r 703ebf57508a -r a4bae7edca13 svghmi/gen_index_xhtml.xslt --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/svghmi/gen_index_xhtml.xslt Fri Jul 03 10:03:25 2020 +0200 @@ -0,0 +1,3737 @@ + + + + + + + + + HMI_PLC_STATUS + + + HMI_CURRENT_PAGE + + + + + + + + + + + + /* + + */ + + + + var hmi_hash = [ + + ]; + + + + var heartbeat_index = + + ; + + + + var hmitree_types = [ + + + /* + + + + */ " + + " + + , + + + + + ] + + + + + + + + + + + + + + / + + + / + + + + + / + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + =" + + " + + + + + + + + + + + + + + /* + + */ + + + + Raw HMI tree + + + + + Indexed HMI tree + + + + + Parsed Widgets + + + + + + + + + + + + /* + + */ + + + + ID, x, y, w, h + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Home + + + No Home page defined! + + + + + No page defined! + + + + + + + + + + + /* + + */ + + + + + + var default_page = " + + "; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + /* + + */ + + + + + + var detachable_elements = { + + + " + + ":[id(" + + "), id(" + + ")] + + , + + + + + } + + + + + + + + + + + + + + + + + " + + ": { + + bbox: [ + + , + + , + + , + + ], + + + + + Page id=" + + " : No match for path " + + " in HMI tree + + + page_index: + + , + + + relative_widgets: [ + + + hmi_widgets[" + + "] + + , + + + + + ], + + absolute_widgets: [ + + + hmi_widgets[" + + "] + + , + + + + + ], + + jumps: [ + + + + + + + + + + hmi_widgets[" + + "] + + , + + + + + + ], + + required_detachables: { + + + " + + ": detachable_elements[" + + "] + + , + + + + + } + + + + + } + + , + + + + + + + + + /* + + */ + + + + + + var page_desc = { + + + } + + + + + + + + + + /* + + */ + + + + + + DETACHABLES: + + + + + + + + In Foreach: + + + + + + + + + + + + + + + + + + + + + + + none + + + 100vh + + + 100vw + + + + + + + ViewBox settings other than X=0, Y=0 and Scale=1 are not supported + + + + + All units must be set to "px" in Inkscape's document properties + + + + + + + + + + + + + + + + + + href + + + width + + + height + + + x + + + y + + + + + + transform + + + style + + + + + + + + + + + + + + + + + + + ; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + _ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + /* + + */ + + + + let id = document.getElementById.bind(document); + + var svg_root = id(" + + "); + + + + + + + + + /* + + */ + + + + + + Unlinked : + + + + + + + + + + + + + + + " + + " + + , + + + + + + + + + Widget + + id=" + + " : No match for path " + + " in HMI tree + + + + + + , + + + + + + " + + ": new + + Widget (" + + ",[ + + ],[ + + ],{ + + + + + }) + + , + + + + + + + + + + + + + + + + + + + + + + + + + + + + /* + + */ + + + + class Widget { + + offset = 0; + + frequency = 10; /* FIXME arbitrary default max freq. Obtain from config ? */ + + unsubscribable = false; + + constructor(elt_id,args,indexes,members){ + + this.element_id = elt_id; + + this.element = id(elt_id); + + this.args = args; + + this.indexes = indexes; + + Object.keys(members).forEach(prop => this[prop]=members[prop]); + + } + + + + unsub(){ + + /* remove subsribers */ + + if(!this.unsubscribable) for(let index of this.indexes){ + + let idx = index + this.offset; + + subscribers[idx].delete(this); + + } + + this.offset = 0; + + } + + + + sub(new_offset=0){ + + /* set the offset because relative */ + + this.offset = new_offset; + + /* add this's subsribers */ + + if(!this.unsubscribable) for(let index of this.indexes){ + + subscribers[index + new_offset].add(this); + + } + + need_cache_apply.push(this); + + } + + + + apply_cache() { + + if(!this.unsubscribable) for(let index of this.indexes){ + + /* dispatch current cache in newly opened page widgets */ + + let realindex = index+this.offset; + + let cached_val = cache[realindex]; + + if(cached_val != undefined) + + dispatch_value_to_widget(this, realindex, cached_val, cached_val); + + } + + } + + + + } + + + + + + + + + /* + + */ + + + + + + + + + + class + + Widget extends Widget{ + + /* empty class, as + + widget didn't provide any */ + + } + + + + + + + + + /* + + */ + + + + var hmi_widgets = { + + + } + + + + + + + + + + + + + + + + + + + widget must have a + + element + + + + + + + _elt: id(" + + "), + + + + + _sub: { + + + + + + + + + + widget must have a + + / + + element + + + /* missing + + / + + element */ + + + + " + + ": id(" + + ") + + , + + + + + + + }, + + + + + + + + + + + + + + + + + + + + + class BackWidget extends Widget{ + + on_click(evt) { + + if(jump_history.length > 1){ + + jump_history.pop(); + + let [page_name, index] = jump_history.pop(); + + switch_page(page_name, index); + + } + + } + + init() { + + this.element.setAttribute("onclick", "hmi_widgets['"+this.element_id+"'].on_click(evt)"); + + } + + } + + + + + + + + active inactive + + + + frequency: 5, + + on_mouse_down: function(evt) { + + if (this.active_style && this.inactive_style) { + + this.active_elt.setAttribute("style", this.active_style); + + this.inactive_elt.setAttribute("style", "display:none"); + + } + + change_hmi_value(this.indexes[0], "=1"); + + }, + + on_mouse_up: function(evt) { + + if (this.active_style && this.inactive_style) { + + this.active_elt.setAttribute("style", "display:none"); + + this.inactive_elt.setAttribute("style", this.inactive_style); + + } + + change_hmi_value(this.indexes[0], "=0"); + + }, + + active_style: undefined, + + inactive_style: undefined, + + init: function() { + + this.active_style = this.active_elt ? this.active_elt.style.cssText : undefined; + + this.inactive_style = this.inactive_elt ? this.inactive_elt.style.cssText : undefined; + + if (this.active_style && this.inactive_style) { + + this.active_elt.setAttribute("style", "display:none"); + + this.inactive_elt.setAttribute("style", this.inactive_style); + + } + + this.element.setAttribute("onmousedown", "hmi_widgets[' + + '].on_mouse_down(evt)"); + + this.element.setAttribute("onmouseup", "hmi_widgets[' + + '].on_mouse_up(evt)"); + + }, + + + + + frequency: 10, + + + + + path + + + + + + value min max + + + + dispatch: function(value) { + + if(this.value_elt) + + this.value_elt.textContent = String(value); + + let [min,max,start,end] = this.range; + + let [cx,cy] = this.center; + + let [rx,ry] = this.proportions; + + let tip = start + (end-start)*Number(value)/(max-min); + + let size = 0; + + if (tip-start > Math.PI) { + + size = 1; + + } else { + + size = 0; + + } + + this.path_elt.setAttribute('d', "M "+(cx+rx*Math.cos(start))+","+(cy+ry*Math.sin(start))+" A "+rx+","+ry+" 0 "+size+" 1 "+(cx+rx*Math.cos(tip))+","+(cy+ry*Math.sin(tip))); + + }, + + range: undefined, + + init: function() { + + let start = Number(this.path_elt.getAttribute('sodipodi:start')); + + let end = Number(this.path_elt.getAttribute('sodipodi:end')); + + let cx = Number(this.path_elt.getAttribute('sodipodi:cx')); + + let cy = Number(this.path_elt.getAttribute('sodipodi:cy')); + + let rx = Number(this.path_elt.getAttribute('sodipodi:rx')); + + let ry = Number(this.path_elt.getAttribute('sodipodi:ry')); + + if (ry == 0) { + + ry = rx; + + } + + if (start > end) { + + end = end + 2*Math.PI; + + } + + let min = this.min_elt ? + + Number(this.min_elt.textContent) : + + this.args.length >= 1 ? this.args[0] : 0; + + let max = this.max_elt ? + + Number(this.max_elt.textContent) : + + this.args.length >= 2 ? this.args[1] : 100; + + this.range = [min, max, start, end]; + + this.center = [cx, cy]; + + this.proportions = [rx, ry]; + + }, + + + + + frequency: 5, + + dispatch: function(value) { + + + + this.element.textContent = String(value); + + + + + Display widget as a group not implemented + + + + }, + + + + + + + + text box button + + + dispatch: function(value) { + + if(!this.opened) this.set_selection(value); + + }, + + init: function() { + + this.button_elt.setAttribute("onclick", "hmi_widgets[' + + '].on_button_click()"); + + // Save original size of rectangle + + this.box_bbox = this.box_elt.getBBox() + + + + // Compute margins + + text_bbox = this.text_elt.getBBox() + + lmargin = text_bbox.x - this.box_bbox.x; + + tmargin = text_bbox.y - this.box_bbox.y; + + this.margins = [lmargin, tmargin].map(x => Math.max(x,0)); + + + + // It is assumed that list content conforms to Array interface. + + this.content = [ + + + " + + ", + + + ]; + + + + // Index of first visible element in the menu, when opened + + this.menu_offset = 0; + + + + // How mutch to lift the menu vertically so that it does not cross bottom border + + this.lift = 0; + + + + // Event handlers cannot be object method ('this' is unknown) + + // as a workaround, handler given to addEventListener is bound in advance. + + this.bound_close_on_click_elsewhere = this.close_on_click_elsewhere.bind(this); + + + + this.opened = false; + + }, + + // Called when a menu entry is clicked + + on_selection_click: function(selection) { + + this.close(); + + let orig = this.indexes[0]; + + let idx = this.offset ? orig - this.offset : orig; + + apply_hmi_value(idx, selection); + + }, + + on_button_click: function() { + + this.open(); + + }, + + on_backward_click: function(){ + + this.scroll(false); + + }, + + on_forward_click:function(){ + + this.scroll(true); + + }, + + set_selection: function(value) { + + let display_str; + + if(value >= 0 && value < this.content.length){ + + // if valid selection resolve content + + display_str = this.content[value]; + + this.last_selection = value; + + } else { + + // otherwise show problem + + display_str = "?"+String(value)+"?"; + + } + + // It is assumed that first span always stays, + + // and contains selection when menu is closed + + this.text_elt.firstElementChild.textContent = display_str; + + }, + + grow_text: function(up_to) { + + let count = 1; + + let txt = this.text_elt; + + let first = txt.firstElementChild; + + // Real world (pixels) boundaries of current page + + let bounds = svg_root.getBoundingClientRect(); + + this.lift = 0; + + while(count < up_to) { + + let next = first.cloneNode(); + + // relative line by line text flow instead of absolute y coordinate + + next.removeAttribute("y"); + + next.setAttribute("dy", "1.1em"); + + // default content to allow computing text element bbox + + next.textContent = "..."; + + // append new span to text element + + txt.appendChild(next); + + // now check if text extended by one row fits to page + + // FIXME : exclude margins to be more accurate on box size + + let rect = txt.getBoundingClientRect(); + + if(rect.bottom > bounds.bottom){ + + // in case of overflow at the bottom, lift up one row + + let backup = first.getAttribute("dy"); + + // apply lift asr a dy added too first span (y attrib stays) + + first.setAttribute("dy", "-"+String((this.lift+1)*1.1)+"em"); + + rect = txt.getBoundingClientRect(); + + if(rect.top > bounds.top){ + + this.lift += 1; + + } else { + + // if it goes over the top, then backtrack + + // restore dy attribute on first span + + if(backup) + + first.setAttribute("dy", backup); + + else + + first.removeAttribute("dy"); + + // remove unwanted child + + txt.removeChild(next); + + return count; + + } + + } + + count++; + + } + + return count; + + }, + + close_on_click_elsewhere: function(e) { + + // inhibit events not targetting spans (menu items) + + if(e.target.parentNode !== this.text_elt){ + + e.stopPropagation(); + + // close menu in case click is outside box + + if(e.target !== this.box_elt) + + this.close(); + + } + + }, + + close: function(){ + + // Stop hogging all click events + + svg_root.removeEventListener("click", this.bound_close_on_click_elsewhere, true); + + // Restore position and sixe of widget elements + + this.reset_text(); + + this.reset_box(); + + // Put the button back in place + + this.element.appendChild(this.button_elt); + + // Mark as closed (to allow dispatch) + + this.opened = false; + + // Dispatch last cached value + + this.apply_cache(); + + }, + + // Set text content when content is smaller than menu (no scrolling) + + set_complete_text: function(){ + + let spans = this.text_elt.children; + + let c = 0; + + for(let item of this.content){ + + let span=spans[c]; + + span.textContent = item; + + span.setAttribute("onclick", "hmi_widgets[' + + '].on_selection_click("+c+")"); + + c++; + + } + + }, + + // Move partial view : + + // false : upward, lower value + + // true : downward, higher value + + scroll: function(forward){ + + let contentlength = this.content.length; + + let spans = this.text_elt.children; + + let spanslength = spans.length; + + // reduce accounted menu size according to jumps + + if(this.menu_offset != 0) spanslength--; + + if(this.menu_offset < contentlength - 1) spanslength--; + + if(forward){ + + this.menu_offset = Math.min( + + contentlength - spans.length + 1, + + this.menu_offset + spanslength); + + }else{ + + this.menu_offset = Math.max( + + 0, + + this.menu_offset - spanslength); + + } + + console.log(this.menu_offset); + + this.set_partial_text(); + + }, + + // Setup partial view text content + + // with jumps at first and last entry when appropriate + + set_partial_text: function(){ + + let spans = this.text_elt.children; + + let contentlength = this.content.length; + + let spanslength = spans.length; + + let i = this.menu_offset, c = 0; + + while(c < spanslength){ + + let span=spans[c]; + + // backward jump only present if not exactly at start + + if(c == 0 && i != 0){ + + span.textContent = "↑ ↑ ↑"; + + span.setAttribute("onclick", "hmi_widgets[' + + '].on_backward_click()"); + + // presence of forward jump when not right at the end + + }else if(c == spanslength-1 && i < contentlength - 1){ + + span.textContent = "↓ ↓ ↓"; + + span.setAttribute("onclick", "hmi_widgets[' + + '].on_forward_click()"); + + // otherwise normal content + + }else{ + + span.textContent = this.content[i]; + + span.setAttribute("onclick", "hmi_widgets[' + + '].on_selection_click("+i+")"); + + i++; + + } + + c++; + + } + + }, + + open: function(){ + + let length = this.content.length; + + // systematically reset text, to strip eventual whitespace spans + + this.reset_text(); + + // grow as much as needed or possible + + let slots = this.grow_text(length); + + // Depending on final size + + if(slots == length) { + + // show all at once + + this.set_complete_text(); + + } else { + + // eventualy align menu to current selection, compensating for lift + + let offset = this.last_selection - this.lift; + + if(offset > 0) + + this.menu_offset = Math.min(offset + 1, length - slots + 1); + + else + + this.menu_offset = 0; + + // show surrounding values + + this.set_partial_text(); + + } + + // Now that text size is known, we can set the box around it + + this.adjust_box_to_text(); + + // Take button out until menu closed + + this.element.removeChild(this.button_elt); + + // Rise widget to top by moving it to last position among siblings + + this.element.parentNode.appendChild(this.element.parentNode.removeChild(this.element)); + + // disable interaction with background + + svg_root.addEventListener("click", this.bound_close_on_click_elsewhere, true); + + // mark as open + + this.opened = true; + + }, + + // Put text element in normalized state + + reset_text: function(){ + + let txt = this.text_elt; + + let first = txt.firstElementChild; + + // remove attribute eventually added to first text line while opening + + first.removeAttribute("onclick"); + + first.removeAttribute("dy"); + + // keep only the first line of text + + for(let span of Array.from(txt.children).slice(1)){ + + txt.removeChild(span) + + } + + }, + + // Put rectangle element in saved original state + + reset_box: function(){ + + let m = this.box_bbox; + + let b = this.box_elt; + + b.x.baseVal.value = m.x; + + b.y.baseVal.value = m.y; + + b.width.baseVal.value = m.width; + + b.height.baseVal.value = m.height; + + }, + + // Use margin and text size to compute box size + + adjust_box_to_text: function(){ + + let [lmargin, tmargin] = this.margins; + + let m = this.text_elt.getBBox(); + + let b = this.box_elt; + + b.x.baseVal.value = m.x - lmargin; + + b.y.baseVal.value = m.y - tmargin; + + b.width.baseVal.value = 2 * lmargin + m.width; + + b.height.baseVal.value = 2 * tmargin + m.height; + + }, + + + + + + + + + + + + index_pool: [ + + + + + + , + + + + + ], + + init: function() { + + + + + + + id(" + + ").setAttribute("onclick", "hmi_widgets[' + + '].on_click(' + + ', evt)"); + + + + + this.items = [ + + + + + + + + + [ /* item=" + + " path=" + + " */ + + + + Missing item labeled + + in ForEach widget + + + + + + + Widget id=" + + " label=" + + " is having wrong path. Accroding to ForEach widget ancestor id=" + + ", path should be descendant of " + + ". + + + hmi_widgets[" + + "] + + , + + + + + ] + + , + + + + + ] + + }, + + item_offset: 0, + + + + class ForEachWidget extends Widget{ + + unsub(){ + + for(let item of this.items){ + + for(let widget of item) { + + widget.unsub(); + + } + + } + + this.offset = 0; + + } + + + + foreach_widgets_do(new_offset, todo){ + + this.offset = new_offset; + + for(let i = 0; i < this.items.length; i++) { + + let item = this.items[i]; + + let orig_item_index = this.index_pool[i]; + + let item_index = this.index_pool[i+this.item_offset]; + + let item_index_offset = item_index - orig_item_index; + + for(let widget of item) { + + todo(widget).call(widget, new_offset + item_index_offset); + + } + + } + + } + + + + sub(new_offset=0){ + + this.foreach_widgets_do(new_offset, w=>w.sub); + + } + + + + apply_cache() { + + this.foreach_widgets_do(this.offset, w=>w.apply_cache); + + } + + + + on_click(opstr, evt) { + + let new_item_offset = eval(String(this.item_offset)+opstr); + + if(new_item_offset + this.items.length > this.index_pool.length) { + + if(this.item_offset + this.items.length == this.index_pool.length) + + new_item_offset = 0; + + else + + new_item_offset = this.index_pool.length - this.items.length; + + } else if(new_item_offset < 0) { + + if(this.item_offset == 0) + + new_item_offset = this.index_pool.length - this.items.length; + + else + + new_item_offset = 0; + + } + + this.item_offset = new_item_offset; + + this.unsub(); + + this.sub(this.offset); + + update_subscriptions(); + + need_cache_apply.push(this); + + jumps_need_update = true; + + requestHMIAnimation(); + + } + + } + + + + + + + + + value + + + + + + + + frequency: 5, + + + last_val: undefined, + + dispatch: function(value) { + + this.last_val = value; + + + this.value_elt.textContent = String(value); + + + }, + + + init: function() { + + + id(" + + ").setAttribute("onclick", "hmi_widgets[' + + '].on_edit_click()"); + + + + id(" + + ").setAttribute("onclick", "hmi_widgets[' + + '].on_op_click(' + + ')"); + + + }, + + on_op_click: function(opstr) { + + let orig = this.indexes[0]; + + let idx = this.offset ? orig - this.offset : orig; + + let new_val = change_hmi_value(idx, opstr); + + }, + + on_edit_click: function(opstr) { + + edit_value(" + + ", " + + ", this, this.last_val); + + }, + + edit_callback: function(new_val) { + + let orig = this.indexes[0]; + + let idx = this.offset ? orig - this.offset : orig; + + apply_hmi_value(idx, new_val); + + }, + + + + + + + + active inactive + + + + + + + + + + disabled + + + + + + + + + + + + + + + + + + + + + + active: false, + + + disabled: false, + + frequency: 2, + + dispatch: function(value) { + + this.disabled = !Number(value); + + this.update(); + + }, + + + update: function(){ + + + if(this.disabled) { + + /* show disabled */ + + this.disabled_elt.setAttribute("style", this.active_elt_style); + + /* hide inactive */ + + this.inactive_elt.setAttribute("style", "display:none"); + + /* hide active */ + + this.active_elt.setAttribute("style", "display:none"); + + } else { + + /* hide disabled */ + + this.disabled_elt.setAttribute("style", "display:none"); + + + if(this.active) { + + /* show active */ + + this.active_elt.setAttribute("style", this.active_elt_style); + + /* hide inactive */ + + this.inactive_elt.setAttribute("style", "display:none"); + + } else { + + /* show inactive */ + + this.inactive_elt.setAttribute("style", this.inactive_elt_style); + + /* hide active */ + + this.active_elt.setAttribute("style", "display:none"); + + } + + + } + + + }, + + + on_click: function(evt) { + + const index = this.indexes.length > 0 ? this.indexes[0] + this.offset : undefined; + + const name = this.args[0]; + + switch_page(name, index); + + }, + + + notify_page_change: function(page_name, index){ + + const ref_index = this.indexes.length > 0 ? this.indexes[0] + this.offset : undefined; + + const ref_name = this.args[0]; + + this.active =((ref_name == undefined || ref_name == page_name) && index == ref_index); + + this.update(); + + }, + + + init: function() { + + this.element.setAttribute("onclick", "hmi_widgets[' + + '].on_click(evt)"); + + + this.active_elt_style = this.active_elt.getAttribute("style"); + + this.inactive_elt_style = this.inactive_elt.getAttribute("style"); + + + + + this.disabled_elt_style = this.disabled_elt.getAttribute("style"); + + + + this.unsubscribable = true; + + + + }, + + + + + + + + + + + + + + + + + + + + + + + + + + + + Jump id=" + + " to page " + + " with incompatible path " + + (must be same class as " + + ") + + + + + + + + + /* + + */ + + + + var jumps_need_update = false; + + var jump_history = [[default_page, undefined]]; + + + + function update_jumps() { + + page_desc[current_visible_page].jumps.map(w=>w.notify_page_change(current_visible_page,current_page_index)); + + jumps_need_update = false; + + }; + + + + + + + + + + + /* + + */ + + + + + + var keypads = { + + + + + + " + + ":[" + + ", + + , + + ], + + + + } + + + + + + + + + + Esc Enter BackSpace Keys Info Value + + + + + + Sign Space NumDot + + + + + + + CapsLock Shift + + + + + init: function() { + + + id(" + + ").setAttribute("onclick", "hmi_widgets[' + + '].on_key_click(' + + ')"); + + + + if(this. + + _elt) + + this. + + _elt.setAttribute("onclick", "hmi_widgets[' + + '].on_ + + _click()"); + + + }, + + on_key_click: function(symbols) { + + var syms = symbols.split(" "); + + this.shift |= this.caps; + + this.editstr += syms[this.shift?syms.length-1:0]; + + this.shift = false; + + this.update(); + + }, + + on_Esc_click: function() { + + end_modal.call(this); + + }, + + on_Enter_click: function() { + + end_modal.call(this); + + callback_obj = this.result_callback_obj; + + callback_obj.edit_callback(this.editstr); + + }, + + on_BackSpace_click: function() { + + this.editstr = this.editstr.slice(0,this.editstr.length-1); + + this.update(); + + }, + + on_Sign_click: function() { + + if(this.editstr[0] == "-") + + this.editstr = this.editstr.slice(1,this.editstr.length); + + else + + this.editstr = "-" + this.editstr; + + this.update(); + + }, + + on_NumDot_click: function() { + + if(this.editstr.indexOf(".") == "-1"){ + + this.editstr += "."; + + this.update(); + + } + + }, + + on_Space_click: function() { + + this.editstr += " "; + + this.update(); + + }, + + caps: false, + + _caps: undefined, + + on_CapsLock_click: function() { + + this.caps = !this.caps; + + this.update(); + + }, + + shift: false, + + _shift: undefined, + + on_Shift_click: function() { + + this.shift = !this.shift; + + this.caps = false; + + this.update(); + + }, + + + coordinates: [ + + , + + ], + + editstr: "", + + _editstr: undefined, + + result_callback_obj: undefined, + + start_edit: function(info, valuetype, callback_obj, initial) { + + show_modal.call(this); + + this.editstr = initial; + + this.result_callback_obj = callback_obj; + + this.Info_elt.textContent = info; + + this.shift = false; + + this.caps = false; + + this.update(); + + }, + + update: function() { + + if(this.editstr != this._editstr){ + + this._editstr = this.editstr; + + this.Value_elt.textContent = this.editstr; + + } + + if(this.shift != this._shift){ + + this._shift = this.shift; + + (this.shift?widget_active_activable:widget_inactive_activable)(this.Shift_sub); + + } + + if(this.caps != this._caps){ + + this._caps = this.caps; + + (this.caps?widget_active_activable:widget_inactive_activable)(this.CapsLock_sub); + + } + + }, + + + + + frequency: 10, + + + + + needle range + + + + + + value min max + + + + dispatch: function(value) { + + if(this.value_elt) + + this.value_elt.textContent = String(value); + + let [min,max,totallength] = this.range; + + let length = Math.max(0,Math.min(totallength,(Number(value)-min)*totallength/(max-min))); + + let tip = this.range_elt.getPointAtLength(length); + + this.needle_elt.setAttribute('d', "M "+this.origin.x+","+this.origin.y+" "+tip.x+","+tip.y); + + }, + + origin: undefined, + + range: undefined, + + init: function() { + + let min = this.min_elt ? + + Number(this.min_elt.textContent) : + + this.args.length >= 1 ? this.args[0] : 0; + + let max = this.max_elt ? + + Number(this.max_elt.textContent) : + + this.args.length >= 2 ? this.args[1] : 100; + + this.range = [min, max, this.range_elt.getTotalLength()] + + this.origin = this.needle_elt.getPointAtLength(0); + + }, + + + + class SwitchWidget extends Widget{ + + frequency = 5; + + dispatch(value) { + + for(let choice of this.choices){ + + if(value != choice.value){ + + choice.elt.setAttribute("style", "display:none"); + + } else { + + choice.elt.setAttribute("style", choice.style); + + } + + } + + } + + } + + + + + choices: [ + + + + + { + + elt:id(" + + "), + + style:" + + ", + + value: + + + + } + + , + + + + + ], + + + + + + + + active inactive + + + frequency: 5, + + state: 0, + + dispatch: function(value) { + + this.state = value; + + if (this.state) { + + this.active_elt.setAttribute("style", this.active_style); + + this.inactive_elt.setAttribute("style", "display:none"); + + this.state = 0; + + } else { + + this.inactive_elt.setAttribute("style", this.inactive_style); + + this.active_elt.setAttribute("style", "display:none"); + + this.state = 1; + + } + + }, + + on_click: function(evt) { + + change_hmi_value(this.indexes[0], "="+this.state); + + }, + + active_style: undefined, + + inactive_style: undefined, + + init: function() { + + this.active_style = this.active_elt.style.cssText; + + this.inactive_style = this.inactive_elt.style.cssText; + + this.element.setAttribute("onclick", "hmi_widgets[' + + '].on_click(evt)"); + + }, + + + + + Made with SVGHMI. https://beremiz.org + + + + + + + + + + + + + diff -r 703ebf57508a -r a4bae7edca13 svghmi/gen_index_xhtml.ysl2 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/svghmi/gen_index_xhtml.ysl2 Fri Jul 03 10:03:25 2020 +0200 @@ -0,0 +1,91 @@ +include yslt_noindent.yml2 + +// overrides yslt's output function to set CDATA +decl output(method, cdata-section-elements="xhtml:script"); + +// helper to emit some content to internal namespaces +decl emit(*name) alias - { + *name; + template *name { + | + | /* «local-name()» */ + | + content; + | + } +}; + +istylesheet + /* From Inkscape */ + xmlns:dc="http://purl.org/dc/elements/1.1/" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns:xlink="http://www.w3.org/1999/xlink" + xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" + xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" + xmlns:xhtml="http://www.w3.org/1999/xhtml" + + /* Internal namespaces to allow emit code/content from anywhere */ + xmlns:debug="debug" + xmlns:preamble="preamble" + xmlns:declarations="declarations" + xmlns:definitions="definitions" + xmlns:epilogue="epilogue" + + /* Namespace to invoke python code */ + xmlns:ns="beremiz" + + extension-element-prefixes="ns func exsl regexp str dyn" + exclude-result-prefixes="ns func exsl regexp str dyn debug preamble epilogue declarations definitions" { + + const "svg", "/svg:svg"; + const "hmi_elements", "//svg:*[starts-with(@inkscape:label, 'HMI:')]"; + + + include hmi_tree.ysl2 + + include geometry.ysl2 + + include detachable_pages.ysl2 + + include inline_svg.ysl2 + + include widgets_common.ysl2 + + include widget_*.ysl2 + + + template "/" { + comment > Made with SVGHMI. https://beremiz.org + + // all debug output from included definitions, as comments + comment apply "document('')/*/debug:*"; + + html xmlns="http://www.w3.org/1999/xhtml" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns:xlink="http://www.w3.org/1999/xlink" { + head; + body style="margin:0;overflow:hidden;" { + // Inline SVG + copy "$result_svg"; + script{ + | \n//\n//\n// Early independent declarations \n//\n// + apply "document('')/*/preamble:*"; + + | \n//\n//\n// Declarations depending on preamble \n//\n// + apply "document('')/*/declarations:*"; + + | \n//\n//\n// Order independent declaration and code \n//\n// + apply "document('')/*/definitions:*"; + + | \n//\n//\n// Statements that needs to be at the end \n//\n// + apply "document('')/*/epilogue:*"; + + include text svghmi.js + + } + } + } + } +} diff -r 703ebf57508a -r a4bae7edca13 svghmi/geometry.ysl2 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/svghmi/geometry.ysl2 Fri Jul 03 10:03:25 2020 +0200 @@ -0,0 +1,144 @@ +// geometry.ysl2 +// +// Geometry (bounding box intersection) definitions + +// This retrieves geometry obtained through "inkscape -S" +// already parsed by python and presented as a list of +// +const "geometry", "ns:GetSVGGeometry()"; + +// Debug data +emit "debug:geometry" { + | ID, x, y, w, h + foreach "$geometry" + | «@Id» «@x» «@y» «@w» «@h» +} + +// Rates 1D intersection of 2 segments A and B +// described respectively with a0,a1 and b0,b1 +def "func:intersect_1d" { + // it is assumed that a1 > a0 and b1 > b0 + param "a0"; + param "a1"; + param "b0"; + param "b1"; + + const "d0", "$a0 >= $b0"; + const "d1", "$a1 >= $b1"; + choose { + when "not($d0) and $d1" + // b contained in a + // a0 0 ))]"""; +} diff -r 703ebf57508a -r a4bae7edca13 svghmi/hmi_tree.ysl2 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/svghmi/hmi_tree.ysl2 Fri Jul 03 10:03:25 2020 +0200 @@ -0,0 +1,163 @@ +// hmi_tree.ysl2 + + +// HMI Tree computed from VARIABLES.CSV in svghmi.py +const "hmitree", "ns:GetHMITree()"; + +const "_categories" { + noindex > HMI_PLC_STATUS + noindex > HMI_CURRENT_PAGE +} +const "categories", "exsl:node-set($_categories)"; + +// HMI Tree Index +const "_indexed_hmitree" apply "$hmitree", mode="index"; +const "indexed_hmitree", "exsl:node-set($_indexed_hmitree)"; + +emit "preamble:hmi-tree" { + | var hmi_hash = [«$hmitree/@hash»]; + | + | var heartbeat_index = «$indexed_hmitree/*[@hmipath = '/HEARTBEAT']/@index»; + | + | var hmitree_types = [ + + foreach "$indexed_hmitree/*" + | /* «@index» «@hmipath» */ "«substring(local-name(), 5)»"`if "position()!=last()" > ,` + + | ] + | +} + +template "*", mode="index" { + param "index", "0"; + param "parentpath", "''"; + const "content" { + const "path" + choose { + when "count(ancestor::*)=0" > / + when "count(ancestor::*)=1" > /«@name» + otherwise > «$parentpath»/«@name» + } + choose { + when "not(local-name() = $categories/noindex)" { + xsl:copy { + attrib "index" > «$index» + attrib "hmipath" > «$path» + foreach "@*" xsl:copy; + } + apply "*[1]", mode="index"{ + with "index", "$index + 1"; + with "parentpath" > «$path» + } + } + otherwise { + apply "*[1]", mode="index"{ + with "index", "$index"; + with "parentpath" > «$path» + } + } + } + } + + copy "$content"; + apply "following-sibling::*[1]", mode="index" { + with "index", "$index + count(exsl:node-set($content)/*)"; + with "parentpath" > «$parentpath» + } +} + +// Parses: +// "HMI:WidgetType:param1:param2@path1@path2" +// +// Into: +// widget type="WidgetType" id="blah456" { +// arg value="param1"; +// arg value="param2"; +// path value="path1" index="345"; +// path value="path2"; +// } +// +template "*", mode="parselabel" { + const "label","@inkscape:label"; + const "description", "substring-after($label,'HMI:')"; + + const "_args", "substring-before($description,'@')"; + const "args" choose { + when "$_args" value "$_args"; + otherwise value "$description"; + } + + const "_type", "substring-before($args,':')"; + const "type" choose { + when "$_type" value "$_type"; + otherwise value "$args"; + } + + if "$type" widget { + attrib "id" > «@id» + attrib "type" > «$type» + foreach "str:split(substring-after($args, ':'), ':')" { + arg { + attrib "value" > «.» + } + } + const "paths", "substring-after($description,'@')"; + foreach "str:split($paths, '@')" { + if "string-length(.) > 0" path { + attrib "value" > «.» + const "path", "."; + const "item", "$indexed_hmitree/*[@hmipath = $path]"; + if "count($item) = 1" { + attrib "index" > «$item/@index» + attrib "type" > «local-name($item)» + } + } + } + } +} + +const "_parsed_widgets" apply "$hmi_elements", mode="parselabel"; +const "parsed_widgets","exsl:node-set($_parsed_widgets)"; + +def "func:widget" { + param "id"; + result "$parsed_widgets/widget[@id = $id]"; +} + +def "func:is_descendant_path" { + param "descend"; + param "ancest"; + // TODO : use HMI tree to answer more accurately + result "string-length($ancest) > 0 and starts-with($descend,$ancest)"; +} + +def "func:same_class_paths" { + param "a"; + param "b"; + const "class_a", "$indexed_hmitree/*[@hmipath = $a]/@class"; + const "class_b", "$indexed_hmitree/*[@hmipath = $b]/@class"; + result "$class_a and $class_b and $class_a = $class_b"; +} + +// Debug data +template "*", mode="testtree"{ + param "indent", "''"; + > «$indent» «local-name()» + foreach "@*" > «local-name()»="«.»" + > \n + apply "*", mode="testtree" { + with "indent" value "concat($indent,'>')" + }; +} + +emit "debug:hmi-tree" { + | Raw HMI tree + apply "$hmitree", mode="testtree"; + | + | Indexed HMI tree + apply "$indexed_hmitree", mode="testtree"; + | + | Parsed Widgets + copy "_parsed_widgets"; + apply "$parsed_widgets", mode="testtree"; +} diff -r 703ebf57508a -r a4bae7edca13 svghmi/inline_svg.ysl2 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/svghmi/inline_svg.ysl2 Fri Jul 03 10:03:25 2020 +0200 @@ -0,0 +1,161 @@ +// inline_svg.ysl2 +// +// Produce Inline SVG element of resulting XHTML page. + +// Since stylesheet output namespace is xhtml, templates that output svg have to be explicitely declared as such +in xsl decl svgtmpl(match, xmlns="http://www.w3.org/2000/svg") alias template; +in xsl decl svgfunc(name, xmlns="http://www.w3.org/2000/svg") alias template; + + +// Identity template : +// - copy every attributes +// - copy every sub-elements +template "@* | node()", mode="inline_svg" { + // use real xsl:copy instead copy-of alias from yslt.yml2 + if "not(@id = $discardable_elements/@id)" + xsl:copy apply "@* | node()", mode="inline_svg"; +} + +// replaces inkscape's height and width hints. forces fit +template "svg:svg/@width", mode="inline_svg"; +template "svg:svg/@height", mode="inline_svg"; +svgtmpl "svg:svg", mode="inline_svg" svg { + attrib "preserveAspectRatio" > none + attrib "height" > 100vh + attrib "width" > 100vw + apply "@* | node()", mode="inline_svg"; +} +// ensure that coordinate in CSV file generated by inkscape are in default reference frame +template "svg:svg[@viewBox!=concat('0 0 ', @width, ' ', @height)]", mode="inline_svg" { + error > ViewBox settings other than X=0, Y=0 and Scale=1 are not supported +} +// ensure that coordinate in CSV file generated by inkscape match svg default unit +template "sodipodi:namedview[@units!='px' or @inkscape:document-units!='px']", mode="inline_svg" { + error > All units must be set to "px" in Inkscape's document properties +} + +////// Clone unlinking +// +// svg:use (inkscape's clones) inside a widgets are +// replaced by real elements they refer in order to : +// - allow finding "needle" element in "meter" widget, +// even if "needle" is in a group refered by a svg use. +// - if "needle" is visible through a svg:use for +// each instance of the widget, then needle would show +// the same position in all instances +// +// For now, clone unlinkink applies to descendants of all widget except HMI:Page +// TODO: narrow application of clone unlinking to active elements, +// while keeping static decoration cloned +const "to_unlink", "$hmi_elements[not(@id = $hmi_pages)]/descendant-or-self::svg:use"; +svgtmpl "svg:use", mode="inline_svg" +{ + choose { + when "@id = $to_unlink/@id" + call "unlink_clone"; + otherwise + xsl:copy apply "@* | node()", mode="inline_svg"; + } +} + +// to unlink a clone, an group containing a copy of target element is created +// that way, style and transforms can be preserved +const "_excluded_use_attrs" { + name > href + name > width + name > height + name > x + name > y +} +const "excluded_use_attrs","exsl:node-set($_excluded_use_attrs)"; + +const "_merge_use_attrs" { + name > transform + name > style +} +const "merge_use_attrs","exsl:node-set($_merge_use_attrs)"; + +svgfunc "unlink_clone"{ + const "targetid","substring-after(@xlink:href,'#')"; + const "target", "//svg:*[@id = $targetid]"; + g{ + choose { + when "$target[self::svg:g]" { + foreach "@*[not(local-name() = $excluded_use_attrs/name | $merge_use_attrs)]" + attrib "{name()}" > «.» + + if "@style | $target/@style" + attrib "style" { + > «@style» + if "@style and $target/@style" > ; + > «$target/@style» + } + + if "@transform | $target/@transform" + attrib "transform" { + > «@transform» + if "@transform and $target/@transform" > + > «$target/@transform» + } + + apply "$target/*", mode="unlink_clone"{ + with "seed","@id"; + } + } + otherwise { + // include non excluded attributes + foreach "@*[not(local-name() = $excluded_use_attrs/name)]" + attrib "{name()}" > «.» + + apply "$target", mode="unlink_clone"{ + with "seed","@id"; + } + } + } + } +} + +// clone unlinking is really similar to deep-copy +// all nodes are sytematically copied +svgtmpl "@id", mode="unlink_clone" { + param "seed"; + attrib "id" > «$seed»_«.» +} + +svgtmpl "@*", mode="unlink_clone" xsl:copy; + +// copying widgets would have unwanted effect +// instead widget is refered through a svg:use. +svgtmpl "svg:*", mode="unlink_clone" { + param "seed"; + choose { + // node recursive copy ends when finding a widget + when "@id = $hmi_elements/@id" { + // place a clone instead of copying + use{ + attrib "xlink:href" > «concat('#',@id)» + } + } + otherwise { + xsl:copy apply "@* | node()", mode="unlink_clone" { + with "seed","$seed"; + } + } + } +} + +const "result_svg" apply "/", mode="inline_svg"; +const "result_svg_ns", "exsl:node-set($result_svg)"; + +emit "preamble:inline-svg" { + | let id = document.getElementById.bind(document); + | var svg_root = id("«$svg/@id»"); +} + +emit "debug:clone-unlinking" { + | + | Unlinked : + foreach "$to_unlink"{ + | «@id» + } +} diff -r 703ebf57508a -r a4bae7edca13 svghmi/pous.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/svghmi/pous.xml Fri Jul 03 10:03:25 2020 +0200 @@ -0,0 +1,50 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff -r 703ebf57508a -r a4bae7edca13 svghmi/svghmi.c --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/svghmi/svghmi.c Fri Jul 03 10:03:25 2020 +0200 @@ -0,0 +1,370 @@ +#include +#include +#include "iec_types_all.h" +#include "POUS.h" +#include "config.h" +#include "beremiz.h" + +#define DEFAULT_REFRESH_PERIOD_MS 100 +#define HMI_BUFFER_SIZE %(buffer_size)d +#define HMI_ITEM_COUNT %(item_count)d +#define HMI_HASH_SIZE 8 +static uint8_t hmi_hash[HMI_HASH_SIZE] = {%(hmi_hash_ints)s}; + +/* PLC reads from that buffer */ +static char rbuf[HMI_BUFFER_SIZE]; + +/* PLC writes to that buffer */ +static char wbuf[HMI_BUFFER_SIZE]; + +/* TODO change that in case of multiclient... */ +/* worst biggest send buffer. FIXME : use dynamic alloc ? */ +static char sbuf[HMI_HASH_SIZE + HMI_BUFFER_SIZE + (HMI_ITEM_COUNT * sizeof(uint32_t))]; +static unsigned int sbufidx; + +%(extern_variables_declarations)s + +#define ticktime_ns %(PLC_ticktime)d +static uint16_t ticktime_ms = (ticktime_ns>1000000)? + ticktime_ns/1000000: + 1; + +typedef enum { + buf_free = 0, + buf_new, + buf_set, + buf_tosend +} buf_state_t; + +static int global_write_dirty = 0; + +typedef struct { + void *ptr; + __IEC_types_enum type; + uint32_t buf_index; + + /* publish/write/send */ + long wlock; + buf_state_t wstate; + + /* zero means not subscribed */ + uint16_t refresh_period_ms; + uint16_t age_ms; + + /* retrieve/read/recv */ + long rlock; + buf_state_t rstate; + +} hmi_tree_item_t; + +static hmi_tree_item_t hmi_tree_item[] = { +%(variable_decl_array)s +}; + +typedef int(*hmi_tree_iterator)(uint32_t, hmi_tree_item_t*); +static int traverse_hmi_tree(hmi_tree_iterator fp) +{ + unsigned int i; + for(i = 0; i < sizeof(hmi_tree_item)/sizeof(hmi_tree_item_t); i++){ + hmi_tree_item_t *dsc = &hmi_tree_item[i]; + int res = (*fp)(i, dsc); + if(res != 0){ + return res; + } + } + return 0; +} + +#define __Unpack_desc_type hmi_tree_item_t + +%(var_access_code)s + +static int write_iterator(uint32_t index, hmi_tree_item_t *dsc) +{ + if(AtomicCompareExchange(&dsc->wlock, 0, 1) == 0) + { + if(dsc->wstate == buf_set){ + /* if being subscribed */ + if(dsc->refresh_period_ms){ + if(dsc->age_ms + ticktime_ms < dsc->refresh_period_ms){ + dsc->age_ms += ticktime_ms; + }else{ + dsc->wstate = buf_tosend; + global_write_dirty = 1; + } + } + } + + void *dest_p = &wbuf[dsc->buf_index]; + void *real_value_p = NULL; + char flags = 0; + void *visible_value_p = UnpackVar(dsc, &real_value_p, &flags); + + /* if new value differs from previous one */ + USINT sz = __get_type_enum_size(dsc->type); + if(__Is_a_string(dsc)){ + sz = ((STRING*)visible_value_p)->len + 1; + } + if(dsc->wstate == buf_new /* just subscribed + or already subscribed having value change */ + || (dsc->refresh_period_ms > 0 && memcmp(dest_p, visible_value_p, sz) != 0)){ + /* copy and flag as set */ + memcpy(dest_p, visible_value_p, sz); + /* if not already marked/signaled, do it */ + if(dsc->wstate != buf_set && dsc->wstate != buf_tosend) { + if(dsc->wstate == buf_new || ticktime_ms > dsc->refresh_period_ms){ + dsc->wstate = buf_tosend; + global_write_dirty = 1; + } else { + dsc->wstate = buf_set; + } + dsc->age_ms = 0; + } + } + + AtomicCompareExchange(&dsc->wlock, 1, 0); + } + // else ... : PLC can't wait, variable will be updated next turn + return 0; +} + +static int send_iterator(uint32_t index, hmi_tree_item_t *dsc) +{ + while(AtomicCompareExchange(&dsc->wlock, 0, 1)) sched_yield(); + + if(dsc->wstate == buf_tosend) + { + uint32_t sz = __get_type_enum_size(dsc->type); + if(sbufidx + sizeof(uint32_t) + sz <= sizeof(sbuf)) + { + void *src_p = &wbuf[dsc->buf_index]; + void *dst_p = &sbuf[sbufidx]; + if(__Is_a_string(dsc)){ + sz = ((STRING*)src_p)->len + 1; + } + /* TODO : force into little endian */ + memcpy(dst_p, &index, sizeof(uint32_t)); + memcpy(dst_p + sizeof(uint32_t), src_p, sz); + dsc->wstate = buf_free; + sbufidx += sizeof(uint32_t) /* index */ + sz; + } + else + { + printf("BUG!!! %%d + %%ld + %%d > %%ld \n", sbufidx, sizeof(uint32_t), sz, sizeof(sbuf)); + AtomicCompareExchange(&dsc->wlock, 1, 0); + return EOVERFLOW; + } + } + + AtomicCompareExchange(&dsc->wlock, 1, 0); + return 0; +} + +static int read_iterator(uint32_t index, hmi_tree_item_t *dsc) +{ + if(AtomicCompareExchange(&dsc->rlock, 0, 1) == 0) + { + if(dsc->rstate == buf_set) + { + void *src_p = &rbuf[dsc->buf_index]; + void *real_value_p = NULL; + char flags = 0; + void *visible_value_p = UnpackVar(dsc, &real_value_p, &flags); + memcpy(real_value_p, src_p, __get_type_enum_size(dsc->type)); + dsc->rstate = buf_free; + } + AtomicCompareExchange(&dsc->rlock, 1, 0); + } + // else ... : PLC can't wait, variable will be updated next turn + return 0; +} + +void update_refresh_period(hmi_tree_item_t *dsc, uint16_t refresh_period_ms) +{ + while(AtomicCompareExchange(&dsc->wlock, 0, 1)) sched_yield(); + if(refresh_period_ms) { + if(!dsc->refresh_period_ms) + { + dsc->wstate = buf_new; + } + } else { + dsc->wstate = buf_free; + } + dsc->refresh_period_ms = refresh_period_ms; + AtomicCompareExchange(&dsc->wlock, 1, 0); +} + +static int reset_iterator(uint32_t index, hmi_tree_item_t *dsc) +{ + update_refresh_period(dsc, 0); + return 0; +} + +void SVGHMI_SuspendFromPythonThread(void); +void SVGHMI_WakeupFromRTThread(void); + +static int continue_collect; + +int __init_svghmi() +{ + bzero(rbuf,sizeof(rbuf)); + bzero(wbuf,sizeof(wbuf)); + + continue_collect = 1; + + return 0; +} + +void __cleanup_svghmi() +{ + continue_collect = 0; + SVGHMI_WakeupFromRTThread(); +} + +void __retrieve_svghmi() +{ + traverse_hmi_tree(read_iterator); +} + +void __publish_svghmi() +{ + global_write_dirty = 0; + traverse_hmi_tree(write_iterator); + if(global_write_dirty) { + SVGHMI_WakeupFromRTThread(); + } +} + +/* PYTHON CALLS */ +int svghmi_send_collect(uint32_t *size, char **ptr){ + + SVGHMI_SuspendFromPythonThread(); + + if(continue_collect) { + int res; + sbufidx = HMI_HASH_SIZE; + if((res = traverse_hmi_tree(send_iterator)) == 0) + { + if(sbufidx > HMI_HASH_SIZE){ + memcpy(&sbuf[0], &hmi_hash[0], HMI_HASH_SIZE); + *ptr = &sbuf[0]; + *size = sbufidx; + return 0; + } + return ENODATA; + } + // printf("collected BAD result %%d\n", res); + return res; + } + else + { + return EINTR; + } +} + +typedef enum { + setval = 0, + reset = 1, + subscribe = 2 +} cmd_from_JS; + +// Returns : +// 0 is OK, <0 is error, 1 is heartbeat +int svghmi_recv_dispatch(uint32_t size, const uint8_t *ptr){ + const uint8_t* cursor = ptr + HMI_HASH_SIZE; + const uint8_t* end = ptr + size; + + int was_hearbeat = 0; + + /* match hmitree fingerprint */ + if(size <= HMI_HASH_SIZE || memcmp(ptr, hmi_hash, HMI_HASH_SIZE) != 0) + { + printf("svghmi_recv_dispatch MISMATCH !!\n"); + return -EINVAL; + } + + while(cursor < end) + { + uint32_t progress; + cmd_from_JS cmd = *(cursor++); + switch(cmd) + { + case setval: + { + uint32_t index = *(uint32_t*)(cursor); + uint8_t const *valptr = cursor + sizeof(uint32_t); + + if(index == heartbeat_index) + was_hearbeat = 1; + + if(index < HMI_ITEM_COUNT) + { + hmi_tree_item_t *dsc = &hmi_tree_item[index]; + void *real_value_p = NULL; + char flags = 0; + void *visible_value_p = UnpackVar(dsc, &real_value_p, &flags); + void *dst_p = &rbuf[dsc->buf_index]; + uint32_t sz = __get_type_enum_size(dsc->type); + + if(__Is_a_string(dsc)){ + sz = ((STRING*)valptr)->len + 1; + } + + if((valptr + sz) <= end) + { + // rescheduling spinlock until free + while(AtomicCompareExchange(&dsc->rlock, 0, 1)) sched_yield(); + + memcpy(dst_p, valptr, sz); + dsc->rstate = buf_set; + + AtomicCompareExchange(&dsc->rlock, 1, 0); + progress = sz + sizeof(uint32_t) /* index */; + } + else + { + return -EINVAL; + } + } + else + { + return -EINVAL; + } + } + break; + + case reset: + { + progress = 0; + traverse_hmi_tree(reset_iterator); + } + break; + + case subscribe: + { + uint32_t index = *(uint32_t*)(cursor); + uint16_t refresh_period_ms = *(uint32_t*)(cursor + sizeof(uint32_t)); + + if(index < HMI_ITEM_COUNT) + { + hmi_tree_item_t *dsc = &hmi_tree_item[index]; + update_refresh_period(dsc, refresh_period_ms); + } + else + { + return -EINVAL; + } + + progress = sizeof(uint32_t) /* index */ + + sizeof(uint16_t) /* refresh period */; + } + break; + default: + printf("svghmi_recv_dispatch unknown %%d\n",cmd); + + } + cursor += progress; + } + return was_hearbeat; +} + diff -r 703ebf57508a -r a4bae7edca13 svghmi/svghmi.js --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/svghmi/svghmi.js Fri Jul 03 10:03:25 2020 +0200 @@ -0,0 +1,450 @@ +// svghmi.js + +var cache = hmitree_types.map(_ignored => undefined); +var updates = {}; +var need_cache_apply = []; + +function dispatch_value_to_widget(widget, index, value, oldval) { + try { + let idx = widget.offset ? index - widget.offset : index; + let idxidx = widget.indexes.indexOf(idx); + let d = widget.dispatch; + if(typeof(d) == "function" && idxidx == 0){ + d.call(widget, value, oldval); + } + else if(typeof(d) == "object" && d.length >= idxidx){ + d[idxidx].call(widget, value, oldval); + } + /* else dispatch_0, ..., dispatch_n ? */ + /*else { + throw new Error("Dunno how to dispatch to widget at index = " + index); + }*/ + } catch(err) { + console.log(err); + } +} + +function dispatch_value(index, value) { + let widgets = subscribers[index]; + + let oldval = cache[index]; + cache[index] = value; + + if(widgets.size > 0) { + for(let widget of widgets){ + dispatch_value_to_widget(widget, index, value, oldval); + } + } +}; + +function init_widgets() { + Object.keys(hmi_widgets).forEach(function(id) { + let widget = hmi_widgets[id]; + let init = widget.init; + if(typeof(init) == "function"){ + try { + init.call(widget); + } catch(err) { + console.log(err); + } + } + }); +}; + +// Open WebSocket to relative "/ws" address +var ws = new WebSocket(window.location.href.replace(/^http(s?:\/\/[^\/]*)\/.*$/, 'ws$1/ws')); +ws.binaryType = 'arraybuffer'; + +const dvgetters = { + INT: (dv,offset) => [dv.getInt16(offset, true), 2], + BOOL: (dv,offset) => [dv.getInt8(offset, true), 1], + NODE: (dv,offset) => [dv.getInt8(offset, true), 1], + STRING: (dv, offset) => { + size = dv.getInt8(offset); + return [ + String.fromCharCode.apply(null, new Uint8Array( + dv.buffer, /* original buffer */ + offset + 1, /* string starts after size*/ + size /* size of string */ + )), size + 1]; /* total increment */ + } +}; + +// Apply updates recieved through ws.onmessage to subscribed widgets +function apply_updates() { + for(let index in updates){ + // serving as a key, index becomes a string + // -> pass Number(index) instead + dispatch_value(Number(index), updates[index]); + delete updates[index]; + } +} + +// Called on requestAnimationFrame, modifies DOM +var requestAnimationFrameID = null; +function animate() { + // Do the page swith if any one pending + if(current_subscribed_page != current_visible_page){ + switch_visible_page(current_subscribed_page); + } + + while(widget = need_cache_apply.pop()){ + widget.apply_cache(); + } + + if(jumps_need_update) update_jumps(); + + apply_updates(); + requestAnimationFrameID = null; +} + +function requestHMIAnimation() { + if(requestAnimationFrameID == null){ + requestAnimationFrameID = window.requestAnimationFrame(animate); + } +} + +// Message reception handler +// Hash is verified and HMI values updates resulting from binary parsing +// are stored until browser can compute next frame, DOM is left untouched +ws.onmessage = function (evt) { + + let data = evt.data; + let dv = new DataView(data); + let i = 0; + try { + for(let hash_int of hmi_hash) { + if(hash_int != dv.getUint8(i)){ + throw new Error("Hash doesn't match"); + }; + i++; + }; + + while(i < data.byteLength){ + let index = dv.getUint32(i, true); + i += 4; + let iectype = hmitree_types[index]; + if(iectype != undefined){ + let dvgetter = dvgetters[iectype]; + let [value, bytesize] = dvgetter(dv,i); + updates[index] = value; + i += bytesize; + } else { + throw new Error("Unknown index "+index); + } + }; + // register for rendering on next frame, since there are updates + requestHMIAnimation(); + } catch(err) { + // 1003 is for "Unsupported Data" + // ws.close(1003, err.message); + + // TODO : remove debug alert ? + alert("Error : "+err.message+"\\\\nHMI will be reloaded."); + + // force reload ignoring cache + location.reload(true); + } +}; + + +function send_blob(data) { + if(data.length > 0) { + ws.send(new Blob([new Uint8Array(hmi_hash)].concat(data))); + }; +}; + +const typedarray_types = { + INT: (number) => new Int16Array([number]), + BOOL: (truth) => new Int16Array([truth]), + NODE: (truth) => new Int16Array([truth]), + STRING: (str) => { + // beremiz default string max size is 128 + str = str.slice(0,128); + binary = new Uint8Array(str.length + 1); + binary[0] = str.length; + for(var i = 0; i < str.length; i++){ + binary[i+1] = str.charCodeAt(i); + } + return binary; + } + /* TODO */ +}; + +function send_reset() { + send_blob(new Uint8Array([1])); /* reset = 1 */ +}; + +// subscription state, as it should be in hmi server +// hmitree indexed array of integers +var subscriptions = hmitree_types.map(_ignored => 0); + +// subscription state as needed by widget now +// hmitree indexed array of Sets of widgets objects +var subscribers = hmitree_types.map(_ignored => new Set()); + +// artificially subscribe the watchdog widget to "/heartbeat" hmi variable +// Since dispatch directly calls change_hmi_value, +// PLC will periodically send variable at given frequency +subscribers[heartbeat_index].add({ + /* type: "Watchdog", */ + frequency: 1, + indexes: [heartbeat_index], + dispatch: function(value) { + change_hmi_value(heartbeat_index, "+1"); + } +}); + +function update_subscriptions() { + let delta = []; + for(let index = 0; index < subscribers.length; index++){ + let widgets = subscribers[index]; + + // periods are in ms + let previous_period = subscriptions[index]; + + // subscribing with a zero period is unsubscribing + let new_period = 0; + if(widgets.size > 0) { + let maxfreq = 0; + for(let widget of widgets){ + let wf = widget.frequency; + if(wf != undefined && maxfreq < wf) + maxfreq = wf; + } + + if(maxfreq != 0) + new_period = 1000/maxfreq; + } + + if(previous_period != new_period) { + subscriptions[index] = new_period; + delta.push( + new Uint8Array([2]), /* subscribe = 2 */ + new Uint32Array([index]), + new Uint16Array([new_period])); + } + } + send_blob(delta); +}; + +function send_hmi_value(index, value) { + let iectype = hmitree_types[index]; + let tobinary = typedarray_types[iectype]; + send_blob([ + new Uint8Array([0]), /* setval = 0 */ + new Uint32Array([index]), + tobinary(value)]); + + // DON'T DO THAT unless read_iterator in svghmi.c modifies wbuf as well, not only rbuf + // cache[index] = value; +}; + +function apply_hmi_value(index, new_val) { + let old_val = cache[index] + if(new_val != undefined && old_val != new_val) + send_hmi_value(index, new_val); + return new_val; +} + +quotes = {"'":null, '"':null}; + +function change_hmi_value(index, opstr) { + let op = opstr[0]; + let given_val; + if(opstr.length < 2) + return undefined; // TODO raise + if(opstr[1] in quotes){ + if(opstr.length < 3) + return undefined; // TODO raise + if(opstr[opstr.length-1] == opstr[1]){ + given_val = opstr.slice(2,opstr.length-1); + } + } else { + given_val = Number(opstr.slice(1)); + } + let old_val = cache[index]; + let new_val; + switch(op){ + case "=": + new_val = given_val; + break; + case "+": + new_val = old_val + given_val; + break; + case "-": + new_val = old_val - given_val; + break; + case "*": + new_val = old_val * given_val; + break; + case "/": + new_val = old_val / given_val; + break; + } + if(new_val != undefined && old_val != new_val) + send_hmi_value(index, new_val); + // TODO else raise + return new_val; +} + +var current_visible_page; +var current_subscribed_page; +var current_page_index; + +function prepare_svg() { + for(let eltid in detachable_elements){ + let [element,parent] = detachable_elements[eltid]; + parent.removeChild(element); + } +}; + +function switch_page(page_name, page_index) { + if(current_subscribed_page != current_visible_page){ + /* page switch already going */ + /* TODO LOG ERROR */ + return false; + } + + if(page_name == undefined) + page_name = current_subscribed_page; + + + let old_desc = page_desc[current_subscribed_page]; + let new_desc = page_desc[page_name]; + + if(new_desc == undefined){ + /* TODO LOG ERROR */ + return false; + } + + if(page_index == undefined){ + page_index = new_desc.page_index; + } + + if(old_desc){ + old_desc.absolute_widgets.map(w=>w.unsub()); + old_desc.relative_widgets.map(w=>w.unsub()); + } + new_desc.absolute_widgets.map(w=>w.sub()); + var new_offset = page_index == undefined ? 0 : page_index - new_desc.page_index; + new_desc.relative_widgets.map(w=>w.sub(new_offset)); + + update_subscriptions(); + + current_subscribed_page = page_name; + current_page_index = page_index; + + jumps_need_update = true; + + requestHMIAnimation(); + + jump_history.push([page_name, page_index]); + if(jump_history.length > 42) + jump_history.shift(); + + return true; +}; + +function switch_visible_page(page_name) { + + let old_desc = page_desc[current_visible_page]; + let new_desc = page_desc[page_name]; + + if(old_desc){ + for(let eltid in old_desc.required_detachables){ + if(!(eltid in new_desc.required_detachables)){ + let [element, parent] = old_desc.required_detachables[eltid]; + parent.removeChild(element); + } + } + for(let eltid in new_desc.required_detachables){ + if(!(eltid in old_desc.required_detachables)){ + let [element, parent] = new_desc.required_detachables[eltid]; + parent.appendChild(element); + } + } + }else{ + for(let eltid in new_desc.required_detachables){ + let [element, parent] = new_desc.required_detachables[eltid]; + parent.appendChild(element); + } + } + + svg_root.setAttribute('viewBox',new_desc.bbox.join(" ")); + current_visible_page = page_name; +}; + +// Once connection established +ws.onopen = function (evt) { + init_widgets(); + send_reset(); + // show main page + prepare_svg(); + switch_page(default_page); +}; + +ws.onclose = function (evt) { + // TODO : add visible notification while waiting for reload + console.log("Connection closed. code:"+evt.code+" reason:"+evt.reason+" wasClean:"+evt.wasClean+" Reload in 10s."); + // TODO : re-enable auto reload when not in debug + //window.setTimeout(() => location.reload(true), 10000); + alert("Connection closed. code:"+evt.code+" reason:"+evt.reason+" wasClean:"+evt.wasClean+"."); + +}; + +var xmlns = "http://www.w3.org/2000/svg"; +var edit_callback; +function edit_value(path, valuetype, callback, initial) { + + let [keypadid, xcoord, ycoord] = keypads[valuetype]; + console.log('XXX TODO : Edit value', path, valuetype, callback, initial, keypadid); + edit_callback = callback; + let widget = hmi_widgets[keypadid]; + widget.start_edit(path, valuetype, callback, initial); +}; + +var current_modal; /* TODO stack ?*/ + +function show_modal() { + let [element, parent] = detachable_elements[this.element.id]; + + tmpgrp = document.createElementNS(xmlns,"g"); + tmpgrpattr = document.createAttribute("transform"); + + let [xcoord,ycoord] = this.coordinates; + let [xdest,ydest] = page_desc[current_visible_page].bbox; + tmpgrpattr.value = "translate("+String(xdest-xcoord)+","+String(ydest-ycoord)+")"; + tmpgrp.setAttributeNode(tmpgrpattr); + + tmpgrp.appendChild(element); + parent.appendChild(tmpgrp); + + current_modal = [this.element.id, tmpgrp]; +}; + +function end_modal() { + let [eltid, tmpgrp] = current_modal; + let [element, parent] = detachable_elements[this.element.id]; + + parent.removeChild(tmpgrp); + + current_modal = undefined; +}; + +function widget_active_activable(eltsub) { + if(eltsub.inactive_style === undefined) + eltsub.inactive_style = eltsub.inactive.getAttribute("style"); + eltsub.inactive.setAttribute("style", "display:none"); + if(eltsub.active_style !== undefined) + eltsub.active.setAttribute("style", eltsub.active_style); + console.log("active", eltsub); +}; +function widget_inactive_activable(eltsub) { + if(eltsub.active_style === undefined) + eltsub.active_style = eltsub.active.getAttribute("style"); + eltsub.active.setAttribute("style", "display:none"); + if(eltsub.inactive_style !== undefined) + eltsub.inactive.setAttribute("style", eltsub.inactive_style); + console.log("inactive", eltsub); +}; diff -r 703ebf57508a -r a4bae7edca13 svghmi/svghmi.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/svghmi/svghmi.py Fri Jul 03 10:03:25 2020 +0200 @@ -0,0 +1,645 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# This file is part of Beremiz +# Copyright (C) 2019: Edouard TISSERANT +# +# See COPYING file for copyrights details. + +from __future__ import absolute_import +import os +import shutil +from itertools import izip, imap +from pprint import pformat +import hashlib +import weakref +import shlex + +import wx +import wx.dataview as dv + +from lxml import etree +from lxml.etree import XSLTApplyError + +import util.paths as paths +from POULibrary import POULibrary +from docutil import open_svg, get_inkscape_path + +from util.ProcessLogger import ProcessLogger +from runtime.typemapping import DebugTypesSize +import targets +from editors.ConfTreeNodeEditor import ConfTreeNodeEditor +from XSLTransform import XSLTransform + +HMI_TYPES_DESC = { + "HMI_NODE":{}, + "HMI_STRING":{}, + "HMI_INT":{}, + "HMI_BOOL":{} +} + +HMI_TYPES = HMI_TYPES_DESC.keys() + + +ScriptDirectory = paths.AbsDir(__file__) + +class HMITreeNode(object): + def __init__(self, path, name, nodetype, iectype = None, vartype = None, cpath = None, hmiclass = None): + self.path = path + self.name = name + self.nodetype = nodetype + self.hmiclass = hmiclass + + if iectype is not None: + self.iectype = iectype + self.vartype = vartype + self.cpath = cpath + + if nodetype in ["HMI_NODE"]: + self.children = [] + + def pprint(self, indent = 0): + res = ">"*indent + pformat(self.__dict__, indent = indent, depth = 1) + "\n" + if hasattr(self, "children"): + res += "\n".join([child.pprint(indent = indent + 1) + for child in self.children]) + res += "\n" + + return res + + def place_node(self, node): + best_child = None + known_best_match = 0 + potential_siblings = {} + for child in self.children: + if child.path is not None: + in_common = 0 + for child_path_item, node_path_item in izip(child.path, node.path): + if child_path_item == node_path_item: + in_common +=1 + else: + break + # Match can only be HMI_NODE, and the whole path of node + # must match candidate node (except for name part) + # since candidate would become child of that node + if in_common > known_best_match and \ + child.nodetype == "HMI_NODE" and \ + in_common == len(child.path) - 1: + known_best_match = in_common + best_child = child + else: + potential_siblings[child.path[ + -2 if child.nodetype == "HMI_NODE" else -1]] = child + if best_child is not None: + if node.nodetype == "HMI_NODE" and best_child.path[:-1] == node.path[:-1]: + return "Duplicate_HMI_NODE", best_child + return best_child.place_node(node) + else: + candidate_name = node.path[-2 if node.nodetype == "HMI_NODE" else -1] + if candidate_name in potential_siblings: + return "Non_Unique", potential_siblings[candidate_name] + + if node.nodetype == "HMI_NODE" and len(self.children) > 0: + prev = self.children[-1] + if prev.path[:-1] == node.path[:-1]: + return "Late_HMI_NODE",prev + + self.children.append(node) + return None + + def etree(self, add_hash=False): + + attribs = dict(name=self.name) + if self.path is not None: + attribs["path"] = ".".join(self.path) + + if self.hmiclass is not None: + attribs["class"] = self.hmiclass + + if add_hash: + attribs["hash"] = ",".join(map(str,self.hash())) + + res = etree.Element(self.nodetype, **attribs) + + if hasattr(self, "children"): + for child_etree in imap(lambda c:c.etree(), self.children): + res.append(child_etree) + + return res + + def traverse(self): + yield self + if hasattr(self, "children"): + for c in self.children: + for yoodl in c.traverse(): + yield yoodl + + + def hash(self): + """ Produce a hash, any change in HMI tree structure change that hash """ + s = hashlib.new('md5') + self._hash(s) + # limit size to HMI_HASH_SIZE as in svghmi.c + return map(ord,s.digest())[:8] + + def _hash(self, s): + s.update(str((self.name,self.nodetype))) + if hasattr(self, "children"): + for c in self.children: + c._hash(s) + +# module scope for HMITree root +# so that CTN can use HMITree deduced in Library +# note: this only works because library's Generate_C is +# systematicaly invoked before CTN's CTNGenerate_C + +hmi_tree_root = None + +on_hmitree_update = None + +SPECIAL_NODES = [("HMI_ROOT", "HMI_NODE"), + ("heartbeat", "HMI_INT")] + # ("current_page", "HMI_STRING")]) + +class SVGHMILibrary(POULibrary): + def GetLibraryPath(self): + return paths.AbsNeighbourFile(__file__, "pous.xml") + + def Generate_C(self, buildpath, varlist, IECCFLAGS): + global hmi_tree_root, on_hmitree_update + + """ + PLC Instance Tree: + prog0 + +->v1 HMI_INT + +->v2 HMI_INT + +->fb0 (type mhoo) + | +->va HMI_NODE + | +->v3 HMI_INT + | +->v4 HMI_INT + | + +->fb1 (type mhoo) + | +->va HMI_NODE + | +->v3 HMI_INT + | +->v4 HMI_INT + | + +->fb2 + +->v5 HMI_IN + + HMI tree: + hmi0 + +->v1 + +->v2 + +->fb0 class:va + | +-> v3 + | +-> v4 + | + +->fb1 class:va + | +-> v3 + | +-> v4 + | + +->v5 + + """ + + # Filter known HMI types + hmi_types_instances = [v for v in varlist if v["derived"] in HMI_TYPES] + + hmi_tree_root = None + + # take first HMI_NODE (placed as special node), make it root + for i,v in enumerate(hmi_types_instances): + path = v["IEC_path"].split(".") + derived = v["derived"] + if derived == "HMI_NODE": + hmi_tree_root = HMITreeNode(path, "", derived, v["type"], v["vartype"], v["C_path"]) + hmi_types_instances.pop(i) + break + + assert(hmi_tree_root is not None) + + # deduce HMI tree from PLC HMI_* instances + for v in hmi_types_instances: + path = v["IEC_path"].split(".") + # ignores variables starting with _TMP_ + if path[-1].startswith("_TMP_"): + continue + derived = v["derived"] + kwargs={} + if derived == "HMI_NODE": + # TODO : make problem if HMI_NODE used in CONFIG or RESOURCE + name = path[-2] + kwargs['hmiclass'] = path[-1] + else: + name = path[-1] + new_node = HMITreeNode(path, name, derived, v["type"], v["vartype"], v["C_path"], **kwargs) + placement_result = hmi_tree_root.place_node(new_node) + if placement_result is not None: + cause, problematic_node = placement_result + if cause == "Non_Unique": + message = _("HMI tree nodes paths are not unique.\nConflicting variable: {} {}").format( + ".".join(problematic_node.path), + ".".join(new_node.path)) + + last_FB = None + for v in varlist: + if v["vartype"] == "FB": + last_FB = v + if v["C_path"] == problematic_node: + break + if last_FB is not None: + failing_parent = last_FB["type"] + message += "\n" + message += _("Solution: Add HMI_NODE at beginning of {}").format(failing_parent) + + elif cause in ["Late_HMI_NODE", "Duplicate_HMI_NODE"]: + cause, problematic_node = placement_result + message = _("There must be only one occurrence of HMI_NODE before any HMI_* variable in POU.\nConflicting variable: {} {}").format( + ".".join(problematic_node.path), + ".".join(new_node.path)) + + self.FatalError("SVGHMI : " + message) + + if on_hmitree_update is not None: + on_hmitree_update() + + variable_decl_array = [] + extern_variables_declarations = [] + buf_index = 0 + item_count = 0 + found_heartbeat = False + + hearbeat_IEC_path = ['CONFIG', 'HEARTBEAT'] + + for node in hmi_tree_root.traverse(): + if not found_heartbeat and node.path == hearbeat_IEC_path: + hmi_tree_hearbeat_index = item_count + found_heartbeat = True + extern_variables_declarations += [ + "#define heartbeat_index "+str(hmi_tree_hearbeat_index) + ] + if hasattr(node, "iectype"): + sz = DebugTypesSize.get(node.iectype, 0) + variable_decl_array += [ + "{&(" + node.cpath + "), " + node.iectype + { + "EXT": "_P_ENUM", + "IN": "_P_ENUM", + "MEM": "_O_ENUM", + "OUT": "_O_ENUM", + "VAR": "_ENUM" + }[node.vartype] + ", " + + str(buf_index) + ", 0, }"] + buf_index += sz + item_count += 1 + if len(node.path) == 1: + extern_variables_declarations += [ + "extern __IEC_" + node.iectype + "_" + + "t" if node.vartype is "VAR" else "p" + + node.cpath + ";"] + + assert(found_heartbeat) + + # TODO : filter only requiered external declarations + for v in varlist: + if v["C_path"].find('.') < 0: + extern_variables_declarations += [ + "extern %(type)s %(C_path)s;" % v] + + # TODO check if programs need to be declared separately + # "programs_declarations": "\n".join(["extern %(type)s %(C_path)s;" % + # p for p in self._ProgramList]), + + # C code to observe/access HMI tree variables + svghmi_c_filepath = paths.AbsNeighbourFile(__file__, "svghmi.c") + svghmi_c_file = open(svghmi_c_filepath, 'r') + svghmi_c_code = svghmi_c_file.read() + svghmi_c_file.close() + svghmi_c_code = svghmi_c_code % { + "variable_decl_array": ",\n".join(variable_decl_array), + "extern_variables_declarations": "\n".join(extern_variables_declarations), + "buffer_size": buf_index, + "item_count": item_count, + "var_access_code": targets.GetCode("var_access.c"), + "PLC_ticktime": self.GetCTR().GetTicktime(), + "hmi_hash_ints": ",".join(map(str,hmi_tree_root.hash())) + } + + gen_svghmi_c_path = os.path.join(buildpath, "svghmi.c") + gen_svghmi_c = open(gen_svghmi_c_path, 'w') + gen_svghmi_c.write(svghmi_c_code) + gen_svghmi_c.close() + + # Python based WebSocket HMITree Server + svghmiserverfile = open(paths.AbsNeighbourFile(__file__, "svghmi_server.py"), 'r') + svghmiservercode = svghmiserverfile.read() + svghmiserverfile.close() + + runtimefile_path = os.path.join(buildpath, "runtime_svghmi.py") + runtimefile = open(runtimefile_path, 'w') + runtimefile.write(svghmiservercode) + runtimefile.close() + + return ((["svghmi"], [(gen_svghmi_c_path, IECCFLAGS)], True), "", + ("runtime_svghmi0.py", open(runtimefile_path, "rb"))) + + +class HMITreeSelector(wx.TreeCtrl): + def __init__(self, parent): + global on_hmitree_update + wx.TreeCtrl.__init__(self,parent,style=wx.TR_MULTIPLE)# | wx.TR_HIDE_ROOT) + + isz = (16,16) + self.il = il = wx.ImageList(*isz) + self.fldridx = il.AddIcon(wx.ArtProvider.GetIcon(wx.ART_FOLDER, wx.ART_OTHER, isz)) + self.fldropenidx = il.AddIcon(wx.ArtProvider.GetIcon(wx.ART_FOLDER_OPEN, wx.ART_OTHER, isz)) + self.fileidx = il.AddIcon(wx.ArtProvider.GetIcon(wx.ART_NORMAL_FILE, wx.ART_OTHER, isz)) + self.SetImageList(il) + + on_hmitree_update = self.SVGHMIEditorUpdater() + self.MakeTree() + + def _recurseTree(self, current_hmitree_root, current_tc_root): + for c in current_hmitree_root.children: + if hasattr(c, "children"): + display_name = ('{} (class={})'.format(c.name, c.hmiclass)) \ + if c.hmiclass is not None else c.name + tc_child = self.AppendItem(current_tc_root, display_name) + self.SetPyData(tc_child, None) + self.SetItemImage(tc_child, self.fldridx, wx.TreeItemIcon_Normal) + self.SetItemImage(tc_child, self.fldropenidx, wx.TreeItemIcon_Expanded) + + self._recurseTree(c,tc_child) + else: + display_name = '{} {}'.format(c.nodetype[4:], c.name) + tc_child = self.AppendItem(current_tc_root, display_name) + self.SetPyData(tc_child, None) + self.SetItemImage(tc_child, self.fileidx, wx.TreeItemIcon_Normal) + self.SetItemImage(tc_child, self.fileidx, wx.TreeItemIcon_Expanded) + + def MakeTree(self): + global hmi_tree_root + + self.Freeze() + + self.root = None + self.DeleteAllItems() + + root_display_name = _("Please build to see HMI Tree") if hmi_tree_root is None else "HMI" + self.root = self.AddRoot(root_display_name) + self.SetPyData(self.root, None) + self.SetItemImage(self.root, self.fldridx, wx.TreeItemIcon_Normal) + self.SetItemImage(self.root, self.fldropenidx, wx.TreeItemIcon_Expanded) + + if hmi_tree_root is not None: + self._recurseTree(hmi_tree_root, self.root) + + self.Thaw() + + def SVGHMIEditorUpdater(self): + selfref = weakref.ref(self) + def SVGHMIEditorUpdate(): + o = selfref() + if o is not None: + wx.CallAfter(o.MakeTree) + return SVGHMIEditorUpdate + +class HMITreeView(wx.SplitterWindow): + + def __init__(self, parent): + wx.SplitterWindow.__init__(self, parent, + style=wx.SUNKEN_BORDER | wx.SP_3D) + + self.SelectionTree = HMITreeSelector(self) + #self.Staging = wx.Panel(self) + #self.SplitHorizontally(self.SelectionTree, self.Staging, 200) + self.Initialize(self.SelectionTree) + + +class SVGHMIEditor(ConfTreeNodeEditor): + CONFNODEEDITOR_TABS = [ + (_("HMI Tree"), "CreateHMITreeView")] + + def CreateHMITreeView(self, parent): + #self.HMITreeView = HMITreeView(self) + return HMITreeSelector(parent) + + +class SVGHMI(object): + XSD = """ + + + + + + + + + + + + """ + + EditorType = SVGHMIEditor + + ConfNodeMethods = [ + { + "bitmap": "ImportSVG", + "name": _("Import SVG"), + "tooltip": _("Import SVG"), + "method": "_ImportSVG" + }, + { + "bitmap": "ImportSVG", # should be something different + "name": _("Inkscape"), + "tooltip": _("Edit HMI"), + "method": "_StartInkscape" + }, + + # TODO : Launch POEdit button + # PO -> SVG layers button + # SVG layers -> PO + + # TODO : HMITree button + # - can drag'n'drop variabes to Inkscape + + ] + + def _getSVGpath(self, project_path=None): + if project_path is None: + project_path = self.CTNPath() + return os.path.join(project_path, "svghmi.svg") + + + def OnCTNSave(self, from_project_path=None): + if from_project_path is not None: + shutil.copyfile(self._getSVGpath(from_project_path), + self._getSVGpath()) + return True + + def GetSVGGeometry(self): + # invoke inskscape -S, csv-parse output, produce elements + InkscapeGeomColumns = ["Id", "x", "y", "w", "h"] + + inkpath = get_inkscape_path() + svgpath = self._getSVGpath() + _status, result, _err_result = ProcessLogger(self.GetCTRoot().logger, + inkpath + " -S " + svgpath, + no_stdout=True, + no_stderr=True).spin() + res = [] + for line in result.split(): + strippedline = line.strip() + attrs = dict( + zip(InkscapeGeomColumns, line.strip().split(','))) + + res.append(etree.Element("bbox", **attrs)) + + return res + + def GetHMITree(self): + global hmi_tree_root + res = [hmi_tree_root.etree(add_hash=True)] + return res + + def CTNGenerate_C(self, buildpath, locations): + + location_str = "_".join(map(str, self.GetCurrentLocation())) + view_name = self.BaseParams.getName() + + svgfile = self._getSVGpath() + + res = ([], "", False) + + target_fname = "svghmi_"+location_str+".xhtml" + + target_path = os.path.join(self._getBuildPath(), target_fname) + target_file = open(target_path, 'wb') + + if os.path.exists(svgfile): + + # TODO : move to __init__ + transform = XSLTransform(os.path.join(ScriptDirectory, "gen_index_xhtml.xslt"), + [("GetSVGGeometry", lambda *_ignored:self.GetSVGGeometry()), + ("GetHMITree", lambda *_ignored:self.GetHMITree())]) + + + # load svg as a DOM with Etree + svgdom = etree.parse(svgfile) + + # call xslt transform on Inkscape's SVG to generate XHTML + try: + result = transform.transform(svgdom) + except XSLTApplyError as e: + self.FatalError("SVGHMI " + view_name + ": " + e.message) + finally: + for entry in transform.get_error_log(): + message = "SVGHMI: "+ entry.message + "\n" + self.GetCTRoot().logger.write_warning(message) + + result.write(target_file, encoding="utf-8") + # print(str(result)) + # print(transform.xslt.error_log) + + # TODO + # - Errors on HMI semantics + # - ... maybe something to have a global view of what is declared in SVG. + + else: + # TODO : use default svg that expose the HMI tree as-is + target_file.write(""" + + +

No SVG file provided

+ + +""") + + target_file.close() + + res += ((target_fname, open(target_path, "rb")),) + + svghmi_cmds = {} + for thing in ["Start", "Stop", "Watchdog"]: + given_command = self.GetParamsAttributes("SVGHMI.On"+thing)["value"] + svghmi_cmds[thing] = ( + "Popen(" + + repr(shlex.split(given_command.format(port="8008", name=view_name))) + + ")") if given_command else "pass # no command given" + + runtimefile_path = os.path.join(buildpath, "runtime_svghmi1_%s.py" % location_str) + runtimefile = open(runtimefile_path, 'w') + runtimefile.write(""" +# TODO : multiple watchdog (one for each svghmi instance) +def svghmi_watchdog_trigger(): + {svghmi_cmds[Watchdog]} + +svghmi_watchdog = None + +def _runtime_svghmi1_{location}_start(): + global svghmi_watchdog + svghmi_root.putChild( + '{view_name}', + NoCacheFile('{xhtml}', + defaultType='application/xhtml+xml')) + + {svghmi_cmds[Start]} + + svghmi_watchdog = Watchdog( + {watchdog_initial}, + {watchdog_interval}, + svghmi_watchdog_trigger) + +def _runtime_svghmi1_{location}_stop(): + global svghmi_watchdog + if svghmi_watchdog is not None: + svghmi_watchdog.cancel() + svghmi_watchdog = None + + svghmi_root.delEntity('{view_name}') + {svghmi_cmds[Stop]} + + """.format(location=location_str, + xhtml=target_fname, + view_name=view_name, + svghmi_cmds=svghmi_cmds, + watchdog_initial = self.GetParamsAttributes("SVGHMI.WatchdogInitial")["value"], + watchdog_interval = self.GetParamsAttributes("SVGHMI.WatchdogInterval")["value"], + )) + + runtimefile.close() + + res += (("runtime_svghmi1_%s.py" % location_str, open(runtimefile_path, "rb")),) + + return res + + def _ImportSVG(self): + dialog = wx.FileDialog(self.GetCTRoot().AppFrame, _("Choose a SVG file"), os.getcwd(), "", _("SVG files (*.svg)|*.svg|All files|*.*"), wx.OPEN) + if dialog.ShowModal() == wx.ID_OK: + svgpath = dialog.GetPath() + if os.path.isfile(svgpath): + shutil.copy(svgpath, self._getSVGpath()) + else: + self.GetCTRoot().logger.write_error(_("No such SVG file: %s\n") % svgpath) + dialog.Destroy() + + def _StartInkscape(self): + svgfile = self._getSVGpath() + open_inkscape = True + if not self.GetCTRoot().CheckProjectPathPerm(): + dialog = wx.MessageDialog(self.GetCTRoot().AppFrame, + _("You don't have write permissions.\nOpen Inkscape anyway ?"), + _("Open Inkscape"), + wx.YES_NO | wx.ICON_QUESTION) + open_inkscape = dialog.ShowModal() == wx.ID_YES + dialog.Destroy() + if open_inkscape: + if not os.path.isfile(svgfile): + svgfile = None + open_svg(svgfile) + + def CTNGlobalInstances(self): + # view_name = self.BaseParams.getName() + # return [ (view_name + "_" + name, iec_type, "") for name, iec_type in SPECIAL_NODES] + # TODO : move to library level for multiple hmi + return [(name, iec_type, "") for name, iec_type in SPECIAL_NODES] + diff -r 703ebf57508a -r a4bae7edca13 svghmi/svghmi_server.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/svghmi/svghmi_server.py Fri Jul 03 10:03:25 2020 +0200 @@ -0,0 +1,204 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# This file is part of Beremiz +# Copyright (C) 2019: Edouard TISSERANT +# See COPYING file for copyrights details. + +from __future__ import absolute_import +import errno +from threading import RLock, Timer + +try: + from runtime.spawn_subprocess import Popen +except ImportError: + from subprocess import Popen + +from twisted.web.server import Site +from twisted.web.resource import Resource +from twisted.internet import reactor +from twisted.web.static import File + +from autobahn.twisted.websocket import WebSocketServerFactory, WebSocketServerProtocol +from autobahn.websocket.protocol import WebSocketProtocol +from autobahn.twisted.resource import WebSocketResource + +# TODO multiclient : +# session list lock +# svghmi_sessions = [] +# svghmi_watchdogs = [] + +svghmi_session = None +svghmi_watchdog = None + +svghmi_send_collect = PLCBinary.svghmi_send_collect +svghmi_send_collect.restype = ctypes.c_int # error or 0 +svghmi_send_collect.argtypes = [ + ctypes.POINTER(ctypes.c_uint32), # size + ctypes.POINTER(ctypes.c_void_p)] # data ptr +# TODO multiclient : switch to arrays + +svghmi_recv_dispatch = PLCBinary.svghmi_recv_dispatch +svghmi_recv_dispatch.restype = ctypes.c_int # error or 0 +svghmi_recv_dispatch.argtypes = [ + ctypes.c_uint32, # size + ctypes.c_char_p] # data ptr +# TODO multiclient : switch to arrays + +class HMISession(object): + def __init__(self, protocol_instance): + global svghmi_session + + # Single client : + # Creating a new HMISession closes pre-existing HMISession + if svghmi_session is not None: + svghmi_session.close() + svghmi_session = self + self.protocol_instance = protocol_instance + + # TODO multiclient : + # svghmi_sessions.append(self) + # get a unique bit index amont other svghmi_sessions, + # so that we can match flags passed by C->python callback + + def close(self): + global svghmi_session + if svghmi_session == self: + svghmi_session = None + self.protocol_instance.sendClose(WebSocketProtocol.CLOSE_STATUS_CODE_NORMAL) + + def onMessage(self, msg): + # pass message to the C side recieve_message() + return svghmi_recv_dispatch(len(msg), msg) + + # TODO multiclient : pass client index as well + + def sendMessage(self, msg): + self.protocol_instance.sendMessage(msg, True) + return 0 + +class Watchdog(object): + def __init__(self, initial_timeout, interval, callback): + self._callback = callback + self.lock = RLock() + self.initial_timeout = initial_timeout + self.interval = interval + self.callback = callback + with self.lock: + self._start() + + def _start(self, rearm=False): + duration = self.interval if rearm else self.initial_timeout + if duration: + self.timer = Timer(duration, self.trigger) + self.timer.start() + else: + self.timer = None + + def _stop(self): + if self.timer is not None: + self.timer.cancel() + self.timer = None + + def cancel(self): + with self.lock: + self._stop() + + def feed(self, rearm=True): + with self.lock: + self._stop() + self._start(rearm) + + def trigger(self): + self._callback() + # wait for initial timeout on re-start + self.feed(rearm=False) + +class HMIProtocol(WebSocketServerProtocol): + + def __init__(self, *args, **kwargs): + self._hmi_session = None + WebSocketServerProtocol.__init__(self, *args, **kwargs) + + def onOpen(self): + assert(self._hmi_session is None) + self._hmi_session = HMISession(self) + + def onClose(self, wasClean, code, reason): + self._hmi_session = None + + def onMessage(self, msg, isBinary): + assert(self._hmi_session is not None) + + result = self._hmi_session.onMessage(msg) + if result == 1 : # was heartbeat + if svghmi_watchdog is not None: + svghmi_watchdog.feed() + +class HMIWebSocketServerFactory(WebSocketServerFactory): + protocol = HMIProtocol + +svghmi_root = None +svghmi_listener = None +svghmi_send_thread = None + +def SendThreadProc(): + global svghmi_session + size = ctypes.c_uint32() + ptr = ctypes.c_void_p() + res = 0 + while True: + res=svghmi_send_collect(ctypes.byref(size), ctypes.byref(ptr)) + if res == 0: + # TODO multiclient : dispatch to sessions + if svghmi_session is not None: + svghmi_session.sendMessage(ctypes.string_at(ptr.value,size.value)) + elif res == errno.ENODATA: + # this happens when there is no data after wakeup + # because of hmi data refresh period longer than PLC common ticktime + pass + else: + # this happens when finishing + break + + +def watchdog_trigger(): + print("SVGHMI watchdog trigger") + + +# Called by PLCObject at start +def _runtime_svghmi0_start(): + global svghmi_listener, svghmi_root, svghmi_send_thread + + svghmi_root = Resource() + svghmi_root.putChild("ws", WebSocketResource(HMIWebSocketServerFactory())) + + svghmi_listener = reactor.listenTCP(8008, Site(svghmi_root)) + + # start a thread that call the C part of SVGHMI + svghmi_send_thread = Thread(target=SendThreadProc, name="SVGHMI Send") + svghmi_send_thread.start() + + +# Called by PLCObject at stop +def _runtime_svghmi0_stop(): + global svghmi_listener, svghmi_root, svghmi_send_thread, svghmi_session + + if svghmi_session is not None: + svghmi_session.close() + svghmi_root.delEntity("ws") + svghmi_root = None + svghmi_listener.stopListening() + svghmi_listener = None + # plc cleanup calls svghmi_(locstring)_cleanup and unlocks send thread + svghmi_send_thread.join() + svghmi_send_thread = None + + +class NoCacheFile(File): + def render_GET(self, request): + request.setHeader(b"Cache-Control", b"no-cache, no-store") + return File.render_GET(self, request) + render_HEAD = render_GET + + diff -r 703ebf57508a -r a4bae7edca13 svghmi/widget_back.ysl2 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/svghmi/widget_back.ysl2 Fri Jul 03 10:03:25 2020 +0200 @@ -0,0 +1,17 @@ +// widget_back.ysl2 + +template "widget[@type='Back']", mode="widget_class" + || + class BackWidget extends Widget{ + on_click(evt) { + if(jump_history.length > 1){ + jump_history.pop(); + let [page_name, index] = jump_history.pop(); + switch_page(page_name, index); + } + } + init() { + this.element.setAttribute("onclick", "hmi_widgets['"+this.element_id+"'].on_click(evt)"); + } + } + || diff -r 703ebf57508a -r a4bae7edca13 svghmi/widget_button.ysl2 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/svghmi/widget_button.ysl2 Fri Jul 03 10:03:25 2020 +0200 @@ -0,0 +1,33 @@ +// widget_button.ysl2 + +template "widget[@type='Button']", mode="widget_defs" { + param "hmi_element"; + optional_labels("active inactive"); + | frequency: 5, + | on_mouse_down: function(evt) { + | if (this.active_style && this.inactive_style) { + | this.active_elt.setAttribute("style", this.active_style); + | this.inactive_elt.setAttribute("style", "display:none"); + | } + | change_hmi_value(this.indexes[0], "=1"); + | }, + | on_mouse_up: function(evt) { + | if (this.active_style && this.inactive_style) { + | this.active_elt.setAttribute("style", "display:none"); + | this.inactive_elt.setAttribute("style", this.inactive_style); + | } + | change_hmi_value(this.indexes[0], "=0"); + | }, + | active_style: undefined, + | inactive_style: undefined, + | init: function() { + | this.active_style = this.active_elt ? this.active_elt.style.cssText : undefined; + | this.inactive_style = this.inactive_elt ? this.inactive_elt.style.cssText : undefined; + | if (this.active_style && this.inactive_style) { + | this.active_elt.setAttribute("style", "display:none"); + | this.inactive_elt.setAttribute("style", this.inactive_style); + | } + | this.element.setAttribute("onmousedown", "hmi_widgets['«$hmi_element/@id»'].on_mouse_down(evt)"); + | this.element.setAttribute("onmouseup", "hmi_widgets['«$hmi_element/@id»'].on_mouse_up(evt)"); + | }, +} \ No newline at end of file diff -r 703ebf57508a -r a4bae7edca13 svghmi/widget_circularbar.ysl2 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/svghmi/widget_circularbar.ysl2 Fri Jul 03 10:03:25 2020 +0200 @@ -0,0 +1,48 @@ +// widget_circularbar.ysl2 + + +template "widget[@type='CircularBar']", mode="widget_defs" { + param "hmi_element"; + | frequency: 10, + labels("path"); + optional_labels("value min max"); + | dispatch: function(value) { + | if(this.value_elt) + | this.value_elt.textContent = String(value); + | let [min,max,start,end] = this.range; + | let [cx,cy] = this.center; + | let [rx,ry] = this.proportions; + | let tip = start + (end-start)*Number(value)/(max-min); + | let size = 0; + | if (tip-start > Math.PI) { + | size = 1; + | } else { + | size = 0; + | } + | this.path_elt.setAttribute('d', "M "+(cx+rx*Math.cos(start))+","+(cy+ry*Math.sin(start))+" A "+rx+","+ry+" 0 "+size+" 1 "+(cx+rx*Math.cos(tip))+","+(cy+ry*Math.sin(tip))); + | }, + | range: undefined, + | init: function() { + | let start = Number(this.path_elt.getAttribute('sodipodi:start')); + | let end = Number(this.path_elt.getAttribute('sodipodi:end')); + | let cx = Number(this.path_elt.getAttribute('sodipodi:cx')); + | let cy = Number(this.path_elt.getAttribute('sodipodi:cy')); + | let rx = Number(this.path_elt.getAttribute('sodipodi:rx')); + | let ry = Number(this.path_elt.getAttribute('sodipodi:ry')); + | if (ry == 0) { + | ry = rx; + | } + | if (start > end) { + | end = end + 2*Math.PI; + | } + | let min = this.min_elt ? + | Number(this.min_elt.textContent) : + | this.args.length >= 1 ? this.args[0] : 0; + | let max = this.max_elt ? + | Number(this.max_elt.textContent) : + | this.args.length >= 2 ? this.args[1] : 100; + | this.range = [min, max, start, end]; + | this.center = [cx, cy]; + | this.proportions = [rx, ry]; + | }, +} \ No newline at end of file diff -r 703ebf57508a -r a4bae7edca13 svghmi/widget_custom.ysl2 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/svghmi/widget_custom.ysl2 Fri Jul 03 10:03:25 2020 +0200 @@ -0,0 +1,62 @@ +// widget_custom.ysl2 +// +// widget entierely defined from JS code in Inkscape description field + +// TODO + +// a preliminary implementation was initially attempted but disabled +// code collected around before code refactoring + + +/*const "mark" > =HMI=\n*/ + + + /* TODO re-enable + || + function evaluate_js_from_descriptions() { + var Page; + var Input; + var Display; + var res = []; + || + const "midmark" > \n«$mark» + apply """//*[contains(child::svg:desc, $midmark) or \ + starts-with(child::svg:desc, $mark)]""",2 + mode="code_from_descs"; + || + return res; + } + || + */ + + // template "*", mode="code_from_descs" { + // || + // { + // var path, role, name, priv; + // var id = "«@id»"; + // || + + // /* if label is used, use it as default name */ + // if "@inkscape:label" + // |> name = "«@inkscape:label»"; + + // | /* -------------- */ + + // // this breaks indent, but fixing indent could break string literals + // value "substring-after(svg:desc, $mark)"; + // // nobody reads generated code anyhow... + + // || + + // /* -------------- */ + // res.push({ + // path:path, + // role:role, + // name:name, + // priv:priv + // }) + // } + // || + // } + + diff -r 703ebf57508a -r a4bae7edca13 svghmi/widget_display.ysl2 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/svghmi/widget_display.ysl2 Fri Jul 03 10:03:25 2020 +0200 @@ -0,0 +1,19 @@ +// widget_display.ysl2 + + +template "widget[@type='Display']", mode="widget_defs" { + param "hmi_element"; + | frequency: 5, + | dispatch: function(value) { + choose { + when "$hmi_element[self::svg:text]"{ + // TODO : care about ? + | this.element.textContent = String(value); + } + otherwise { + warning > Display widget as a group not implemented + } + } + | }, + +} diff -r 703ebf57508a -r a4bae7edca13 svghmi/widget_dropdown.ysl2 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/svghmi/widget_dropdown.ysl2 Fri Jul 03 10:03:25 2020 +0200 @@ -0,0 +1,255 @@ +// widget_dropdown.ysl2 + +template "widget[@type='DropDown']", mode="widget_defs" { + param "hmi_element"; + labels("text box button"); +|| + dispatch: function(value) { + if(!this.opened) this.set_selection(value); + }, + init: function() { + this.button_elt.setAttribute("onclick", "hmi_widgets['«$hmi_element/@id»'].on_button_click()"); + // Save original size of rectangle + this.box_bbox = this.box_elt.getBBox() + + // Compute margins + text_bbox = this.text_elt.getBBox() + lmargin = text_bbox.x - this.box_bbox.x; + tmargin = text_bbox.y - this.box_bbox.y; + this.margins = [lmargin, tmargin].map(x => Math.max(x,0)); + + // It is assumed that list content conforms to Array interface. + this.content = [ + ``foreach "arg" | "«@value»", + ]; + + // Index of first visible element in the menu, when opened + this.menu_offset = 0; + + // How mutch to lift the menu vertically so that it does not cross bottom border + this.lift = 0; + + // Event handlers cannot be object method ('this' is unknown) + // as a workaround, handler given to addEventListener is bound in advance. + this.bound_close_on_click_elsewhere = this.close_on_click_elsewhere.bind(this); + + this.opened = false; + }, + // Called when a menu entry is clicked + on_selection_click: function(selection) { + this.close(); + let orig = this.indexes[0]; + let idx = this.offset ? orig - this.offset : orig; + apply_hmi_value(idx, selection); + }, + on_button_click: function() { + this.open(); + }, + on_backward_click: function(){ + this.scroll(false); + }, + on_forward_click:function(){ + this.scroll(true); + }, + set_selection: function(value) { + let display_str; + if(value >= 0 && value < this.content.length){ + // if valid selection resolve content + display_str = this.content[value]; + this.last_selection = value; + } else { + // otherwise show problem + display_str = "?"+String(value)+"?"; + } + // It is assumed that first span always stays, + // and contains selection when menu is closed + this.text_elt.firstElementChild.textContent = display_str; + }, + grow_text: function(up_to) { + let count = 1; + let txt = this.text_elt; + let first = txt.firstElementChild; + // Real world (pixels) boundaries of current page + let bounds = svg_root.getBoundingClientRect(); + this.lift = 0; + while(count < up_to) { + let next = first.cloneNode(); + // relative line by line text flow instead of absolute y coordinate + next.removeAttribute("y"); + next.setAttribute("dy", "1.1em"); + // default content to allow computing text element bbox + next.textContent = "..."; + // append new span to text element + txt.appendChild(next); + // now check if text extended by one row fits to page + // FIXME : exclude margins to be more accurate on box size + let rect = txt.getBoundingClientRect(); + if(rect.bottom > bounds.bottom){ + // in case of overflow at the bottom, lift up one row + let backup = first.getAttribute("dy"); + // apply lift asr a dy added too first span (y attrib stays) + first.setAttribute("dy", "-"+String((this.lift+1)*1.1)+"em"); + rect = txt.getBoundingClientRect(); + if(rect.top > bounds.top){ + this.lift += 1; + } else { + // if it goes over the top, then backtrack + // restore dy attribute on first span + if(backup) + first.setAttribute("dy", backup); + else + first.removeAttribute("dy"); + // remove unwanted child + txt.removeChild(next); + return count; + } + } + count++; + } + return count; + }, + close_on_click_elsewhere: function(e) { + // inhibit events not targetting spans (menu items) + if(e.target.parentNode !== this.text_elt){ + e.stopPropagation(); + // close menu in case click is outside box + if(e.target !== this.box_elt) + this.close(); + } + }, + close: function(){ + // Stop hogging all click events + svg_root.removeEventListener("click", this.bound_close_on_click_elsewhere, true); + // Restore position and sixe of widget elements + this.reset_text(); + this.reset_box(); + // Put the button back in place + this.element.appendChild(this.button_elt); + // Mark as closed (to allow dispatch) + this.opened = false; + // Dispatch last cached value + this.apply_cache(); + }, + // Set text content when content is smaller than menu (no scrolling) + set_complete_text: function(){ + let spans = this.text_elt.children; + let c = 0; + for(let item of this.content){ + let span=spans[c]; + span.textContent = item; + span.setAttribute("onclick", "hmi_widgets['«$hmi_element/@id»'].on_selection_click("+c+")"); + c++; + } + }, + // Move partial view : + // false : upward, lower value + // true : downward, higher value + scroll: function(forward){ + let contentlength = this.content.length; + let spans = this.text_elt.children; + let spanslength = spans.length; + // reduce accounted menu size according to jumps + if(this.menu_offset != 0) spanslength--; + if(this.menu_offset < contentlength - 1) spanslength--; + if(forward){ + this.menu_offset = Math.min( + contentlength - spans.length + 1, + this.menu_offset + spanslength); + }else{ + this.menu_offset = Math.max( + 0, + this.menu_offset - spanslength); + } + console.log(this.menu_offset); + this.set_partial_text(); + }, + // Setup partial view text content + // with jumps at first and last entry when appropriate + set_partial_text: function(){ + let spans = this.text_elt.children; + let contentlength = this.content.length; + let spanslength = spans.length; + let i = this.menu_offset, c = 0; + while(c < spanslength){ + let span=spans[c]; + // backward jump only present if not exactly at start + if(c == 0 && i != 0){ + span.textContent = "↑ ↑ ↑"; + span.setAttribute("onclick", "hmi_widgets['«$hmi_element/@id»'].on_backward_click()"); + // presence of forward jump when not right at the end + }else if(c == spanslength-1 && i < contentlength - 1){ + span.textContent = "↓ ↓ ↓"; + span.setAttribute("onclick", "hmi_widgets['«$hmi_element/@id»'].on_forward_click()"); + // otherwise normal content + }else{ + span.textContent = this.content[i]; + span.setAttribute("onclick", "hmi_widgets['«$hmi_element/@id»'].on_selection_click("+i+")"); + i++; + } + c++; + } + }, + open: function(){ + let length = this.content.length; + // systematically reset text, to strip eventual whitespace spans + this.reset_text(); + // grow as much as needed or possible + let slots = this.grow_text(length); + // Depending on final size + if(slots == length) { + // show all at once + this.set_complete_text(); + } else { + // eventualy align menu to current selection, compensating for lift + let offset = this.last_selection - this.lift; + if(offset > 0) + this.menu_offset = Math.min(offset + 1, length - slots + 1); + else + this.menu_offset = 0; + // show surrounding values + this.set_partial_text(); + } + // Now that text size is known, we can set the box around it + this.adjust_box_to_text(); + // Take button out until menu closed + this.element.removeChild(this.button_elt); + // Rise widget to top by moving it to last position among siblings + this.element.parentNode.appendChild(this.element.parentNode.removeChild(this.element)); + // disable interaction with background + svg_root.addEventListener("click", this.bound_close_on_click_elsewhere, true); + // mark as open + this.opened = true; + }, + // Put text element in normalized state + reset_text: function(){ + let txt = this.text_elt; + let first = txt.firstElementChild; + // remove attribute eventually added to first text line while opening + first.removeAttribute("onclick"); + first.removeAttribute("dy"); + // keep only the first line of text + for(let span of Array.from(txt.children).slice(1)){ + txt.removeChild(span) + } + }, + // Put rectangle element in saved original state + reset_box: function(){ + let m = this.box_bbox; + let b = this.box_elt; + b.x.baseVal.value = m.x; + b.y.baseVal.value = m.y; + b.width.baseVal.value = m.width; + b.height.baseVal.value = m.height; + }, + // Use margin and text size to compute box size + adjust_box_to_text: function(){ + let [lmargin, tmargin] = this.margins; + let m = this.text_elt.getBBox(); + let b = this.box_elt; + b.x.baseVal.value = m.x - lmargin; + b.y.baseVal.value = m.y - tmargin; + b.width.baseVal.value = 2 * lmargin + m.width; + b.height.baseVal.value = 2 * tmargin + m.height; + }, +|| +} diff -r 703ebf57508a -r a4bae7edca13 svghmi/widget_foreach.ysl2 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/svghmi/widget_foreach.ysl2 Fri Jul 03 10:03:25 2020 +0200 @@ -0,0 +1,105 @@ + +template "widget[@type='ForEach']", mode="widget_defs" { + param "hmi_element"; + + const "class","arg[1]/@value"; + + const "base_path","path/@value"; + const "hmi_index_base", "$indexed_hmitree/*[@hmipath = $base_path]"; + const "hmi_tree_base", "$hmitree/descendant-or-self::*[@path = $hmi_index_base/@path]"; + const "hmi_tree_items", "$hmi_tree_base/*[@class = $class]"; + const "hmi_index_items", "$indexed_hmitree/*[@path = $hmi_tree_items/@path]"; + const "items_paths", "$hmi_index_items/@hmipath"; + | index_pool: [ + foreach "$hmi_index_items" { + | «@index»`if "position()!=last()" > ,` + } + | ], + | init: function() { + const "prefix","concat($class,':')"; + const "buttons_regex","concat('^',$prefix,'[+\-][0-9]+')"; + const "buttons", "$hmi_element/*[regexp:test(@inkscape:label, $buttons_regex)]"; + foreach "$buttons" { + const "op","substring-after(@inkscape:label, $prefix)"; + | id("«@id»").setAttribute("onclick", "hmi_widgets['«$hmi_element/@id»'].on_click('«$op»', evt)"); + } + | + | this.items = [ + const "items_regex","concat('^',$prefix,'[0-9]+')"; + const "unordered_items","$hmi_element//*[regexp:test(@inkscape:label, $items_regex)]"; + foreach "$unordered_items" { + const "elt_label","concat($prefix, string(position()))"; + const "elt","$unordered_items[@inkscape:label = $elt_label]"; + const "pos","position()"; + const "item_path", "$items_paths[$pos]"; + | [ /* item="«$elt_label»" path="«$item_path»" */ + if "count($elt)=0" error > Missing item labeled «$elt_label» in ForEach widget «$hmi_element/@id» + foreach "func:refered_elements($elt)[@id = $hmi_elements/@id][not(@id = $elt/@id)]" { + if "not(func:is_descendant_path(func:widget(@id)/path/@value, $item_path))" + error > Widget id="«@id»" label="«@inkscape:label»" is having wrong path. Accroding to ForEach widget ancestor id="«$hmi_element/@id»", path should be descendant of "«$item_path»". + | hmi_widgets["«@id»"]`if "position()!=last()" > ,` + } + | ]`if "position()!=last()" > ,` + } + | ] + | }, + | item_offset: 0, +} + +template "widget[@type='ForEach']", mode="widget_class" +|| +class ForEachWidget extends Widget{ + unsub(){ + for(let item of this.items){ + for(let widget of item) { + widget.unsub(); + } + } + this.offset = 0; + } + + foreach_widgets_do(new_offset, todo){ + this.offset = new_offset; + for(let i = 0; i < this.items.length; i++) { + let item = this.items[i]; + let orig_item_index = this.index_pool[i]; + let item_index = this.index_pool[i+this.item_offset]; + let item_index_offset = item_index - orig_item_index; + for(let widget of item) { + todo(widget).call(widget, new_offset + item_index_offset); + } + } + } + + sub(new_offset=0){ + this.foreach_widgets_do(new_offset, w=>w.sub); + } + + apply_cache() { + this.foreach_widgets_do(this.offset, w=>w.apply_cache); + } + + on_click(opstr, evt) { + let new_item_offset = eval(String(this.item_offset)+opstr); + if(new_item_offset + this.items.length > this.index_pool.length) { + if(this.item_offset + this.items.length == this.index_pool.length) + new_item_offset = 0; + else + new_item_offset = this.index_pool.length - this.items.length; + } else if(new_item_offset < 0) { + if(this.item_offset == 0) + new_item_offset = this.index_pool.length - this.items.length; + else + new_item_offset = 0; + } + this.item_offset = new_item_offset; + this.unsub(); + this.sub(this.offset); + update_subscriptions(); + need_cache_apply.push(this); + jumps_need_update = true; + requestHMIAnimation(); + } +} +|| + diff -r 703ebf57508a -r a4bae7edca13 svghmi/widget_input.ysl2 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/svghmi/widget_input.ysl2 Fri Jul 03 10:03:25 2020 +0200 @@ -0,0 +1,50 @@ +// widget_input.ysl2 + +template "widget[@type='Input']", mode="widget_defs" { + param "hmi_element"; + const "value_elt" { + optional_labels("value"); + } + const "have_value","string-length($value_elt)>0"; + value "$value_elt"; + if "$have_value" + | frequency: 5, + | last_val: undefined, + | dispatch: function(value) { + | this.last_val = value; + if "$have_value" + | this.value_elt.textContent = String(value); + + | }, + const "edit_elt_id","$hmi_element/*[@inkscape:label='edit'][1]/@id"; + | init: function() { + if "$edit_elt_id" { + | id("«$edit_elt_id»").setAttribute("onclick", "hmi_widgets['«$hmi_element/@id»'].on_edit_click()"); + } + foreach "$hmi_element/*[regexp:test(@inkscape:label,'^[=+\-].+')]" { + | id("«@id»").setAttribute("onclick", "hmi_widgets['«$hmi_element/@id»'].on_op_click('«func:escape_quotes(@inkscape:label)»')"); + } + | }, + | on_op_click: function(opstr) { + | let orig = this.indexes[0]; + | let idx = this.offset ? orig - this.offset : orig; + | let new_val = change_hmi_value(idx, opstr); + // if "$have_value"{ + // | this.value_elt.textContent = String(new_val); + // /* TODO gray out value until refreshed */ + // } + | }, + | on_edit_click: function(opstr) { + | edit_value("«path/@value»", "«path/@type»", this, this.last_val); + | }, + + | edit_callback: function(new_val) { + | let orig = this.indexes[0]; + | let idx = this.offset ? orig - this.offset : orig; + | apply_hmi_value(idx, new_val); + // if "$have_value"{ + // | this.value_elt.textContent = String(new_val); + // /* TODO gray out value until refreshed */ + // } + | }, +} diff -r 703ebf57508a -r a4bae7edca13 svghmi/widget_jump.ysl2 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/svghmi/widget_jump.ysl2 Fri Jul 03 10:03:25 2020 +0200 @@ -0,0 +1,125 @@ +// widget_jump.ysl2 + +function "jump_widget_activity" { + param "hmi_element"; + optional_labels("active inactive"); +} + +function "jump_widget_disability" { + param "hmi_element"; + optional_labels("disabled"); +} + +template "widget[@type='Jump']", mode="widget_defs" { + param "hmi_element"; + const "activity" call "jump_widget_activity" with "hmi_element", "$hmi_element"; + const "have_activity","string-length($activity)>0"; + value "$activity"; + const "disability" call "jump_widget_disability" with "hmi_element", "$hmi_element"; + const "have_disability","$have_activity and string-length($disability)>0"; + value "$disability"; + if "$have_activity" { + | active: false, + if "$have_disability" { + | disabled: false, + | frequency: 2, + | dispatch: function(value) { + | this.disabled = !Number(value); + | this.update(); + | }, + } + | update: function(){ + if "$have_disability" { + | if(this.disabled) { + | /* show disabled */ + | this.disabled_elt.setAttribute("style", this.active_elt_style); + | /* hide inactive */ + | this.inactive_elt.setAttribute("style", "display:none"); + | /* hide active */ + | this.active_elt.setAttribute("style", "display:none"); + | } else { + | /* hide disabled */ + | this.disabled_elt.setAttribute("style", "display:none"); + } + | if(this.active) { + | /* show active */ + | this.active_elt.setAttribute("style", this.active_elt_style); + | /* hide inactive */ + | this.inactive_elt.setAttribute("style", "display:none"); + | } else { + | /* show inactive */ + | this.inactive_elt.setAttribute("style", this.inactive_elt_style); + | /* hide active */ + | this.active_elt.setAttribute("style", "display:none"); + | } + if "$have_disability" { + | } + } + | }, + } + | on_click: function(evt) { + | const index = this.indexes.length > 0 ? this.indexes[0] + this.offset : undefined; + | const name = this.args[0]; + | switch_page(name, index); + | }, + if "$have_activity" { + | notify_page_change: function(page_name, index){ + | const ref_index = this.indexes.length > 0 ? this.indexes[0] + this.offset : undefined; + | const ref_name = this.args[0]; + | this.active =((ref_name == undefined || ref_name == page_name) && index == ref_index); + | this.update(); + | }, + } + | init: function() { + /* registering event this way does not "click" through svg:use + | this.element.onclick = evt => switch_page(this.args[0]); + event must be registered by adding attribute to element instead + TODO : generalize mouse event handling by global event capture + getElementsAtPoint() + */ + | this.element.setAttribute("onclick", "hmi_widgets['«$hmi_element/@id»'].on_click(evt)"); + if "$have_activity" { + | this.active_elt_style = this.active_elt.getAttribute("style"); + | this.inactive_elt_style = this.inactive_elt.getAttribute("style"); + } + choose { + when "$have_disability" { + | this.disabled_elt_style = this.disabled_elt.getAttribute("style"); + } + otherwise { + | this.unsubscribable = true; + } + } + | }, +} + +template "widget[@type='Jump']", mode="per_page_widget_template"{ + param "page_desc"; + /* check that given path is compatible with page's reference path */ + if "path" { + /* when no page name provided, check for same page */ + const "target_page_name" choose { + when "arg" value "arg[1]/@value"; + otherwise value "$page_desc/arg[1]/@value"; + } + const "target_page_path" choose { + when "arg" value "$hmi_pages_descs[arg[1]/@value = $target_page_name]/path[1]/@value"; + otherwise value "$page_desc/path[1]/@value"; + } + + if "not(func:same_class_paths($target_page_path, path[1]/@value))" + error > Jump id="«@id»" to page "«$target_page_name»" with incompatible path "«path[1]/@value» (must be same class as "«$target_page_path»") + } +} + +emit "declarations:jump" +|| +var jumps_need_update = false; +var jump_history = [[default_page, undefined]]; + +function update_jumps() { + page_desc[current_visible_page].jumps.map(w=>w.notify_page_change(current_visible_page,current_page_index)); + jumps_need_update = false; +}; + +|| + diff -r 703ebf57508a -r a4bae7edca13 svghmi/widget_keypad.ysl2 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/svghmi/widget_keypad.ysl2 Fri Jul 03 10:03:25 2020 +0200 @@ -0,0 +1,107 @@ +// widget_keypad.ysl2 + +emit "declarations:keypad" { + | + | var keypads = { + foreach "$keypads_descs"{ + const "keypad_id","@id"; + foreach "arg"{ + const "g", "$geometry[@Id = $keypad_id]"; + | "«@value»":["«$keypad_id»", «$g/@x», «$g/@y»], + } + } + | } +} + +template "widget[@type='Keypad']", mode="widget_defs" { + param "hmi_element"; + labels("Esc Enter BackSpace Keys Info Value"); + optional_labels("Sign Space NumDot"); + activable_labels("CapsLock Shift"); + | init: function() { + foreach "$hmi_element/*[@inkscape:label = 'Keys']/*" { + | id("«@id»").setAttribute("onclick", "hmi_widgets['«$hmi_element/@id»'].on_key_click('«func:escape_quotes(@inkscape:label)»')"); + } + foreach "str:split('Esc Enter BackSpace Sign Space NumDot CapsLock Shift')" { + | if(this.«.»_elt) + | this.«.»_elt.setAttribute("onclick", "hmi_widgets['«$hmi_element/@id»'].on_«.»_click()"); + } + | }, + | on_key_click: function(symbols) { + | var syms = symbols.split(" "); + | this.shift |= this.caps; + | this.editstr += syms[this.shift?syms.length-1:0]; + | this.shift = false; + | this.update(); + | }, + | on_Esc_click: function() { + | end_modal.call(this); + | }, + | on_Enter_click: function() { + | end_modal.call(this); + | callback_obj = this.result_callback_obj; + | callback_obj.edit_callback(this.editstr); + | }, + | on_BackSpace_click: function() { + | this.editstr = this.editstr.slice(0,this.editstr.length-1); + | this.update(); + | }, + | on_Sign_click: function() { + | if(this.editstr[0] == "-") + | this.editstr = this.editstr.slice(1,this.editstr.length); + | else + | this.editstr = "-" + this.editstr; + | this.update(); + | }, + | on_NumDot_click: function() { + | if(this.editstr.indexOf(".") == "-1"){ + | this.editstr += "."; + | this.update(); + | } + | }, + | on_Space_click: function() { + | this.editstr += " "; + | this.update(); + | }, + | caps: false, + | _caps: undefined, + | on_CapsLock_click: function() { + | this.caps = !this.caps; + | this.update(); + | }, + | shift: false, + | _shift: undefined, + | on_Shift_click: function() { + | this.shift = !this.shift; + | this.caps = false; + | this.update(); + | }, + const "g", "$geometry[@Id = $hmi_element/@id]"; + | coordinates: [«$g/@x», «$g/@y»], + | editstr: "", + | _editstr: undefined, + | result_callback_obj: undefined, + | start_edit: function(info, valuetype, callback_obj, initial) { + | show_modal.call(this); + | this.editstr = initial; + | this.result_callback_obj = callback_obj; + | this.Info_elt.textContent = info; + | this.shift = false; + | this.caps = false; + | this.update(); + | }, + | update: function() { + | if(this.editstr != this._editstr){ + | this._editstr = this.editstr; + | this.Value_elt.textContent = this.editstr; + | } + | if(this.shift != this._shift){ + | this._shift = this.shift; + | (this.shift?widget_active_activable:widget_inactive_activable)(this.Shift_sub); + | } + | if(this.caps != this._caps){ + | this._caps = this.caps; + | (this.caps?widget_active_activable:widget_inactive_activable)(this.CapsLock_sub); + | } + | }, +} diff -r 703ebf57508a -r a4bae7edca13 svghmi/widget_meter.ysl2 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/svghmi/widget_meter.ysl2 Fri Jul 03 10:03:25 2020 +0200 @@ -0,0 +1,31 @@ +// widget_meter.ysl2 + + +template "widget[@type='Meter']", mode="widget_defs" { + param "hmi_element"; + | frequency: 10, + labels("needle range"); + optional_labels("value min max"); + | dispatch: function(value) { + | if(this.value_elt) + | this.value_elt.textContent = String(value); + | let [min,max,totallength] = this.range; + | let length = Math.max(0,Math.min(totallength,(Number(value)-min)*totallength/(max-min))); + | let tip = this.range_elt.getPointAtLength(length); + | this.needle_elt.setAttribute('d', "M "+this.origin.x+","+this.origin.y+" "+tip.x+","+tip.y); + | }, + | origin: undefined, + | range: undefined, + | init: function() { + | let min = this.min_elt ? + | Number(this.min_elt.textContent) : + | this.args.length >= 1 ? this.args[0] : 0; + | let max = this.max_elt ? + | Number(this.max_elt.textContent) : + | this.args.length >= 2 ? this.args[1] : 100; + | this.range = [min, max, this.range_elt.getTotalLength()] + | this.origin = this.needle_elt.getPointAtLength(0); + | }, +} + + diff -r 703ebf57508a -r a4bae7edca13 svghmi/widget_switch.ysl2 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/svghmi/widget_switch.ysl2 Fri Jul 03 10:03:25 2020 +0200 @@ -0,0 +1,32 @@ +// widget_switch.ysl2 + +template "widget[@type='Switch']", mode="widget_class" + || + class SwitchWidget extends Widget{ + frequency = 5; + dispatch(value) { + for(let choice of this.choices){ + if(value != choice.value){ + choice.elt.setAttribute("style", "display:none"); + } else { + choice.elt.setAttribute("style", choice.style); + } + } + } + } + || + +template "widget[@type='Switch']", mode="widget_defs" { + param "hmi_element"; + | choices: [ + const "regex",!"'^(\"[^\"].*\"|\-?[0-9]+|false|true)(#.*)?$'"!; + foreach "$result_svg_ns//*[@id = $hmi_element/@id]//*[regexp:test(@inkscape:label,$regex)]" { + const "literal", "regexp:match(@inkscape:label,$regex)[2]"; + | { + | elt:id("«@id»"), + | style:"«@style»", + | value:«$literal» + | }`if "position()!=last()" > ,` + } + | ], +} diff -r 703ebf57508a -r a4bae7edca13 svghmi/widget_tooglebutton.ysl2 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/svghmi/widget_tooglebutton.ysl2 Fri Jul 03 10:03:25 2020 +0200 @@ -0,0 +1,30 @@ +// widget_tooglebutton.ysl2 + +template "widget[@type='ToggleButton']", mode="widget_defs" { + param "hmi_element"; + labels("active inactive"); + | frequency: 5, + | state: 0, + | dispatch: function(value) { + | this.state = value; + | if (this.state) { + | this.active_elt.setAttribute("style", this.active_style); + | this.inactive_elt.setAttribute("style", "display:none"); + | this.state = 0; + | } else { + | this.inactive_elt.setAttribute("style", this.inactive_style); + | this.active_elt.setAttribute("style", "display:none"); + | this.state = 1; + | } + | }, + | on_click: function(evt) { + | change_hmi_value(this.indexes[0], "="+this.state); + | }, + | active_style: undefined, + | inactive_style: undefined, + | init: function() { + | this.active_style = this.active_elt.style.cssText; + | this.inactive_style = this.inactive_elt.style.cssText; + | this.element.setAttribute("onclick", "hmi_widgets['«$hmi_element/@id»'].on_click(evt)"); + | }, +} \ No newline at end of file diff -r 703ebf57508a -r a4bae7edca13 svghmi/widgets_common.ysl2 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/svghmi/widgets_common.ysl2 Fri Jul 03 10:03:25 2020 +0200 @@ -0,0 +1,189 @@ +// widgets_common.ysl2 + +in xsl decl labels(*ptr, name="defs_by_labels") alias call-template { + with "hmi_element", "$hmi_element"; + with "labels"{text *ptr}; + content; +}; + +decl optional_labels(*ptr) alias - { + /* TODO add some per label xslt variable to check if exist */ + labels(*ptr){ + with "mandatory","'no'"; + content; + } +}; + +decl activable_labels(*ptr) alias - { + optional_labels(*ptr) { + with "subelements","'active inactive'"; + content; + } +}; + +template "svg:*", mode="hmi_widgets" { + const "widget", "func:widget(@id)"; + const "eltid","@id"; + const "args" foreach "$widget/arg" > "«@value»"`if "position()!=last()" > ,` + const "indexes" foreach "$widget/path" { + choose { + when "not(@index)" { + warning > Widget «$widget/@type» id="«$eltid»" : No match for path "«@value»" in HMI tree + } + otherwise { + > «@index»`if "position()!=last()" > ,` + } + } + } + + | "«@id»": new «$widget/@type»Widget ("«@id»",[«$args»],[«$indexes»],{ + apply "$widget", mode="widget_defs" with "hmi_element","."; + | })`if "position()!=last()" > ,` +} + +def "func:unique_types" { + param "elts_with_type"; + choose { + when "count($elts_with_type) > 1" { + const "prior_results","func:unique_types($elts_with_type[position()!=last()])"; + choose { + when "$elts_with_type[last()][@type = $prior_results/@type]"{ + // type already in + result "$prior_results"; + } + otherwise { + result "$prior_results | $elts_with_type[last()]"; + } + } + } + otherwise { + result "$elts_with_type"; + } + } +} + +emit "preamble:widget-base-class" { + || + class Widget { + offset = 0; + frequency = 10; /* FIXME arbitrary default max freq. Obtain from config ? */ + unsubscribable = false; + constructor(elt_id,args,indexes,members){ + this.element_id = elt_id; + this.element = id(elt_id); + this.args = args; + this.indexes = indexes; + Object.keys(members).forEach(prop => this[prop]=members[prop]); + } + + unsub(){ + /* remove subsribers */ + if(!this.unsubscribable) for(let index of this.indexes){ + let idx = index + this.offset; + subscribers[idx].delete(this); + } + this.offset = 0; + } + + sub(new_offset=0){ + /* set the offset because relative */ + this.offset = new_offset; + /* add this's subsribers */ + if(!this.unsubscribable) for(let index of this.indexes){ + subscribers[index + new_offset].add(this); + } + need_cache_apply.push(this); + } + + apply_cache() { + if(!this.unsubscribable) for(let index of this.indexes){ + /* dispatch current cache in newly opened page widgets */ + let realindex = index+this.offset; + let cached_val = cache[realindex]; + if(cached_val != undefined) + dispatch_value_to_widget(this, realindex, cached_val, cached_val); + } + } + + } + || +} + +emit "preamble:hmi-classes" { + const "used_widget_types", "func:unique_types($parsed_widgets/widget)"; + apply "$used_widget_types", mode="widget_class"; +} + +template "widget", mode="widget_class" +|| +class «@type»Widget extends Widget{ + /* empty class, as «@type» widget didn't provide any */ +} +|| + +const "excluded_types", "str:split('Page Lang List')"; +const "excluded_ids","$parsed_widgets/widget[not(@type = $excluded_types)]/@id"; + +emit "preamble:hmi-elements" { + | var hmi_widgets = { + apply "$hmi_elements[@id = $excluded_ids]", mode="hmi_widgets"; + | } +} + +function "defs_by_labels" { + param "labels","''"; + param "mandatory","'yes'"; + param "subelements","/.."; + param "hmi_element"; + const "widget_type","@type"; + foreach "str:split($labels)" { + const "name","."; + const "elt","$result_svg_ns//*[@id = $hmi_element/@id]//*[@inkscape:label=$name][1]"; + choose { + when "not($elt/@id)" { + if "$mandatory='yes'" { + error > «$widget_type» widget must have a «$name» element + } + // otherwise produce nothing + } + otherwise { + | «$name»_elt: id("«$elt/@id»"), + if "$subelements" { + | «$name»_sub: { + foreach "str:split($subelements)" { + const "subname","."; + const "subelt","$elt/*[@inkscape:label=$subname][1]"; + choose { + when "not($subelt/@id)" { + if "$mandatory='yes'" { + error > «$widget_type» widget must have a «$name»/«$subname» element + } + | /* missing «$name»/«$subname» element */ + } + otherwise { + | "«$subname»": id("«$subelt/@id»")`if "position()!=last()" > ,` + } + } + } + | }, + } + } + } + } +} + +def "func:escape_quotes" { + param "txt"; + // have to use a python string to enter escaped quote + const "frst", !"substring-before($txt,'\"')"!; + const "frstln", "string-length($frst)"; + choose { + when "$frstln > 0 and string-length($txt) > $frstln" { + result !"concat($frst,'\\\"',func:escape_quotes(substring-after($txt,'\"')))"!; + } + otherwise { + result "$txt"; + } + } +} + diff -r 703ebf57508a -r a4bae7edca13 targets/Linux/plc_Linux_main.c --- a/targets/Linux/plc_Linux_main.c Wed Jul 01 10:36:20 2020 +0200 +++ b/targets/Linux/plc_Linux_main.c Fri Jul 03 10:03:25 2020 +0200 @@ -235,3 +235,18 @@ { pthread_mutex_lock(&python_mutex); } + +static pthread_cond_t svghmi_send_WakeCond = PTHREAD_COND_INITIALIZER; +static pthread_mutex_t svghmi_send_WakeCondLock = PTHREAD_MUTEX_INITIALIZER; + +void SVGHMI_SuspendFromPythonThread(void) +{ + pthread_mutex_lock(&svghmi_send_WakeCondLock); + pthread_cond_wait(&svghmi_send_WakeCond, &svghmi_send_WakeCondLock); + pthread_mutex_unlock(&svghmi_send_WakeCondLock); +} + +void SVGHMI_WakeupFromRTThread(void) +{ + pthread_cond_signal(&svghmi_send_WakeCond); +} diff -r 703ebf57508a -r a4bae7edca13 targets/Xenomai/plc_Xenomai_main.c --- a/targets/Xenomai/plc_Xenomai_main.c Wed Jul 01 10:36:20 2020 +0200 +++ b/targets/Xenomai/plc_Xenomai_main.c Fri Jul 03 10:03:25 2020 +0200 @@ -26,6 +26,8 @@ #define PLC_STATE_WAITDEBUG_PIPE_CREATED 64 #define PLC_STATE_WAITPYTHON_FILE_OPENED 128 #define PLC_STATE_WAITPYTHON_PIPE_CREATED 256 +#define PLC_STATE_SVGHMI_FILE_OPENED 512 +#define PLC_STATE_SVGHMI_PIPE_CREATED 1024 #define WAITDEBUG_PIPE_DEVICE "/dev/rtp0" #define WAITDEBUG_PIPE_MINOR 0 @@ -35,6 +37,8 @@ #define WAITPYTHON_PIPE_MINOR 2 #define PYTHON_PIPE_DEVICE "/dev/rtp3" #define PYTHON_PIPE_MINOR 3 +#define SVGHMI_PIPE_DEVICE "/dev/rtp4" +#define SVGHMI_PIPE_MINOR 4 #define PIPE_SIZE 1 // rt-pipes commands @@ -68,10 +72,12 @@ RT_PIPE WaitPython_pipe; RT_PIPE Debug_pipe; RT_PIPE Python_pipe; +RT_PIPE svghmi_pipe; int WaitDebug_pipe_fd; int WaitPython_pipe_fd; int Debug_pipe_fd; int Python_pipe_fd; +int svghmi_pipe_fd; int PLC_shutdown = 0; @@ -114,6 +120,16 @@ PLC_state &= ~PLC_STATE_TASK_CREATED; } + if (PLC_state & PLC_STATE_SVGHMI_PIPE_CREATED) { + rt_pipe_delete(&svghmi_pipe); + PLC_state &= ~PLC_STATE_SVGHMI_PIPE_CREATED; + } + + if (PLC_state & PLC_STATE_SVGHMI_FILE_OPENED) { + close(svghmi_pipe_fd); + PLC_state &= ~PLC_STATE_SVGHMI_FILE_OPENED; + } + if (PLC_state & PLC_STATE_WAITDEBUG_PIPE_CREATED) { rt_pipe_delete(&WaitDebug_pipe); PLC_state &= ~PLC_STATE_WAITDEBUG_PIPE_CREATED; @@ -240,6 +256,16 @@ _startPLCLog(FO WAITPYTHON_PIPE_DEVICE); PLC_state |= PLC_STATE_WAITPYTHON_FILE_OPENED; + /* create svghmi_pipe */ + if(rt_pipe_create(&svghmi_pipe, "svghmi_pipe", SVGHMI_PIPE_MINOR, PIPE_SIZE) < 0) + _startPLCLog(FO "svghmi_pipe real-time end"); + PLC_state |= PLC_STATE_SVGHMI_PIPE_CREATED; + + /* open svghmi_pipe*/ + if((svghmi_pipe_fd = open(SVGHMI_PIPE_DEVICE, O_RDWR)) == -1) + _startPLCLog(FO SVGHMI_PIPE_DEVICE); + PLC_state |= PLC_STATE_SVGHMI_FILE_OPENED; + /*** create PLC task ***/ if(rt_task_create(&PLC_task, "PLC_task", 0, 50, T_JOINABLE)) _startPLCLog("Failed creating PLC task"); @@ -395,6 +421,18 @@ } /* as plc does not wait for lock. */ } +void SVGHMI_SuspendFromPythonThread(void) +{ + char cmd = 1; /*whatever*/ + read(svghmi_pipe_fd, &cmd, sizeof(cmd)); +} + +void SVGHMI_WakeupFromRTThread(void) +{ + char cmd; + rt_pipe_write(&svghmi_pipe, &cmd, sizeof(cmd), P_NORMAL); +} + #ifndef HAVE_RETAIN int CheckRetainBuffer(void) { diff -r 703ebf57508a -r a4bae7edca13 targets/plc_debug.c --- a/targets/plc_debug.c Wed Jul 01 10:36:20 2020 +0200 +++ b/targets/plc_debug.c Fri Jul 03 10:03:25 2020 +0200 @@ -100,7 +100,7 @@ void __init_debug(void) { /* init local static vars */ -#ifndef TARGET_ONLINE_DEBUG_DISABLE +#ifndef TARGET_ONLINE_DEBUG_DISABLE buffer_cursor = debug_buffer; buffer_state = BUFFER_FREE; #endif @@ -109,9 +109,9 @@ InitRetain(); /* Iterate over all variables to fill debug buffer */ if(CheckRetainBuffer()){ - __for_each_variable_do(RemindIterator); + __for_each_variable_do(RemindIterator); }else{ - char mstr[] = "RETAIN memory invalid - defaults used"; + char mstr[] = "RETAIN memory invalid - defaults used"; LogMessage(LOG_WARNING, mstr, sizeof(mstr)); } retain_offset = 0; @@ -124,7 +124,7 @@ void __cleanup_debug(void) { -#ifndef TARGET_ONLINE_DEBUG_DISABLE +#ifndef TARGET_ONLINE_DEBUG_DISABLE buffer_cursor = debug_buffer; InitiateDebugTransfer(); #endif @@ -150,16 +150,14 @@ if(flags & ( __IEC_DEBUG_FLAG | __IEC_RETAIN_FLAG)){ USINT size = __get_type_enum_size(dsc->type); -#ifndef TARGET_ONLINE_DEBUG_DISABLE +#ifndef TARGET_ONLINE_DEBUG_DISABLE if(flags & __IEC_DEBUG_FLAG){ /* copy visible variable to buffer */; if(do_debug){ /* compute next cursor positon. No need to check overflow, as BUFFER_SIZE is computed large enough */ - if((dsc->type == STRING_ENUM) || - (dsc->type == STRING_P_ENUM) || - (dsc->type == STRING_O_ENUM)){ + if(__Is_a_string(dsc)){ /* optimization for strings */ size = ((STRING*)visible_value_p)->len + 1; } @@ -174,7 +172,7 @@ memcpy(real_value_p, visible_value_p, size); } } -#endif +#endif if(flags & __IEC_RETAIN_FLAG){ /* compute next cursor positon*/ diff -r 703ebf57508a -r a4bae7edca13 targets/var_access.c --- a/targets/var_access.c Wed Jul 01 10:36:20 2020 +0200 +++ b/targets/var_access.c Fri Jul 03 10:03:25 2020 +0200 @@ -14,6 +14,10 @@ forced_value_p = &((__IEC_##TYPENAME##_p *)varp)->fvalue;\ break; +#define __Is_a_string(dsc) (dsc->type == STRING_ENUM) ||\ + (dsc->type == STRING_P_ENUM) ||\ + (dsc->type == STRING_O_ENUM) + static void* UnpackVar(__Unpack_desc_type *dsc, void **real_value_p, char *flags) { void *varp = dsc->ptr; diff -r 703ebf57508a -r a4bae7edca13 tests/svghmi/beremiz.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tests/svghmi/beremiz.xml Fri Jul 03 10:03:25 2020 +0200 @@ -0,0 +1,5 @@ + + + + + diff -r 703ebf57508a -r a4bae7edca13 tests/svghmi/plc.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tests/svghmi/plc.xml Fri Jul 03 10:03:25 2020 +0200 @@ -0,0 +1,517 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + TargetPressure + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + TargetPressure + + + + + + + + + + + + + + Sloth + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Pressure + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Sloth + + + + + + + + + + + Pressure + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 100 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + strout + + + + + + + TargetPressure + + + + + + + + + + + + + + + + + + + + + + + + + + + + + strin + + + + + + + boolin + + + + + + + + + + + boolout + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Pressure + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 2 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + + + + + + + + + + + + + + + + + + diff -r 703ebf57508a -r a4bae7edca13 tests/svghmi/py_ext_0@py_ext/baseconfnode.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tests/svghmi/py_ext_0@py_ext/baseconfnode.xml Fri Jul 03 10:03:25 2020 +0200 @@ -0,0 +1,2 @@ + + diff -r 703ebf57508a -r a4bae7edca13 tests/svghmi/py_ext_0@py_ext/pyfile.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tests/svghmi/py_ext_0@py_ext/pyfile.xml Fri Jul 03 10:03:25 2020 +0200 @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + diff -r 703ebf57508a -r a4bae7edca13 tests/svghmi/svghmi_0@svghmi/baseconfnode.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tests/svghmi/svghmi_0@svghmi/baseconfnode.xml Fri Jul 03 10:03:25 2020 +0200 @@ -0,0 +1,2 @@ + + diff -r 703ebf57508a -r a4bae7edca13 tests/svghmi/svghmi_0@svghmi/confnode.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tests/svghmi/svghmi_0@svghmi/confnode.xml Fri Jul 03 10:03:25 2020 +0200 @@ -0,0 +1,2 @@ + + diff -r 703ebf57508a -r a4bae7edca13 tests/svghmi/svghmi_0@svghmi/svghmi.svg --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tests/svghmi/svghmi_0@svghmi/svghmi.svg Fri Jul 03 10:03:25 2020 +0200 @@ -0,0 +1,2853 @@ + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Home + + + + + + + + + Settings + + + + 8888 + + + + + + + + 8888 + + + + 0 + 10000 + 000 + bar + + SetPoint + Actual + Pressure + + + + + + + 0 + 10000 + 000 + €£$¥ + + + 8888 + + + + →0← + + + + -10 + + + + -100 + + + + +100 + + + + +10 + + + 8888 + 8888 + 8888 + + 8888 + + + + dhu + + + + plop + + + + mhoo + + + + yodl + + + + mhe + + + + + + number + + + + + + + + 7 + + + + 4 + + + + 1 + + + + 8 + + + + 5 + + + + 2 + + + + 9 + + + + 6 + + + + 3 + + + + 0 + + + + + Esc + + + + + + + + +/- + + information + + + . + + + + + + + + + Q + + + + W + + + + E + + + + R + + + + T + + + + Y + + + + U + + + + I + + + + O + + + + P + + + + A + + + + S + + + + D + + + + F + + + + G + + + + H + + + + J + + + + K + + + + L + + + + Z + + + + X + + + + C + + + + V + + + + B + + + + N + + + + M + + + + . + : + + + + ; + , + + + + 1 + + + + 2 + + + + 3 + + + + 4 + + + + 5 + + + + 6 + + + + 7 + + + + 8 + + + + 9 + - + + + + 0 + + + + + + + Esc + + + + + + + + + + + + + Caps + Lock + + + + Caps + Lock + + + + text + + + + Shift + + Shift + + + + Shift + + Shift + + + information + + + + sel_0 + + + + + + + + + onetwothreefiveseveneleven + + + 8888 + + + + + + + + + + + up + + + + + + + + + + + + + + + + + + + + + + 8888 + + + + dhu + + + + plop + + + + mhoo + + + + yodl + + + + mhe + + +