matterlab-serial-device 0.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2023 aspuru-guzik-group / Self-Driving Lab / Devices
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,27 @@
1
+ Metadata-Version: 2.4
2
+ Name: matterlab_serial_device
3
+ Version: 0.0.0
4
+ Summary: A wrapper for PySerial device interfaces.
5
+ Author: Han Hao, Martin Seifrid
6
+ License: Apache 2.0
7
+ Platform: win
8
+ Platform: osx
9
+ Platform: unix
10
+ Platform: linux
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3 :: Only
13
+ Classifier: Programming Language :: Python :: 3.6
14
+ Classifier: Programming Language :: Python :: 3.7
15
+ Classifier: Programming Language :: Python :: 3.8
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Requires-Python: >=3.7
19
+ License-File: LICENSE
20
+ Requires-Dist: pyserial
21
+ Provides-Extra: testing
22
+ Requires-Dist: flake8>=4; extra == "testing"
23
+ Requires-Dist: mypy>=0; extra == "testing"
24
+ Requires-Dist: pytest>=7; extra == "testing"
25
+ Requires-Dist: pytest-cov>=3; extra == "testing"
26
+ Requires-Dist: tox>=3; extra == "testing"
27
+ Dynamic: license-file
@@ -0,0 +1,92 @@
1
+ # Serial Device Interface
2
+
3
+
4
+
5
+ ## Getting started
6
+
7
+ To make it easy for you to get started with GitLab, here's a list of recommended next steps.
8
+
9
+ Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
10
+
11
+ ## Add your files
12
+
13
+ - [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
14
+ - [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
15
+
16
+ ```
17
+ cd existing_repo
18
+ git remote add origin https://gitlab.com/aspuru-guzik-group/self-driving-lab/devices/serial-device-interface.git
19
+ git branch -M main
20
+ git push -uf origin main
21
+ ```
22
+
23
+ ## Integrate with your tools
24
+
25
+ - [ ] [Set up project integrations](https://gitlab.com/aspuru-guzik-group/self-driving-lab/devices/serial-device-interface/-/settings/integrations)
26
+
27
+ ## Collaborate with your team
28
+
29
+ - [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
30
+ - [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
31
+ - [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
32
+ - [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
33
+ - [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
34
+
35
+ ## Test and Deploy
36
+
37
+ Use the built-in continuous integration in GitLab.
38
+
39
+ - [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
40
+ - [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
41
+ - [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
42
+ - [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
43
+ - [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
44
+
45
+ ***
46
+
47
+ # Editing this README
48
+
49
+ When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
50
+
51
+ ## Suggestions for a good README
52
+ Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
53
+
54
+ ## Name
55
+ Choose a self-explaining name for your project.
56
+
57
+ ## Description
58
+ Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
59
+
60
+ ## Badges
61
+ On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
62
+
63
+ ## Visuals
64
+ Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
65
+
66
+ ## Installation
67
+ Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
68
+
69
+ ## Usage
70
+ Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
71
+
72
+ ## Support
73
+ Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
74
+
75
+ ## Roadmap
76
+ If you have ideas for releases in the future, it is a good idea to list them in the README.
77
+
78
+ ## Contributing
79
+ State if you are open to contributions and what your requirements are for accepting them.
80
+
81
+ For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
82
+
83
+ You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
84
+
85
+ ## Authors and acknowledgment
86
+ Show your appreciation to those who have contributed to the project.
87
+
88
+ ## License
89
+ For open source projects, say how it is licensed.
90
+
91
+ ## Project status
92
+ If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
@@ -0,0 +1,44 @@
1
+ [metadata]
2
+ name = matterlab_serial_device
3
+ version = 0.0.0
4
+ description = A wrapper for PySerial device interfaces.
5
+ author = Han Hao, Martin Seifrid
6
+ license = Apache 2.0
7
+ license_file = LICENSE
8
+ platforms = win, osx, unix, linux
9
+ classifiers =
10
+ Programming Language :: Python :: 3
11
+ Programming Language :: Python :: 3 :: Only
12
+ Programming Language :: Python :: 3.6
13
+ Programming Language :: Python :: 3.7
14
+ Programming Language :: Python :: 3.8
15
+ Programming Language :: Python :: 3.9
16
+ Programming Language :: Python :: 3.10
17
+
18
+ [options]
19
+ packages =
20
+ matterlab_serial_device
21
+ install_requires =
22
+ pyserial
23
+ python_requires = >=3.7
24
+ package_dir =
25
+ =src
26
+
27
+ [options.extras_require]
28
+ testing =
29
+ flake8>=4
30
+ mypy>=0
31
+ pytest>=7
32
+ pytest-cov>=3
33
+ tox>=3
34
+
35
+ [options.package_data]
36
+ matterlab_serial_device = py.typed
37
+
38
+ [flake8]
39
+ max-line-length = 160
40
+
41
+ [egg_info]
42
+ tag_build =
43
+ tag_date = 0
44
+
@@ -0,0 +1,4 @@
1
+ from setuptools import setup
2
+
3
+ if __name__ == "__main__":
4
+ setup()
@@ -0,0 +1,3 @@
1
+ from .serial_device import SerialDevice, SerialDeviceSettings, open_close
2
+
3
+ __all__ = ["SerialDevice", "SerialDeviceSettings", "open_close"]
@@ -0,0 +1,236 @@
1
+ import json
2
+ import time
3
+ from pathlib import Path
4
+ from typing import Dict, Optional, Tuple, Union
5
+ from logging import Logger, getLogger
6
+
7
+ import serial
8
+ from serial import Serial
9
+
10
+ SERIAL_PARITY: Dict = {"none": serial.PARITY_NONE,
11
+ "odd": serial.PARITY_ODD,
12
+ "even": serial.PARITY_EVEN,
13
+ "mark": serial.PARITY_MARK,
14
+ "space": serial.PARITY_SPACE
15
+ }
16
+
17
+ SERIAL_BYTESIZE: Dict = {5: serial.FIVEBITS,
18
+ 6: serial.SIXBITS,
19
+ 7: serial.SEVENBITS,
20
+ 8: serial.EIGHTBITS
21
+ }
22
+
23
+ SERIAL_STOPBITS: Dict = {1: serial.STOPBITS_ONE,
24
+ 1.5: serial.STOPBITS_ONE_POINT_FIVE,
25
+ 2: serial.STOPBITS_TWO
26
+ }
27
+
28
+ SERIAL_FACTORY: Dict = {"parity": SERIAL_PARITY,
29
+ "bytesize": SERIAL_BYTESIZE,
30
+ "stopbits": SERIAL_STOPBITS
31
+ }
32
+
33
+
34
+ def open_close(func):
35
+ """
36
+ decorator
37
+ close communication first in case it is open (otherwise will raise error port is already open)
38
+ open communication before sending/receiving commands
39
+ then close in case of failure of communication
40
+ :param func:
41
+ :return:
42
+ """
43
+
44
+ def wrapper(self, *args, **kwargs):
45
+ self.close_device_comm() # This is done to avoid opening a port that is already open
46
+ self.open_device_comm()
47
+ func_return = func(self, *args, **kwargs)
48
+ self.close_device_comm()
49
+ return func_return
50
+
51
+ return wrapper
52
+
53
+
54
+ class SerialDeviceSettings:
55
+ special_keys: Tuple = ("parity", "bytesize", "stopbits",)
56
+
57
+ def __init__(self, default_settings: Path, **kwargs) -> None:
58
+ """
59
+ read settings of SerialDevice
60
+ :param default_settings: path of default settings of this device
61
+ :param kwargs: device-specific setting, e.g. com_port, address
62
+ """
63
+ with default_settings.open("r") as f:
64
+ self._defaults: Dict = json.load(f)
65
+
66
+ settings = {**kwargs}
67
+
68
+ if "com_port" not in settings:
69
+ settings: Dict = self._get_com_port(settings)
70
+
71
+ if ("RS485" in settings) and (settings["RS485"] is True) and ("address" not in settings):
72
+ settings: Dict = self._get_address(settings)
73
+
74
+ self._set_attrs({**self._defaults, **settings})
75
+
76
+ def _set_attrs(self, attributes: Dict) -> None:
77
+ """
78
+ read settings of the device
79
+ :param attributes:
80
+ :return:
81
+ """
82
+ for key, value in attributes.items():
83
+ self.__setattr__(key, value)
84
+
85
+ for sp_key in self.special_keys:
86
+ if sp_key in attributes:
87
+ if attributes[sp_key] not in SERIAL_FACTORY[sp_key]:
88
+ raise ValueError(f"Invalid value for {sp_key}: {attributes[sp_key]}")
89
+ else:
90
+ self.__setattr__(sp_key, SERIAL_FACTORY[sp_key][attributes[sp_key]])
91
+
92
+ @staticmethod
93
+ def _get_com_port(settings: Dict) -> Dict:
94
+ """
95
+ manual input of the COM port of the device
96
+ other settings use default
97
+ :return:
98
+ """
99
+ settings["com_port"]: str = input('Enter the appropriate communications port\
100
+ (e.g., COM1 for windows, or /dev/ttyS0 or /dev/ttySUSB0 for Linux):\n')
101
+ return settings
102
+
103
+ @staticmethod
104
+ def _get_address(settings: Dict) -> Dict:
105
+ """
106
+ manual input of the RS485 port of the device
107
+ other settings use default
108
+ :param settings:
109
+ :return:
110
+ """
111
+ address: str = input('Enter the appropriate RS485 address:\n')
112
+ if not address.isdigit():
113
+ raise TypeError("Address must be an integer.")
114
+ if int(address) <= 0 or int(address) > 255:
115
+ raise ValueError("Address must be between 1 and 255.")
116
+
117
+ settings["address"]: int = int(address)
118
+ return settings
119
+
120
+
121
+ class SerialDevice:
122
+ default_eol: bytes = b"\r\n"
123
+
124
+ def __init__(
125
+ self,
126
+ default_settings: Path,
127
+ settings: Dict = None,
128
+ logger: Optional[Logger] = None,
129
+ ) -> None:
130
+ self.settings: SerialDeviceSettings = SerialDeviceSettings(default_settings, settings)
131
+ self._init_device()
132
+ self.logger = logger if logger is not None else getLogger()
133
+ self.logger.debug(f"Created SerialDevice with settings: {self.settings.__dict__}")
134
+
135
+ def _init_device(self):
136
+ """
137
+ add a device according to the device_setting
138
+ :return: None
139
+ """
140
+ self.device = Serial(port=self.settings.com_port,
141
+ baudrate=self.settings.baudrate,
142
+ parity=self.settings.parity,
143
+ bytesize=self.settings.bytesize,
144
+ timeout=self.settings.timeout,
145
+ stopbits=self.settings.stopbits,
146
+ )
147
+ self.close_device_comm()
148
+
149
+ def open_device_comm(self):
150
+ """
151
+ close communication with the device to free the port
152
+ open communication with the device
153
+ DO NOT start the device electronically!
154
+ :return:
155
+ """
156
+ self.device.close()
157
+ self.device.open()
158
+
159
+ def close_device_comm(self):
160
+ """
161
+ close communication with the device
162
+ DO NOT shut down the device electronically!
163
+ :return:
164
+ """
165
+ self.device.close()
166
+
167
+ @staticmethod
168
+ def _encode(command: Union[str, bytes, bytearray]) -> bytes:
169
+ """
170
+ encode the command to bytes
171
+ :param command:
172
+ :return bytes:
173
+ """
174
+ if isinstance(command, str):
175
+ command: bytes = command.encode()
176
+ elif isinstance(command, bytearray):
177
+ command: bytes = bytes(command)
178
+ elif isinstance(command, bytes):
179
+ pass
180
+ else:
181
+ raise TypeError("'command' type must be either str, bytes, or bytearray.")
182
+ return command
183
+
184
+ def write(self, command: Union[str, bytes, bytearray]) -> None:
185
+ """
186
+ write the command in bytes to the device
187
+ :param command: command to write
188
+ :return:
189
+ """
190
+ command_bytes: bytes = self._encode(command)
191
+ self.device.write(command_bytes)
192
+
193
+ def read(self, return_bytes: bool = False, **kwargs) -> Union[str, bytes]:
194
+ """
195
+ read the response from the device until EOL (b'\r\n')
196
+ :return: decoded string, not including the EOL
197
+ """
198
+ response: bytes = self.read_bytes(**kwargs)
199
+ if return_bytes:
200
+ return response
201
+ else:
202
+ return response.decode(self.settings.encoding)
203
+
204
+ def read_bytes(self,
205
+ read_until: Optional[Union[str, bytes]] = None,
206
+ num_bytes: int = None,
207
+ remove_from_start: int = 0,
208
+ remove_from_end: Optional[int] = None
209
+ ) -> bytes:
210
+ """
211
+ read the response from the device until EOL (b'\r\n')
212
+ num_bytes: max number of bytes
213
+ :return: decoded string, not including the EOL
214
+ """
215
+ read_until: Union[str, bytes] = read_until if read_until else self.default_eol
216
+ command_bytes: bytes = self._encode(read_until)
217
+ full_response: bytes = self.device.read_until(expected=command_bytes, size=num_bytes)
218
+ if not remove_from_end:
219
+ return full_response[remove_from_start:]
220
+ else:
221
+ return full_response[remove_from_start:-remove_from_end]
222
+
223
+ def query(self,
224
+ write_command: Union[str, bytes, bytearray],
225
+ read_delay: float = 0.5,
226
+ **kwargs
227
+ ) -> str:
228
+ """
229
+ Send command to the device, wait for read_delay seconds, then read the response.
230
+ :param write_command:
231
+ :param read_delay:
232
+ :return:
233
+ """
234
+ self.write(write_command)
235
+ time.sleep(read_delay)
236
+ return self.read(**kwargs)
@@ -0,0 +1,27 @@
1
+ Metadata-Version: 2.4
2
+ Name: matterlab_serial_device
3
+ Version: 0.0.0
4
+ Summary: A wrapper for PySerial device interfaces.
5
+ Author: Han Hao, Martin Seifrid
6
+ License: Apache 2.0
7
+ Platform: win
8
+ Platform: osx
9
+ Platform: unix
10
+ Platform: linux
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3 :: Only
13
+ Classifier: Programming Language :: Python :: 3.6
14
+ Classifier: Programming Language :: Python :: 3.7
15
+ Classifier: Programming Language :: Python :: 3.8
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Requires-Python: >=3.7
19
+ License-File: LICENSE
20
+ Requires-Dist: pyserial
21
+ Provides-Extra: testing
22
+ Requires-Dist: flake8>=4; extra == "testing"
23
+ Requires-Dist: mypy>=0; extra == "testing"
24
+ Requires-Dist: pytest>=7; extra == "testing"
25
+ Requires-Dist: pytest-cov>=3; extra == "testing"
26
+ Requires-Dist: tox>=3; extra == "testing"
27
+ Dynamic: license-file
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ README.md
3
+ setup.cfg
4
+ setup.py
5
+ src/matterlab_serial_device/__init__.py
6
+ src/matterlab_serial_device/serial_device.py
7
+ src/matterlab_serial_device.egg-info/PKG-INFO
8
+ src/matterlab_serial_device.egg-info/SOURCES.txt
9
+ src/matterlab_serial_device.egg-info/dependency_links.txt
10
+ src/matterlab_serial_device.egg-info/requires.txt
11
+ src/matterlab_serial_device.egg-info/top_level.txt
12
+ tests/test_serial_device.py
13
+ tests/test_serial_device_settings.py
@@ -0,0 +1,8 @@
1
+ pyserial
2
+
3
+ [testing]
4
+ flake8>=4
5
+ mypy>=0
6
+ pytest>=7
7
+ pytest-cov>=3
8
+ tox>=3
@@ -0,0 +1,88 @@
1
+ import pytest
2
+ from pathlib import Path
3
+
4
+ from matterlab_serial_device import SerialDevice
5
+
6
+ defaults_path = Path(__file__).parent.parent / "data" / "default_settings.json"
7
+
8
+
9
+ @pytest.fixture
10
+ def serial_device(mocker):
11
+ # Create a SerialDevice instance for testing
12
+ settings = {"com_port": "COM1"}
13
+ mocker.patch("serial.Serial")
14
+ return SerialDevice(defaults_path, settings)
15
+
16
+
17
+ def test_init_device(serial_device, mocker):
18
+ mock_serial = mocker.patch("serial.Serial")
19
+ device = serial_device()
20
+ mock_serial.assert_called_once_with(
21
+ port=serial_device.settings.com_port,
22
+ baudrate=serial_device.settings.baudrate,
23
+ parity=serial_device.settings.parity,
24
+ bytesize=serial_device.settings.bytesize,
25
+ timeout=serial_device.settings.timeout,
26
+ stopbits=serial_device.settings.stopbits,
27
+ )
28
+ mock_serial.return_value.close_device_comm.assert_called_once()
29
+
30
+
31
+ def test_open_and_close_device_comm(serial_device, mocker):
32
+ mock_serial = mocker.patch("serial.Serial")
33
+ serial_device.open_device_comm()
34
+ mock_serial.return_value.close.assert_called_once()
35
+ mock_serial.return_value.open.assert_called_once()
36
+
37
+ serial_device.close_device_comm()
38
+ mock_serial.return_value.close.assert_called_once()
39
+
40
+
41
+ def test_encode(serial_device):
42
+ command_str = "test"
43
+ command_bytes = b"test"
44
+ result_str = serial_device._encode(command_str)
45
+ result_bytes = serial_device._encode(command_bytes)
46
+
47
+ assert result_str == command_bytes
48
+ assert result_bytes == command_bytes
49
+
50
+
51
+ def test_write(serial_device, mocker):
52
+ command = "test command"
53
+ command_bytes = b"test command"
54
+ mock_write = mocker.patch.object(serial_device.device, "write")
55
+ serial_device.write(command)
56
+
57
+ mock_write.assert_called_once_with(command_bytes)
58
+
59
+
60
+ def test_read(serial_device, mocker):
61
+ response_bytes = b"test response"
62
+ mock_read_bytes = mocker.patch.object(serial_device, "read_bytes", return_value=response_bytes)
63
+ result = serial_device.read()
64
+
65
+ assert result == response_bytes.decode(serial_device.settings.encoding)
66
+ mock_read_bytes.assert_called_once_with()
67
+
68
+
69
+ def test_read_bytes(serial_device, mocker):
70
+ response_bytes = b"test response"
71
+ mock_read_until = mocker.patch.object(serial_device.device, "read_until", return_value=response_bytes)
72
+ result = serial_device.read_bytes()
73
+
74
+ assert result == response_bytes
75
+ mock_read_until.assert_called_once_with(expected=serial_device.default_eol, size=None)
76
+
77
+
78
+ def test_query(serial_device, mocker):
79
+ write_command = "test command"
80
+ read_delay = 0.5
81
+ response = "test response"
82
+ mock_write = mocker.patch.object(serial_device, "write")
83
+ mock_read = mocker.patch.object(serial_device, "read", return_value=response)
84
+ result = serial_device.query(write_command, read_delay)
85
+
86
+ assert result == response
87
+ mock_write.assert_called_once_with(write_command)
88
+ mock_read.assert_called_once_with()
@@ -0,0 +1,34 @@
1
+ import serial
2
+ import pytest
3
+
4
+ from pathlib import Path
5
+
6
+ from matterlab_serial_device import SerialDeviceSettings
7
+
8
+ defaults_path = Path(__file__).parent.parent / "data" / "default_settings.json"
9
+
10
+
11
+ def test_device_settings_init():
12
+ settings = SerialDeviceSettings(defaults_path, {"com_port": "COM1"})
13
+ assert settings.com_port == "COM1"
14
+ assert settings.baudrate == 19200
15
+ assert settings.parity == serial.PARITY_ODD
16
+ assert settings.bytesize == 7
17
+ assert settings.timeout == 1
18
+
19
+
20
+ def test_get_com_port(monkeypatch):
21
+ monkeypatch.setattr("builtins.input", lambda _: "COM123")
22
+ settings = SerialDeviceSettings(defaults_path)
23
+ assert settings.com_port == "COM123"
24
+
25
+
26
+ def test_get_rs485_address(monkeypatch):
27
+ monkeypatch.setattr("builtins.input", lambda _: "123")
28
+ settings = SerialDeviceSettings(defaults_path, {"com_port": "COM1", "RS485": True})
29
+ assert settings.address == 123
30
+
31
+ for address, error in zip(["one", "0", "256"], [TypeError, ValueError, ValueError]):
32
+ with pytest.raises(error):
33
+ monkeypatch.setattr("builtins.input", lambda _: address)
34
+ settings = SerialDeviceSettings(defaults_path, {"com_port": "COM1", "RS485": True})