Commit 32f88d04 authored by Gino Tosti's avatar Gino Tosti
Browse files

added checks on Null variable in opcuserver template and code. Added excel to...

added checks on Null variable in opcuserver template and code. Added excel to word ICD file converter
parent e4725fad
Loading
Loading
Loading
Loading
+26 −2
Original line number Diff line number Diff line
@@ -24,7 +24,28 @@ except ImportError:
        shell.interact()

from opcua import ua, uamethod, Server
def checkData(var):

    for v in var:
       ty=v.get_data_type_as_variant_type()
       if ty==ua.VariantType.Boolean:
          if v.get_value()==None:
             v.set_value(False, ua.VariantType.Boolean)
       if ty==ua.VariantType.String:
          if v.get_value()==None:
             v.set_value("String-Data", ua.VariantType.String)
       if ty==ua.VariantType.Int16:
          if v.get_value()==None:
             v.set_value(0, ua.VariantType.Int16)
       if ty==ua.VariantType.Int32:
          if v.get_value()==None:
             v.set_value(0, ua.VariantType.Int32)
       if ty==ua.VariantType.UInt16:
          if v.get_value()==None:
             v.set_value(0, ua.VariantType.UInt16)
       if ty==ua.VariantType.UInt32:
          if v.get_value()==None:
             v.set_value(0, ua.VariantType.UInt32)

class SubHandler(object):
    """
@@ -49,7 +70,7 @@ class VarUpdater(Thread):
        while not self._stopev:
            for v in self.var:
                ty=v.get_data_type_as_variant_type()
                if ty!=ua.VariantType.String and ty!=ua.VariantType.Boolean: 
                if ty==ua.VariantType.Double: 
                     if v.get_value()!=None:
                        v.set_value(v.get_value()+random.uniform(-5,5))
                     else:
@@ -81,6 +102,9 @@ if __name__ == "__main__":
    root = server.get_root_node()
    obj=root.get_children()[0].get_children()
    get=obj[2].get_children()
    checkData(set1)
    set1= obj[3].get_children()
    checkData(set1)

    # starting Server
    server.start()
+3 −0
Original line number Diff line number Diff line
@@ -124,6 +124,9 @@
       #if $val=="nan" or $val=="NA"
	#set $val="0"
       #end if
       #if $x["OPC UA Data type"][$idx].upper()=="INT16" or $x["OPC UA Data type"][$idx].upper()=="INT32" 
		#set $val=str($val).split(".")[0]
       #end if
      <uax:$type>$val</uax:$type>
  </Value>
#end if 
+524 KiB

File added.

No diff preview for this file type.

test/icd_converter.py

0 → 100755
+167 −0
Original line number Diff line number Diff line
from docxtpl import DocxTemplate, InlineImage
from docx import *
from docx.shared import *
from docx.oxml.ns import nsdecls
from docx.oxml import parse_xml
from optparse import OptionParser
import random
import datetime
import pandas as pd

TMPFILE='/tmp/tmp_123.docx'
template_file="ASTRI-INAF-ICD-Template.docx"
args={}
def readIcd(icdfile,sheet_name):
    try:
        main_sheet = pd.read_excel(icdfile,sheet_name=sheet_name,engine="openpyxl")
    except FileNotFoundError:
        print("File does not exist")
        return None
    mains=main_sheet.dropna(axis=0,how='all')
    main=mains.dropna(axis=1,how='all')
    print(main)
    sheetT=main.T
    print(sheetT)
    return sheetT

def getSheetRecord(sheet,idx):
    mains= sheet[idx].to_dict()
    mai=[]
    for key in mains.keys():
        mai.append({'Index':key,'Value':mains[key]})
        #print(mai[-1])
    return mai

def rowTorecord(row):
    mains= row.to_dict()
    mai=[]
    for key in mains.keys():
        val=str(mains[key])
        if val=="nan":
            val="NA"
        mai.append({'Index':key,'Value':val})
        #print(mai[-1])
    return mai


def color_row(cells):
    'make row of cells background colored, defaults to column header row'
    for cell in cells:
        shading_elm_2 = parse_xml(r'<w:shd {} w:fill="CCE5FF"/>'.format(nsdecls('w')))
        cell._tc.get_or_add_tcPr().append(shading_elm_2)
def color_head(cells):
    'make row of cells background colored, defaults to column header row'
    for cell in cells:
        shading_elm_2 = parse_xml(r'<w:shd {} w:fill="99CCFF"/>'.format(nsdecls('w')))
        cell._tc.get_or_add_tcPr().append(shading_elm_2)

def createTable(document, records):
    tables = document.tables
    table1 = tables[-1]
    style=table1.style
    table = document.add_table(rows=1, cols=2,style=style)  #Create a table with and set the rows and columns
    # Define the table style.  You can set any style defined in the styles files of the library
    hdr_cells = table.rows[0].cells
    color_head(hdr_cells)
    tb_cell_run = hdr_cells[0].paragraphs[0].add_run()
    tb_cell_run.add_text('Property Name')
    tb_cell_run.font.size = Pt(14)
    tb_cell_run.bold=True
    hdr_cells[0].width = Inches(2.5)

    tb_cell_run = hdr_cells[1].paragraphs[0].add_run()
    tb_cell_run.add_text('Value')
    tb_cell_run.font.size = Pt(12)
    tb_cell_run.bold=True
    hdr_cells[0].width = Inches(2.5)
    for record in records:
        row = table.add_row()
        row_cells = row.cells
        color_row(row_cells)
        tb_cell_run = row_cells[0].paragraphs[0].add_run()
        tb_cell_run.add_text(str(record.get('Index')))
        tb_cell_run.font.size =Pt(10)
        tb_cell_run.bold=True
        row_cells[0].width = Inches(3.0)

        tb_cell_run = row_cells[1].paragraphs[0].add_run()
        tb_cell_run.add_text(str(record.get('Value')))
        tb_cell_run.font.size =Pt(10)
        row_cells[1].width = Inches(2.5)
    return table

def createMainTable(doc, main_sheet):
    caption = doc.add_paragraph("Main Tables", style="Heading 2")
    createTable(doc, main_sheet)

def makeTmpTemplate(main_sheet):
    template = DocxTemplate(template_file)
    context = {
    'Assembly':main_sheet[0]['Value'],
    'Authors':'G.Tosti,et al.',
    'Issue':'1.0',
    'ConAuthors':'S.Scuderi, et al',
    #'day': datetime.datetime.now().strftime('%d'),
    #'month': datetime.datetime.now().strftime('%m'),
    #'year': datetime.datetime.now().strftime('%Y'),
    'TableTitle':'Main Table',
    'MainSheet': main_sheet,
    }
    #Render automated report
    doc=template.render(context)
    template.save(TMPFILE)
def makeTables(doc,sheet):
    #print(sheet)
    #print(len(sheet))
    for index in range(0,len(sheet.columns)):
         record=rowTorecord(sheet[index])
         #print(record)
         doc.add_paragraph(str(record[0]['Value']),style="Heading 3")
         createTable(doc, record)
         doc.add_paragraph("")

def createDocTables(icdfile, outfile):
    sheet=readIcd(icdfile,"Main")
    if sheet is not None:
        main_sheet=getSheetRecord(sheet,0)
        makeTmpTemplate(main_sheet)
        doc=Document(TMPFILE)
        print("Adding Main table")
        createMainTable(doc, main_sheet)
        print("Adding GET table")
        Sheet=readIcd(icdfile,"GET")
        doc.add_paragraph("GET Commands", style="Heading 2")
        makeTables(doc,Sheet)
        print("Adding SET table")
        Sheet=readIcd(icdfile,"SET")
        doc.add_paragraph("SET Commands", style="Heading 2")
        makeTables(doc,Sheet)
        print("Adding MODE table")
        Sheet=readIcd(icdfile,"MODE")
        doc.add_paragraph("MODE Commands", style="Heading 2")
        makeTables(doc,Sheet)
        print("Adding CMD table")
        Sheet=readIcd(icdfile,"CMD")
        doc.add_paragraph("CMD Commands", style="Heading 2")
        makeTables(doc,Sheet)
        doc.save(outfile)
        return doc
    else:
        return None
def main():
    usage = "usage: %prog [options] arg"
    parser = OptionParser(usage)
    parser.add_option("-f", "--file", dest="filename",
                      help="read data from excel FILENAME")
    (options, args) = parser.parse_args()
    icdfile=options.filename
    outfile=icdfile.split('.')[0]+'.docx'
    if createDocTables(icdfile, outfile) is not None:
        print("The generated .Docx file is is:",outfile)
    else:
        print("Error occurred during File generation")
        exit()

if __name__ == '__main__':

    main()