I was asked quite frequently how a PDF report with process data from the PLC program can be created with PLCnext. An easy way is to use a Python script which collects process data via the REST API and creates the PDF on the device. The creation of the script is triggered by a function block in IEC61131 on the PLC.
Here are the necessary steps:
-
Install pip on the PLC for the user "plcnext_firmware". This is the user which is used by the function block that executes the Python.
sudo passwd plcnext_firmware --> assign a new password su plcnext_firmware curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py python3 get-pip.py
-
Install the required Python libraries:
python3 -m pip install requests
python3 -m pip install fpdf
- Create a Python script and copy it to the /opt/plcnext/ folder on the PLC:
import requests
import json
import sys
from fpdf import FPDF
from datetime import datetime
sys.path.append('/opt/plcnext/.local/python3.10/site-packages/')
class PDF(FPDF):
def header(self):
self.image('Logo.png', 10, 8, 40) # optional
self.set_font('Arial', 'B', 20)
self.cell(0,10,'Monthly report', border=False, ln=True, align='C')
self.ln(20)
def footer(self):
self.set_y(-15)
self.set_font('Arial', 'I', 12)
self.cell(0,10,f'Page {self.page_no()}/{{nb}}',align='C')
##################################
Read data from the PLC via REST
##################################
response = requests.get('https://192.168.178.10/_pxc_api/api/variables?paths=Arp.Plc.Eclr/INST_SolarEnergy.diPower', verify=False)
data = response.json()
variables = data['variables']
value = variables[0]['value']
###############
Timestamp
###############
now = datetime.now()
current_time = now.strftime("%m.%d.%Y %H:%M:%S")
################
Create PDF
################
pdf = PDF('P','mm','A4')
pdf.alias_nb_pages()
pdf.set_auto_page_break(auto=True, margin = 15)
pdf.add_page()
pdf.set_font('Arial', '', 12)
mes = 'The power of the pump is ' + str(value) + ' W'
pdf.cell(200, 10, 'Report '+current_time, ln=True)
pdf.cell(200, 10, txt = mes, ln=True)
pdf.output('Report.pdf')
-
Create a new PLC project.
-
In the project create a variable which can be accessed via the REST API. For local variables, the "HMI" tag must be selected.
-
Import the PLCnextBase library into the project. The library is available in the PLCnext Store.
-
Create a program which uses the PBCL_LinuxShell command to execute the Python script. Be aware that the PLC will perform a warmstart after the first execution of the FB.
- Download and start the program. The script is executed via the xExecuteScript variable. The pdf report is stored in the /opt/plcnext/ folder. The local variable xRetain must have the retain tag checked.
Leave a Reply
You must be logged in to post a comment.