Softwell Automation

Python Industrial Automation Manual

Practical Python manual for industrial automation reporting, SQL historian data, Excel/PDF generation, email alerts, REST API and scheduled plant reports.

Request Manual / Training Details

Talk to Automation Advisor

Get expert guidance for course selection, corporate training, project support and practical learning path.

Course GuidanceSelect the correct PLC SCADA, corporate, online or Industry 4.0 path.
Batch SupportGet schedule, duration, mode and prerequisite guidance.
Project AdviceDiscuss plant, automation, reporting or training requirement.

What this page covers

SQL Data Reading

Connect Python with SQL Server and read SCADA/plant historian values.

Excel & PDF Reports

Generate shift, daily, batch and breakdown reports using Python.

Industry 4.0 Workflow

Prepare REST API, JSON, dashboard and ERP/MES data exchange logic.

Practical Learning Sequence

Practical 01: Install Python, VS Code and required reporting libraries
Practical 02: Connect Python with SQL Server using connection string
Practical 03: Read tag values, alarms and production data from historian table
Practical 04: Create Excel report with formatted rows, headings and totals
Practical 05: Generate PDF report and send by email automatically
Practical 06: Schedule report script for daily or shift-wise execution
Practical 07: Prepare REST API JSON payload for dashboard or ERP integration

Why Choose Softwell Automation

Learn automation with practical examples, industrial troubleshooting approach and complete IT/OT learning path.

Industry Experienced TrainerReal plant examples and project based training.
Hands-on LearningPLC logic, SCADA, VFD, communication and reporting practice.
Flexible ModesOnline, classroom, corporate and in-plant options.

Python Industrial Automation — Ten-Lab Code Workbook

A safe, reproducible path from local file logging to industrial protocols, SQL, reporting, APIs, testing and handover. Example addresses use TEST-NET ranges and must be replaced only with trainer-approved lab endpoints.

Lab 01 - Create a Reproducible Python Environment

Objective: Create an isolated project and record dependency versions.

A. Step-by-Step Procedure

  1. Install a supported Python 3 release in the lab environment.
  2. Create and activate a virtual environment.
  3. Install only the protocol/data packages needed by later labs.
  4. Export a requirements file and create a configuration template without passwords.
python -m venv .venv
.venv\Scripts\activate
pip install pymodbus opcua paho-mqtt pyodbc pandas fastapi uvicorn pytest
pip freeze > requirements.txt

B. Verification Checklist

  • A clean environment can be rebuilt from requirements.txt.
  • Save the project/code and record the environment version.
  • Repeat the test from a known initial state.
  • Capture the required runtime or output evidence.

C. If the Result Is Wrong

CheckAction
Environment and connectionConfirm version, driver, address, permissions and communication state.
Input, parameter or codeCompare the configured value with the lab sheet and official documentation.
Output/resultTrace the value step by step, correct the first deviation and retest safely.

D. Student Evidence Record

File

Project/code filename and revision.

Values

Inputs, settings and observed outputs.

Fault test

Fault introduced, symptom and correction.

Conclusion

Pass criteria and learner observation.

REAL LAB SCREENSHOT / OUTPUT EVIDENCE
Attach a verified capture from the completed lab.

Expected Result and Runtime Behavior

The project opens with isolated dependencies and no credentials committed.

Lab 02 - Log Validated Tag Samples to CSV

Objective: Write timestamped lab data with a defined quality field.

A. Step-by-Step Procedure

  1. Define the tag name, value and quality fields.
  2. Use UTC timestamps for portable reporting.
  3. Append one row per sample with newline-safe CSV handling.
  4. Reopen the file and validate column order and data types.
import csv
from datetime import datetime, timezone
row = [datetime.now(timezone.utc).isoformat(), "Tank.Level", 64.2, "GOOD"]
with open("tag_log.csv", "a", newline="", encoding="utf-8") as f:
    csv.writer(f).writerow(row)

B. Verification Checklist

  • The CSV contains one valid row with an ISO UTC timestamp.
  • Save the project/code and record the environment version.
  • Repeat the test from a known initial state.
  • Capture the required runtime or output evidence.

C. If the Result Is Wrong

CheckAction
Environment and connectionConfirm version, driver, address, permissions and communication state.
Input, parameter or codeCompare the configured value with the lab sheet and official documentation.
Output/resultTrace the value step by step, correct the first deviation and retest safely.

D. Student Evidence Record

File

Project/code filename and revision.

Values

Inputs, settings and observed outputs.

Fault test

Fault introduced, symptom and correction.

Conclusion

Pass criteria and learner observation.

REAL LAB SCREENSHOT / OUTPUT EVIDENCE
Attach a verified capture from the completed lab.

Expected Result and Runtime Behavior

A report tool can read the file without manual cleanup.

Lab 03 - Read Modbus TCP Registers Safely

Objective: Connect to an isolated Modbus simulator and validate the response.

A. Step-by-Step Procedure

  1. Use a simulator or training PLC—never probe an unknown production address.
  2. Configure unit/device ID and register mapping from the lab sheet.
  3. Check the response for protocol errors before using values.
  4. Close the client in all outcomes.
from pymodbus.client import ModbusTcpClient
client = ModbusTcpClient("192.0.2.10", port=502, timeout=2)
try:
    result = client.read_holding_registers(address=0, count=2, slave=1)
    if result.isError():
        raise RuntimeError(result)
    print(result.registers)
finally:
    client.close()

B. Verification Checklist

  • The simulator returns the expected two-register test pattern.
  • Save the project/code and record the environment version.
  • Repeat the test from a known initial state.
  • Capture the required runtime or output evidence.

C. If the Result Is Wrong

CheckAction
Environment and connectionConfirm version, driver, address, permissions and communication state.
Input, parameter or codeCompare the configured value with the lab sheet and official documentation.
Output/resultTrace the value step by step, correct the first deviation and retest safely.

D. Student Evidence Record

File

Project/code filename and revision.

Values

Inputs, settings and observed outputs.

Fault test

Fault introduced, symptom and correction.

Conclusion

Pass criteria and learner observation.

REAL LAB SCREENSHOT / OUTPUT EVIDENCE
Attach a verified capture from the completed lab.

Expected Result and Runtime Behavior

The script reports values or a controlled error and always closes the connection.

Lab 04 - Read an OPC UA Node with Trust Checks

Objective: Connect to a lab endpoint and read one known node.

A. Step-by-Step Procedure

  1. Use the endpoint and node ID provided by the trainer.
  2. Review certificate/security requirements before connecting.
  3. Read one value and its timestamp/quality when supported.
  4. Disconnect in a finally block.
from opcua import Client
client = Client("opc.tcp://192.0.2.20:4840")
try:
    client.connect()
    node = client.get_node("ns=2;s=Tank.Level")
    print(node.get_value())
finally:
    client.disconnect()

B. Verification Checklist

  • The value matches the server simulator and changes when the simulator tag changes.
  • Save the project/code and record the environment version.
  • Repeat the test from a known initial state.
  • Capture the required runtime or output evidence.

C. If the Result Is Wrong

CheckAction
Environment and connectionConfirm version, driver, address, permissions and communication state.
Input, parameter or codeCompare the configured value with the lab sheet and official documentation.
Output/resultTrace the value step by step, correct the first deviation and retest safely.

D. Student Evidence Record

File

Project/code filename and revision.

Values

Inputs, settings and observed outputs.

Fault test

Fault introduced, symptom and correction.

Conclusion

Pass criteria and learner observation.

REAL LAB SCREENSHOT / OUTPUT EVIDENCE
Attach a verified capture from the completed lab.

Expected Result and Runtime Behavior

One trusted lab node is read and the session closes cleanly.

Lab 05 - Publish an MQTT Telemetry Message

Objective: Publish a structured JSON payload to a lab broker.

A. Step-by-Step Procedure

  1. Define topic naming and payload fields.
  2. Use a lab broker with authentication when available.
  3. Publish with an appropriate QoS and wait for completion.
  4. Subscribe separately and verify the received payload.
import json
import paho.mqtt.client as mqtt
payload = {"tag":"Tank.Level","value":64.2,"quality":"GOOD"}
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
client.connect("192.0.2.30", 1883, 30)
info = client.publish("softwell/lab/tank", json.dumps(payload), qos=1)
info.wait_for_publish()
client.disconnect()

B. Verification Checklist

  • The subscriber receives one JSON message with the expected topic and fields.
  • Save the project/code and record the environment version.
  • Repeat the test from a known initial state.
  • Capture the required runtime or output evidence.

C. If the Result Is Wrong

CheckAction
Environment and connectionConfirm version, driver, address, permissions and communication state.
Input, parameter or codeCompare the configured value with the lab sheet and official documentation.
Output/resultTrace the value step by step, correct the first deviation and retest safely.

D. Student Evidence Record

File

Project/code filename and revision.

Values

Inputs, settings and observed outputs.

Fault test

Fault introduced, symptom and correction.

Conclusion

Pass criteria and learner observation.

REAL LAB SCREENSHOT / OUTPUT EVIDENCE
Attach a verified capture from the completed lab.

Expected Result and Runtime Behavior

Telemetry is delivered once to the lab topic and is parseable.

Lab 06 - Write to SQL Server with Parameters

Objective: Insert a sample without concatenating values into SQL text.

A. Step-by-Step Procedure

  1. Use a least-privilege lab login.
  2. Open the connection with encryption settings required by the lab.
  3. Execute a parameterized statement.
  4. Commit on success and rollback/close on failure.
import pyodbc
cn = pyodbc.connect("DSN=SoftwellLab;Trusted_Connection=yes")
try:
    cur = cn.cursor()
    cur.execute("EXEC automation.InsertTagSample ?,?,?,SYSUTCDATETIME()",
                "Tank.Level", 64.2, 192)
    cn.commit()
finally:
    cn.close()

B. Verification Checklist

  • Exactly one lab row is inserted and the logging user cannot alter the table.
  • Save the project/code and record the environment version.
  • Repeat the test from a known initial state.
  • Capture the required runtime or output evidence.

C. If the Result Is Wrong

CheckAction
Environment and connectionConfirm version, driver, address, permissions and communication state.
Input, parameter or codeCompare the configured value with the lab sheet and official documentation.
Output/resultTrace the value step by step, correct the first deviation and retest safely.

D. Student Evidence Record

File

Project/code filename and revision.

Values

Inputs, settings and observed outputs.

Fault test

Fault introduced, symptom and correction.

Conclusion

Pass criteria and learner observation.

REAL LAB SCREENSHOT / OUTPUT EVIDENCE
Attach a verified capture from the completed lab.

Expected Result and Runtime Behavior

The database receives a typed, parameterized sample.

Lab 07 - Add Logging and Bounded Retries

Objective: Make protocol failures visible without retrying forever.

A. Step-by-Step Procedure

  1. Configure a named logger and consistent messages.
  2. Retry only transient operations.
  3. Use a maximum attempt count and increasing delay.
  4. Raise the final error for the supervisor/service to handle.
import logging, time
log = logging.getLogger("collector")
for attempt in range(1, 4):
    try:
        value = read_lab_tag()  # trainer-provided function
        log.info("read_ok value=%s", value)
        break
    except TimeoutError as exc:
        log.warning("attempt=%s error=%s", attempt, exc)
        if attempt == 3:
            raise
        time.sleep(attempt)

B. Verification Checklist

  • Two forced timeouts create warnings and the third successful read exits the loop.
  • Save the project/code and record the environment version.
  • Repeat the test from a known initial state.
  • Capture the required runtime or output evidence.

C. If the Result Is Wrong

CheckAction
Environment and connectionConfirm version, driver, address, permissions and communication state.
Input, parameter or codeCompare the configured value with the lab sheet and official documentation.
Output/resultTrace the value step by step, correct the first deviation and retest safely.

D. Student Evidence Record

File

Project/code filename and revision.

Values

Inputs, settings and observed outputs.

Fault test

Fault introduced, symptom and correction.

Conclusion

Pass criteria and learner observation.

REAL LAB SCREENSHOT / OUTPUT EVIDENCE
Attach a verified capture from the completed lab.

Expected Result and Runtime Behavior

Transient faults are logged and bounded; permanent faults are not hidden.

Lab 08 - Create a Shift Summary with pandas

Objective: Transform timestamped tag data into a reviewable shift result.

A. Step-by-Step Procedure

  1. Load the verified CSV with parsed UTC timestamps.
  2. Assign a documented shift code.
  3. Group by shift and tag.
  4. Export a new report file without overwriting the raw log.
import pandas as pd
df = pd.read_csv("tag_log.csv", names=["time","tag","value","quality"], parse_dates=["time"])
df = df[df["quality"].eq("GOOD")].copy()
df["shift"] = pd.cut(df["time"].dt.hour, bins=[-1,5,13,21,23], labels=["C","A","B","C"], ordered=False)
report = df.groupby(["shift","tag"], observed=True)["value"].agg(["count","mean","min","max"])
report.to_csv("shift_summary.csv")

B. Verification Checklist

  • A known input dataset produces the expected count/min/max for each shift.
  • Save the project/code and record the environment version.
  • Repeat the test from a known initial state.
  • Capture the required runtime or output evidence.

C. If the Result Is Wrong

CheckAction
Environment and connectionConfirm version, driver, address, permissions and communication state.
Input, parameter or codeCompare the configured value with the lab sheet and official documentation.
Output/resultTrace the value step by step, correct the first deviation and retest safely.

D. Student Evidence Record

File

Project/code filename and revision.

Values

Inputs, settings and observed outputs.

Fault test

Fault introduced, symptom and correction.

Conclusion

Pass criteria and learner observation.

REAL LAB SCREENSHOT / OUTPUT EVIDENCE
Attach a verified capture from the completed lab.

Expected Result and Runtime Behavior

The raw log remains unchanged and a separate summary is produced.

Lab 09 - Expose a Read-Only FastAPI Endpoint

Objective: Serve a validated status object for an internal lab dashboard.

A. Step-by-Step Procedure

  1. Create a read-only response model.
  2. Return a controlled sample or validated collector state.
  3. Run only on the training network.
  4. Test success and invalid-route responses.
from fastapi import FastAPI
app = FastAPI(title="Softwell Lab API")
@app.get("/status")
def status():
    return {"line":"Lab-01","state":"READY","quality":"GOOD"}
# Run in lab: uvicorn app:app --host 127.0.0.1 --port 8000

B. Verification Checklist

  • GET /status returns HTTP 200 and the documented JSON fields.
  • Save the project/code and record the environment version.
  • Repeat the test from a known initial state.
  • Capture the required runtime or output evidence.

C. If the Result Is Wrong

CheckAction
Environment and connectionConfirm version, driver, address, permissions and communication state.
Input, parameter or codeCompare the configured value with the lab sheet and official documentation.
Output/resultTrace the value step by step, correct the first deviation and retest safely.

D. Student Evidence Record

File

Project/code filename and revision.

Values

Inputs, settings and observed outputs.

Fault test

Fault introduced, symptom and correction.

Conclusion

Pass criteria and learner observation.

REAL LAB SCREENSHOT / OUTPUT EVIDENCE
Attach a verified capture from the completed lab.

Expected Result and Runtime Behavior

The lab dashboard can read a stable, read-only status endpoint.

Lab 10 - Test, Package and Handover the Collector

Objective: Create repeatable checks and an operator handover record.

A. Step-by-Step Procedure

  1. Write tests for scaling, validation and error paths.
  2. Run tests before packaging.
  3. Document configuration, credentials process and service restart.
  4. Archive code, requirements, test result and sample output.
def scale(raw, low=0.0, high=100.0):
    if not 0 <= raw <= 27648:
        raise ValueError("raw out of range")
    return low + (raw / 27648.0) * (high - low)

def test_scale_midpoint():
    assert round(scale(13824), 1) == 50.0

B. Verification Checklist

  • pytest passes the normal case and a separate test confirms invalid input raises ValueError.
  • Save the project/code and record the environment version.
  • Repeat the test from a known initial state.
  • Capture the required runtime or output evidence.

C. If the Result Is Wrong

CheckAction
Environment and connectionConfirm version, driver, address, permissions and communication state.
Input, parameter or codeCompare the configured value with the lab sheet and official documentation.
Output/resultTrace the value step by step, correct the first deviation and retest safely.

D. Student Evidence Record

File

Project/code filename and revision.

Values

Inputs, settings and observed outputs.

Fault test

Fault introduced, symptom and correction.

Conclusion

Pass criteria and learner observation.

REAL LAB SCREENSHOT / OUTPUT EVIDENCE
Attach a verified capture from the completed lab.

Expected Result and Runtime Behavior

The collector has code, dependency, test, configuration and handover evidence.

Before You Start: Prerequisites, Tested Version, Safety and Evidence

This manual is a practical training workbook, not a substitute for the installed product manual or the site's approved engineering procedure. Record the exact software, firmware, license and hardware before following a step because menus and supported functions can vary by release.

Tested-version planning scope: Confirm Python 3.11 or later in an isolated virtual environment with pinned, trainer-approved package versions. Enter the exact lab-tested software, firmware and hardware in the record below before course delivery; never assume cross-version compatibility.

Environment record

Software build, firmware, device catalog, driver, communication interface and license status.

Safe lab boundary

Use an isolated training system. Follow electrical, mechanical, process and cybersecurity controls before energizing or downloading.

Evidence pack

Keep the source project, parameter/code export, screenshot/trend, fault test, correction and final pass result.

Technical review

Last reviewed by Softwell Automation Technical Training Team on 17 July 2026.

FieldLearner recordVerification
Software / firmware________________Matches the training device and official compatibility information
Project / backup________________Saved before and after the practical
Pass evidence________________Runtime value, trend, alarm, diagnostic or report attached
Fault tested________________Symptom, cause, check and corrective action documented

Practice, Viva and Extension Challenge

Practice

Change one approved input or parameter, predict the result, execute the test and explain any difference.

Viva

Explain the data flow, safety boundary, first diagnostic check and recovery method without opening the answer.

Extension challenge

Add one useful function while preserving the original pass criteria, alarm behavior and rollback path.

Graded mini-project

Combine at least three practicals, submit a versioned project and evidence pack, and demonstrate repeatable recovery.

Python Industrial Automation four-stage practical lab, runtime verification, diagnosis and backup workflow
Instructional workflow diagram: complete configuration, measurable verification, controlled diagnosis and recovery evidence in sequence.
Python — official documentation

Content status: Substantively reviewed and expanded 17 July 2026. Verify release-specific details against the linked official documentation.

Enquire Now

For syllabus, manual PDF, corporate batch or online training details, contact Softwell Automation.

Course Contents / Curriculum

The curriculum follows a practical sequence from fundamentals to project integration.

Level 01Basic PLC, wiring, addressing and ladder logic.
Level 02Advanced PLC, networking, SCADA and diagnostics.
Level 03OPC UA, SQL, Python, reports and IT/OT integration.
Verified learning pathway

Practise This Manual with Guidance

Use the manual with trainer-led practicals, software exercises and troubleshooting support.

Content reviewed: 17 July 2026

☎ Call WhatsApp ✉ Email Enquire Now