Skip to content

Commit

Permalink
transition scripts to pyproject.toml file
Browse files Browse the repository at this point in the history
- drops some scripts for the moment
  • Loading branch information
drunsinn committed Oct 7, 2023
1 parent 79fddda commit 5f4a577
Show file tree
Hide file tree
Showing 15 changed files with 76 additions and 441 deletions.
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@
- npalmerDNX

## Usage
See [lsv2_demo.py](https://github.com/drunsinn/pyLSV2/blob/master/scripts/lsv2_demo.py) for a demonstration of some of the functions.
See [lsv2_demo.py](https://github.com/drunsinn/pyLSV2/blob/master/pyLSV2/demos/lsv2_demo.py) for a demonstration of some of the functions.

Since the whole protocol isn't documented there can always be problems with certain corner cases. Especially during file transfer a lot of stuff can go wrong.
In case the control doesn't accept a command it returns an error. Some of these errors are checked internally but not everything is covered as of now. It is therefore
Expand Down Expand Up @@ -107,7 +107,7 @@ These changes where made intentionally to make further development easier. See t
```
con.read_plc_memory(32, pyLSV2.MemoryType.MARKER, 15)
```
See [lsv2_demo.py](https://github.com/drunsinn/pyLSV2/blob/master/scripts/lsv2_demo.py) for more examples.
See [lsv2_demo.py](https://github.com/drunsinn/pyLSV2/blob/master/pyLSV2/demos/lsv2_demo.py) for more examples.

The available memory areas and their python data type
| Memory Type | Python Type |
Expand Down Expand Up @@ -135,7 +135,7 @@ These changes where made intentionally to make further development easier. See t
con.read_data_path('/TABLE/TOOL/T/1/DOC')
```

See [lsv2_demo.py](https://github.com/drunsinn/pyLSV2/blob/master/scripts/lsv2_demo.py) for more examples.
See [lsv2_demo.py](https://github.com/drunsinn/pyLSV2/blob/master/pyLSV2/demos/lsv2_demo.py) for more examples.

Note that reading values from memory does not take into account the actual size in the control memory. This leads to an offset between the values read with `read_data_path` and `read_plc_memory`. As a workaround you have to multiply the address value with the number of bytes the data type requires. The following example tries to show how this can be accomplished:

Expand All @@ -148,7 +148,7 @@ These changes where made intentionally to make further development easier. See t

### SSH Tunnel
Newer controls allow the use of ssh to encrypt the communication via LSV2.
See [ssh_tunnel_demo.py](https://github.com/drunsinn/pyLSV2/blob/master/scripts/ssh_tunnel_demo.py) for an example on
See [ssh_tunnel_demo.py](https://github.com/drunsinn/pyLSV2/blob/master/pyLSV2/demos/ssh_tunnel.py) for an example on
how to use the python library [sshtunnel](https://github.com/pahaz/sshtunnel) to achieve a secure connection.

## Compatibility
Expand Down Expand Up @@ -183,7 +183,7 @@ These changes where made intentionally to make further development easier. See t
# Tables
Included in this library is also functionality to work with Tables used by different NC Controls. This includes for example TNC controls as well as Anilam 6000i CNC. As these controls and there software versions use different table formats, it is also possible to dreive the format form an existing table and export the format to a json file.

See [tab2csv.py](https://github.com/drunsinn/pyLSV2/blob/master/scripts/tab2csv.py) for a demonstration on how to read a table and convert it to a csv file.
See [tab2csv.py](https://github.com/drunsinn/pyLSV2/blob/master/pyLSV2/demos/tab2csv.py) for a demonstration on how to read a table and convert it to a csv file.

This script can also be used as a command line tool
```
Expand Down
6 changes: 5 additions & 1 deletion pyLSV2/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -1663,7 +1663,11 @@ def read_data_path(self, path: str) -> Union[bool, int, float, str, None]:
self._logger.warning("the argument '%s' is not supported by this control", path)
return None

self._logger.warning("an error occurred while querying data path '%s'. Error code was %d", path, self.last_error.e_code)
self._logger.warning(
"an error occurred while querying data path '%s'. Error code was %d",
path,
self.last_error.e_code,
)
return None

def axes_location(self) -> Union[Dict[str, float], None]:
Expand Down
3 changes: 3 additions & 0 deletions pyLSV2/demos/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Collection of demo scripts for pyLSV2"""
17 changes: 10 additions & 7 deletions scripts/lsv2_demo.py → pyLSV2/demos/lsv2_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,14 @@
import pyLSV2
from pyLSV2.const import MemoryType

__author__ = "drunsinn"
__license__ = "MIT"
__version__ = "1.0"
__email__ = "dr.unsinn@googlemail.com"

if __name__ == "__main__":
def comprehensive_demo():
"""Basic demo for pyLSV2"""
parser = argparse.ArgumentParser()

parser.add_argument("address", nargs="?", default="192.168.56.101", type=str)
# parser.add_argument("address", nargs="?", default="192.168.56.101", type=str)

parser.add_argument("address", help="ip or hostname of control", type=str)

parser.add_argument(
"-d",
Expand Down Expand Up @@ -121,7 +120,7 @@
lang = con.get_machine_parameter("CfgDisplayLanguage.ncLanguage")
print("# Value of machine parameter for NC language: {:s}".format(lang))

if con.version.is_tnc7():
if con.versions.is_tnc7():
print("UI Interface test not available on TNC7?")
else:
print("UI Interface")
Expand Down Expand Up @@ -167,3 +166,7 @@
print("# current tool in spindle: {:d}.{:d} '{:s}'".format(t_info.number, t_info.index, t_info.name))
else:
print("# direct reading of current tool not supported for this control")


if __name__ == "__main__":
comprehensive_demo()
26 changes: 20 additions & 6 deletions scripts/scope2csv.py → pyLSV2/demos/scope2csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import sys
import logging
import argparse
import csv
from csv import writer as csv_writer
from pathlib import Path

import pyLSV2
Expand All @@ -17,7 +17,7 @@
__email__ = "dr.unsinn@googlemail.com"


if __name__ == "__main__":
def main():
parser = argparse.ArgumentParser(
prog="real_time_readings",
description="script to read scope signals from control",
Expand All @@ -37,7 +37,13 @@

parser.add_argument("-a", "--duration", help="number of seconds to record", type=int, default=10)

parser.add_argument("-i", "--interval", help="number of µs between readings", type=int, default=6000)
parser.add_argument(
"-i",
"--interval",
help="number of µs between readings",
type=int,
default=21000,
)

parser.add_argument(
"-d",
Expand Down Expand Up @@ -122,17 +128,21 @@
scope_signals.append(new_signal)

with open(args.output, "w", encoding="utf8") as csv_fp:
csv = csv.writer(csv_fp, dialect="excel", lineterminator="\n")
csv = csv_writer(csv_fp, dialect="excel", lineterminator="\n")
csv.writerow(list(map(lambda x: x.normalized_name(), scope_signals)))
readings_counter = 0

for package in con.real_time_readings(scope_signals, args.duration, args.interval):
signal_readings = package.get_data()
readings_per_signal = len(signal_readings[0].data)
logging.debug("successfulle read %d signals with %d values each" % (len(signal_readings), readings_per_signal))
logging.debug(
"successfulle read %d signals with %d values each",
len(signal_readings),
readings_per_signal,
)

for i in range(readings_per_signal):
row = list()
row = []
for signal in signal_readings:
value = (signal.data[i] * signal.factor) + signal.offset
row.append(value)
Expand All @@ -150,3 +160,7 @@
)

sys.exit(0)


if __name__ == "__main__":
main()
14 changes: 7 additions & 7 deletions scripts/ssh_tunnel_demo.py → pyLSV2/demos/ssh_tunnel.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,13 @@
6. edit this file and set address, user name and path to the key file
"""
import logging
import pyLSV2
from sshtunnel import SSHTunnelForwarder

__author__ = "drunsinn"
__license__ = "MIT"
__version__ = "1.0"
__email__ = "dr.unsinn@googlemail.com"
import pyLSV2

logging.basicConfig(level=logging.INFO)

if __name__ == "__main__":

def main():
address = "192.168.56.101"
user_name = "user"
private_key_file = "<path to private key file>"
Expand All @@ -46,3 +42,7 @@

print("Close SSH tunnel")
ssh_forwarder.stop()


if __name__ == "__main__":
main()
11 changes: 6 additions & 5 deletions scripts/tab2csv.py → pyLSV2/demos/tab2csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,9 @@

from pyLSV2 import NCTable

__author__ = "drunsinn"
__license__ = "MIT"
__version__ = "1.0"
__email__ = "dr.unsinn@googlemail.com"

if __name__ == "__main__":
def main():
"""console application to convert a tnc table file to a csv file"""
parser = argparse.ArgumentParser(description="command line script parsing table files")
parser.add_argument("source", help="table file to parse", type=pathlib.Path)
parser.add_argument("--decimal_char", help="override local decimal char", type=str, default=",")
Expand Down Expand Up @@ -63,3 +60,7 @@
sys.exit(-1)

sys.exit(0)


if __name__ == "__main__":
main()
5 changes: 2 additions & 3 deletions pyLSV2/misc_scope.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
# -*- coding: utf-8 -*-
"""misc helper functions for the scope part of pyLSV2"""
import struct
from datetime import datetime
from typing import List
import logging

Expand Down Expand Up @@ -32,7 +31,7 @@ def decode_signal_description(data_set: bytearray) -> List[ld.ScopeSignal]:
# data_set[ 46: ??] : name of the channel
# type 1, 2, 4, 5:
# data_set[ 59: ] : signal names
signals = list()
signals = []
channel_number = struct.unpack("!H", data_set[0:2])[0]
name_start = 46
name_end = 46
Expand Down Expand Up @@ -121,7 +120,7 @@ def split_dataset(data):
logger.debug("R_OP dataset has expected length")
for i, data_sub_set in enumerate(split_dataset(data_set)):
if data_sub_set[17:] != bytearray(b"?\x00\x00\x00\x00"):
raise Exception("unexpected data in signal details at position 17 %s" % data_sub_set[17:])
raise LSV2DataException("unexpected data in signal details at position 17 %s" % data_sub_set[17:])

signal_list[i].unit = lm.ba_to_ustr(data_sub_set[0:10])
signal_list[i].factor = struct.unpack("<d", data_sub_set[10:18])[0]
Expand Down
18 changes: 9 additions & 9 deletions pyLSV2/table_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ def get_column_empty_value(self, name: str):
def set_column_empty_value(self, name, value):
"""set the default value of a column"""
if len(str(value)) > self._column_format[name]["width"]:
raise Exception("value to long for column")
raise ValueError("value to long for column")
self._column_format[name]["empty_value"] = value

def update_column_format(self, name: str, parameters: dict):
Expand Down Expand Up @@ -204,7 +204,7 @@ def dump_native(self, file_path: pathlib.Path, renumber_column=None):

for column_name in self._columns:
if column_name not in self._column_format:
raise Exception("configuration is incomplete, missing definition for column {column_name:s}")
raise ValueError("configuration is incomplete, missing definition for column {column_name:s}")
fixed_width = self._column_format[column_name]["width"]
format_string = "{0:<%d}" % fixed_width
tfp.write(format_string.format(column_name))
Expand All @@ -228,7 +228,7 @@ def dump_native(self, file_path: pathlib.Path, renumber_column=None):
)
tfp.write(format_string.format(self._column_format[column_name]["empty_value"]))
else:
raise Exception("entry is missing a value for column %s defined in the output format" % column_name)
raise ValueError("entry is missing a value for column %s defined in the output format" % column_name)
tfp.write("\n")
row_counter += 1

Expand Down Expand Up @@ -308,7 +308,7 @@ def parse_table(table_path: pathlib.Path) -> "NCTable":
)

if header is None:
raise Exception("File has wrong format: incorrect header for file %s" % table_path)
raise ValueError("File has wrong format: incorrect header for file %s" % table_path)

nctable.name = header.group("name").strip()
nctable.suffix = header.group("suffix")
Expand Down Expand Up @@ -396,9 +396,9 @@ def parse_table(table_path: pathlib.Path) -> "NCTable":
for c_d in table_config["TableDescription"]["columns"]:
cfg_column_name = c_d["CfgColumnDescription"]["key"]
if cfg_column_name not in nctable.column_names:
raise Exception("found unexpected column %s" % cfg_column_name)
raise ValueError("found unexpected column %s" % cfg_column_name)
if c_d["CfgColumnDescription"]["width"] != nctable.get_column_width(cfg_column_name):
raise Exception(
raise ValueError(
"found difference in column width for colmun %s: %d : %d"
% (
cfg_column_name,
Expand Down Expand Up @@ -447,7 +447,7 @@ def str_to_typed_value(value_string: str):
last_object.append({name: new_category})
else:
if name in last_object:
raise Exception("Element already in dict")
raise ValueError("Element already in dict")
last_object[name] = new_category
object_list.append(new_category)

Expand All @@ -459,7 +459,7 @@ def str_to_typed_value(value_string: str):
last_object.append({name: new_group})
else:
if name in last_object:
raise Exception("Element already in dict")
raise ValueError("Element already in dict")
last_object[name] = new_group
object_list.append(new_group)

Expand All @@ -479,7 +479,7 @@ def str_to_typed_value(value_string: str):
parts = line.split(":=")
last_object[parts[0]] = str_to_typed_value(parts[1])
else:
raise Exception("no keyname??")
raise ValueError("no keyname??")
# last_object["value_%d" % id_counter] = line

return config_data
Expand Down
11 changes: 9 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,15 @@ requires-python = ">=3.6"
keywords = ["LSV2", "CNC", "PLC"]
dynamic = ["version", "readme", ]

#[project.scripts]
#lsv2_demo = "scripts.lsv2_demo"
[project.urls]
"Homepage" = "https://github.com/drunsinn/pyLSV2"
"Bug Tracker" = "https://github.com/drunsinn/pyLSV2/issues"

[project.scripts]
lsv2_demo = "pyLSV2.demos.lsv2_demo:comprehensive_demo"
lsv2_scope2csv = "pyLSV2.demos.scope2csv:main"
lsv2_tab2csv = "pyLSV2.demos.tab2csv:main"
lsv2_tunnel_demo = "pyLSV2.demos.ssh_tunnel:main"

[tool.setuptools]
packages = [
Expand Down
Empty file removed scripts/__init__.py
Empty file.
Loading

0 comments on commit 5f4a577

Please sign in to comment.