Compare commits

...

23 Commits
main ... main

Author SHA1 Message Date
MarieMih
0626f26fea upgrade_both_HW3_HW4 2023-11-20 16:17:49 +03:00
MarieMih
2a3032d4e7 HW3_upgrade 2023-11-19 19:46:40 +03:00
MarieMih
1fbdae751c HW4_second_com 2023-11-16 23:56:44 +03:00
MarieMih
7ec82f80d1 HW4_first_com 2023-11-15 23:29:16 +03:00
39a3e8913f Merge pull request 'HW4' (#3) from Advanced_Python/advanced-python-homework-2023:main into main
Reviewed-on: marmi/advanced-python-homework-2023-marmi#3
2023-11-13 21:43:08 +03:00
MarieMih
74f2be739d Trial_hw3 2023-11-13 21:25:16 +03:00
MarieMih
8200022240 commit_new 2023-10-26 19:34:03 +03:00
MarieMih
3784fc13f6 Merge branch 'Advanced_Python-main' 2023-10-26 19:01:54 +03:00
MarieMih
e11169ae7f Merge branch 'main' of https://git.sciprog.center/Advanced_Python/advanced-python-homework-2023 into Advanced_Python-main 2023-10-26 19:00:03 +03:00
f58e5e5e81 Обновить README.md 2023-09-28 23:15:47 +03:00
MarieMih
1d605fe1af Merge branch 'main' of https://git.sciprog.center/marmi/advanced-python-homework-2023-marmi 2023-09-28 23:11:30 +03:00
MarieMih
8b7b5c9816 second 2023-09-28 23:04:58 +03:00
3794431fd3 Обновить README.md 2023-09-27 22:45:02 +03:00
4208f5eb79 Обновить controls/__init__.py 2023-09-27 22:33:44 +03:00
a58cc1b5c0 Обновить .gitignore 2023-09-27 22:22:34 +03:00
44072438eb Обновить README.md 2023-09-27 22:21:07 +03:00
d06748f486 Обновить README.md 2023-09-27 22:20:22 +03:00
5168d4e2e5 Обновить README.md 2023-09-27 22:19:50 +03:00
e136533b57 Обновить setup.py 2023-09-27 22:16:01 +03:00
03cbb257e3 Обновить LICENSE 2023-09-27 21:47:52 +03:00
766680a8dc Добавить environment.yml 2023-09-27 21:47:01 +03:00
30007ff93f Загрузить файлы в «/» 2023-09-27 21:25:06 +03:00
MarieMih
5430d0503f first 2023-09-27 19:58:08 +03:00
14 changed files with 573 additions and 13 deletions

4
.gitignore vendored
View File

@ -3,6 +3,9 @@ __pycache__/
*.py[cod] *.py[cod]
*$py.class *$py.class
#visual studio
.vs/
# C extensions # C extensions
*.so *.so
@ -127,6 +130,7 @@ venv/
ENV/ ENV/
env.bak/ env.bak/
venv.bak/ venv.bak/
scada-marmi/
# Spyder project settings # Spyder project settings
.spyderproject .spyderproject

251
LICENSE Normal file
View File

@ -0,0 +1,251 @@
?<html>
<head>
<title>The Code Project Open License (CPOL)</title>
<Style>
BODY, P, TD { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10pt }
H1,H2,H3,H4,H5 { color: #ff9900; font-weight: bold; }
H1 { font-size: 14pt;color:black }
H2 { font-size: 13pt; }
H3 { font-size: 12pt; }
H4 { font-size: 10pt; color: black; }
PRE { BACKGROUND-COLOR: #FBEDBB; FONT-FAMILY: "Courier New", Courier, mono; WHITE-SPACE: pre; }
CODE { COLOR: #990000; FONT-FAMILY: "Courier New", Courier, mono; }
.SpacedList li { padding: 5px 0px 5px 0px;}
</style>
</head>
<body bgcolor="#FFFFFF" color=#000000>
<h1>The Code Project Open License (CPOL) 1.02</h1>
<br />
<center>
<div style="text-align: left; border: 2px solid #000000; width: 660; background-color: #FFFFD9; padding: 20px;">
<h2>Preamble</h2>
<p>
This License governs Your use of the Work. This License is intended to allow developers
to use the Source Code and Executable Files provided as part of the Work in any
application in any form.
</p>
<p>
The main points subject to the terms of the License are:</p>
<ul>
<li>Source Code and Executable Files can be used in commercial applications;</li>
<li>Source Code and Executable Files can be redistributed; and</li>
<li>Source Code can be modified to create derivative works.</li>
<li>No claim of suitability, guarantee, or any warranty whatsoever is provided. The software is
provided "as-is".</li>
<li>The Article accompanying the Work may not be distributed or republished without the
Author's consent</li>
</ul>
<p>
This License is entered between You, the individual or other entity reading or otherwise
making use of the Work licensed pursuant to this License and the individual or other
entity which offers the Work under the terms of this License ("Author").</p>
<h2>License</h2>
<p>
THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CODE PROJECT OPEN
LICENSE ("LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE
LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT
LAW IS PROHIBITED.</p>
<p>
BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HEREIN, YOU ACCEPT AND AGREE TO BE
BOUND BY THE TERMS OF THIS LICENSE. THE AUTHOR GRANTS YOU THE RIGHTS CONTAINED HEREIN
IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS. IF YOU DO NOT
AGREE TO ACCEPT AND BE BOUND BY THE TERMS OF THIS LICENSE, YOU CANNOT MAKE ANY
USE OF THE WORK.</p>
<ol class="SpacedList">
<li><strong>Definitions.</strong>
<ol class="SpacedList" style="list-style-type: lower-alpha;">
<li><strong>"Articles"</strong> means, collectively, all articles written by Author
which describes how the Source Code and Executable Files for the Work may be used
by a user.</li>
<li><b>"Author"</b> means the individual or entity that offers the Work under the terms
of this License.<strong></strong></li>
<li><strong>"Derivative Work"</strong> means a work based upon the Work or upon the
Work and other pre-existing works.</li>
<li><b>"Executable Files"</b> refer to the executables, binary files, configuration
and any required data files included in the Work.</li>
<li>"<b>Publisher</b>" means the provider of the website, magazine, CD-ROM, DVD or other
medium from or by which the Work is obtained by You.</li>
<li><b>"Source Code"</b> refers to the collection of source code and configuration files
used to create the Executable Files.</li>
<li><b>"Standard Version"</b> refers to such a Work if it has not been modified, or
has been modified in accordance with the consent of the Author, such consent being
in the full discretion of the Author. </li>
<li><b>"Work"</b> refers to the collection of files distributed by the Publisher, including
the Source Code, Executable Files, binaries, data files, documentation, whitepapers
and the Articles. </li>
<li><b>"You"</b> is you, an individual or entity wishing to use the Work and exercise
your rights under this License.
</li>
</ol>
</li>
<li><strong>Fair Use/Fair Use Rights.</strong> Nothing in this License is intended to
reduce, limit, or restrict any rights arising from fair use, fair dealing, first
sale or other limitations on the exclusive rights of the copyright owner under copyright
law or other applicable laws.
</li>
<li><strong>License Grant.</strong> Subject to the terms and conditions of this License,
the Author hereby grants You a worldwide, royalty-free, non-exclusive, perpetual
(for the duration of the applicable copyright) license to exercise the rights in
the Work as stated below:
<ol class="SpacedList" style="list-style-type: lower-alpha;">
<li>You may use the standard version of the Source Code or Executable Files in Your
own applications. </li>
<li>You may apply bug fixes, portability fixes and other modifications obtained from
the Public Domain or from the Author. A Work modified in such a way shall still
be considered the standard version and will be subject to this License.</li>
<li>You may otherwise modify Your copy of this Work (excluding the Articles) in any
way to create a Derivative Work, provided that You insert a prominent notice in
each changed file stating how, when and where You changed that file.</li>
<li>You may distribute the standard version of the Executable Files and Source Code
or Derivative Work in aggregate with other (possibly commercial) programs as part
of a larger (possibly commercial) software distribution. </li>
<li>The Articles discussing the Work published in any form by the author may not be
distributed or republished without the Author&#39;s consent. The author retains
copyright to any such Articles. You may use the Executable Files and Source Code
pursuant to this License but you may not repost or republish or otherwise distribute
or make available the Articles, without the prior written consent of the Author.</li>
</ol>
Any subroutines or modules supplied by You and linked into the Source Code or Executable
Files of this Work shall not be considered part of this Work and will not be subject
to the terms of this License.
</li>
<li><strong>Patent License.</strong> Subject to the terms and conditions of this License,
each Author hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable (except as stated in this section) patent license to make, have made, use, import,
and otherwise transfer the Work.</li>
<li><strong>Restrictions.</strong> The license granted in Section 3 above is expressly
made subject to and limited by the following restrictions:
<ol class="SpacedList" style="list-style-type: lower-alpha;">
<li>You agree not to remove any of the original copyright, patent, trademark, and
attribution notices and associated disclaimers that may appear in the Source Code
or Executable Files. </li>
<li>You agree not to advertise or in any way imply that this Work is a product of Your
own. </li>
<li>The name of the Author may not be used to endorse or promote products derived from
the Work without the prior written consent of the Author.</li>
<li>You agree not to sell, lease, or rent any part of the Work. This does not restrict
you from including the Work or any part of the Work inside a larger software
distribution that itself is being sold. The Work by itself, though, cannot be sold,
leased or rented.</li>
<li>You may distribute the Executable Files and Source Code only under the terms of
this License, and You must include a copy of, or the Uniform Resource Identifier
for, this License with every copy of the Executable Files or Source Code You distribute
and ensure that anyone receiving such Executable Files and Source Code agrees that
the terms of this License apply to such Executable Files and/or Source Code. You
may not offer or impose any terms on the Work that alter or restrict the terms of
this License or the recipients&#39; exercise of the rights granted hereunder. You
may not sublicense the Work. You must keep intact all notices that refer to this
License and to the disclaimer of warranties. You may not distribute the Executable
Files or Source Code with any technological measures that control access or use
of the Work in a manner inconsistent with the terms of this License. </li>
<li>You agree not to use the Work for illegal, immoral or improper purposes, or on pages
containing illegal, immoral or improper material. The Work is subject to applicable
export laws. You agree to comply with all such laws and regulations that may apply
to the Work after Your receipt of the Work.
</li>
</ol>
</li>
<li><strong>Representations, Warranties and Disclaimer.</strong> THIS WORK IS PROVIDED
"AS IS", "WHERE IS" AND "AS AVAILABLE", WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES
OR CONDITIONS OR GUARANTEES. YOU, THE USER, ASSUME ALL RISK IN ITS USE, INCLUDING
COPYRIGHT INFRINGEMENT, PATENT INFRINGEMENT, SUITABILITY, ETC. AUTHOR EXPRESSLY
DISCLAIMS ALL EXPRESS, IMPLIED OR STATUTORY WARRANTIES OR CONDITIONS, INCLUDING
WITHOUT LIMITATION, WARRANTIES OR CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY
OR FITNESS FOR A PARTICULAR PURPOSE, OR ANY WARRANTY OF TITLE OR NON-INFRINGEMENT,
OR THAT THE WORK (OR ANY PORTION THEREOF) IS CORRECT, USEFUL, BUG-FREE OR FREE OF
VIRUSES. YOU MUST PASS THIS DISCLAIMER ON WHENEVER YOU DISTRIBUTE THE WORK OR DERIVATIVE
WORKS.
</li>
<li><b>Indemnity. </b>You agree to defend, indemnify and hold harmless the Author and
the Publisher from and against any claims, suits, losses, damages, liabilities,
costs, and expenses (including reasonable legal or attorneys fees) resulting from
or relating to any use of the Work by You.
</li>
<li><strong>Limitation on Liability.</strong> EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE
LAW, IN NO EVENT WILL THE AUTHOR OR THE PUBLISHER BE LIABLE TO YOU ON ANY LEGAL
THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES
ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK OR OTHERWISE, EVEN IF THE AUTHOR
OR THE PUBLISHER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
</li>
<li><strong>Termination.</strong>
<ol style="list-style-type: lower-alpha;">
<li>This License and the rights granted hereunder will terminate automatically upon
any breach by You of any term of this License. Individuals or entities who have
received Derivative Works from You under this License, however, will not have their
licenses terminated provided such individuals or entities remain in full compliance
with those licenses. Sections 1, 2, 6, 7, 8, 9, 10 and 11 will survive any termination
of this License. </li>
<li>If You bring a copyright, trademark, patent or any other infringement claim against
any contributor over infringements You claim are made by the Work, your License
from such contributor to the Work ends automatically.</li>
<li>Subject to the above terms and conditions, this License is perpetual (for the duration
of the applicable copyright in the Work). Notwithstanding the above, the Author
reserves the right to release the Work under different license terms or to stop
distributing the Work at any time; provided, however that any such election will
not serve to withdraw this License (or any other license that has been, or is required
to be, granted under the terms of this License), and this License will continue
in full force and effect unless terminated as stated above.
</li>
</ol>
</li>
<li><strong>Publisher</strong>. The parties hereby confirm that the Publisher shall
not, under any circumstances, be responsible for and shall not have any liability
in respect of the subject matter of this License. The Publisher makes no warranty
whatsoever in connection with the Work and shall not be liable to You or any party
on any legal theory for any damages whatsoever, including without limitation any
general, special, incidental or consequential damages arising in connection to this
license. The Publisher reserves the right to cease making the Work available to
You at any time without notice</li>
<li><strong>Miscellaneous</strong>
<ol class="SpacedList" style="list-style-type: lower-alpha;">
<li>This License shall be governed by the laws of the location of the head office of
the Author or if the Author is an individual, the laws of location of the principal
place of residence of the Author.</li>
<li>If any provision of this License is invalid or unenforceable under applicable law,
it shall not affect the validity or enforceability of the remainder of the terms
of this License, and without further action by the parties to this License, such
provision shall be reformed to the minimum extent necessary to make such provision
valid and enforceable. </li>
<li>No term or provision of this License shall be deemed waived and no breach consented
to unless such waiver or consent shall be in writing and signed by the party to
be charged with such waiver or consent. </li>
<li>This License constitutes the entire agreement between the parties with respect to
the Work licensed herein. There are no understandings, agreements or representations
with respect to the Work not specified herein. The Author shall not be bound by
any additional provisions that may appear in any communication from You. This License
may not be modified without the mutual written agreement of the Author and You.
</li>
</ol>
</li>
</ol>
</div>
</center>
</body>
</html>

View File

@ -1,2 +1,19 @@
# advanced-python-homework-2023 # advanced-python-homework-2023
# Окружение
Чтобы развернуть окружение для разработки с помощью conda:
conda env create -f environment.yml
conda activate scada-marmi
# Sphinx
sphinx-quickstart docs
sphinx-build -M html docs/source/ docs/build/
cd docs
./make html

View File

@ -0,0 +1,14 @@
"""
SCADA (Supervisory Control And Data Acquisition)
SCADA-системы нужны для организации сбора данных в реальном времени,
диспетчерского контроля и автоматизации технологических процессов.
SCADA-системы решают следующие задачи:
Обмен данными и их обработка в реальном времени.
Логическое управление.
Отображение информации на экране монитора в удобной и понятной для человека форме.
Ведение базы данных с технологической информацией.
Аварийная сигнализация и управление служебными сообщениями о неполадках.
Подготовка и генерирование отчетов о ходе технологического процесса.
"""

20
docs/Makefile Normal file
View File

@ -0,0 +1,20 @@
# Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line, and also
# from the environment for the first two.
SPHINXOPTS ?=
SPHINXBUILD ?= sphinx-build
SOURCEDIR = source
BUILDDIR = build
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)

35
docs/make.bat Normal file
View File

@ -0,0 +1,35 @@
@ECHO OFF
pushd %~dp0
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set SOURCEDIR=source
set BUILDDIR=build
%SPHINXBUILD% >NUL 2>NUL
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.https://www.sphinx-doc.org/
exit /b 1
)
if "%1" == "" goto help
%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
goto end
:help
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
:end
popd

54
docs/source/conf.py Normal file
View File

@ -0,0 +1,54 @@
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))
# -- Project information -----------------------------------------------------
project = 'scada'
copyright = '2023, marmi'
author = 'marmi'
# -- General configuration ---------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = []
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'alabaster'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

33
docs/source/index.rst Normal file
View File

@ -0,0 +1,33 @@
.. scada documentation master file, created by
sphinx-quickstart on Thu Sep 28 15:37:18 2023.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to scada's documentation!
=================================
**Scada** is my project. It offers a *simple* and
*intuitive* interface.
.. note::
This project is under active development.
you can use the package ``controls``:
.. automodule: controls/__init__.py
:members:
.. toctree::
:maxdepth: 2
:caption: Contents:
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

13
environment.yml Normal file
View File

@ -0,0 +1,13 @@
# To set up a development environment using conda run:
#
# conda env create -f environment.yml
# conda activate scada-marmi
#
name: scada-marmi
channels:
- conda-forge
- anaconda
dependencies:
- sphinx
- pylint
- mypy

View File

@ -1,9 +1,12 @@
from dataclasses import dataclass from dataclasses import dataclass
from typing import Optional, Collection, Any from typing import Optional, Collection, Any
from abc import abstractmethod from abc import ABC, abstractmethod
from enum import IntEnum
class DeviceLifecycleState: class DeviceLifecycleState(IntEnum):
pass # TODO(Homework #3) INIT = 0
OPEN = 1
CLOSE = 2
class DevaceError(Exception): class DevaceError(Exception):
@ -33,8 +36,8 @@ class ActionDescriptor:
info: Optional[str] = None info: Optional[str] = None
class Device: class Device(ABC):
# TODO(Homework #3)
_state = DeviceLifecycleState.INIT _state = DeviceLifecycleState.INIT
@property @property
@ -44,9 +47,13 @@ class Device:
def close(self): def close(self):
self._state = DeviceLifecycleState.CLOSE self._state = DeviceLifecycleState.CLOSE
@property
@abstractmethod
def trait_descriptors(self) -> Collection[TraitDescriptor]: def trait_descriptors(self) -> Collection[TraitDescriptor]:
pass pass
@property
@abstractmethod
def action_descriptors(self) -> Collection[ActionDescriptor]: def action_descriptors(self) -> Collection[ActionDescriptor]:
pass pass

View File

@ -1,8 +1,77 @@
import time
from turtle import Turtle from turtle import Turtle
from controls.device import SynchronyDevice from equipment.device import SynchronyDevice
from equipment.device import Device
import inspect
from typing import Optional, Collection, Any
class TurtleDevice(SynchronyDevice): class TurtleDevice(SynchronyDevice):
pass # TODO(Homework #3) def open(self):
super().open()
self.turtle = Turtle()
def close (self):
super().close()
del self.turtle
@property
def trait_descriptors(self):
l = list()
for i in inspect.getmembers(TurtleDevice):
if not (i[0].startswith("__") or i[0].startswith("_")) and not inspect.isfunction(i[1]):
l.append(i[0])
return l
@property
def action_descriptors(self):
l = list()
#print(inspect.getmembers(TurtleDevice))
#for i in dir(TurtleDevice):
# # print(type(getattr(TurtleDevice(), i))=='method')
# # if not i.startswith("__") and type(getattr(TurtleDevice(), i)) == types.MethodType:
# if not i.startswith("__") and inspect.isroutine(inspect.getattr_static(TurtleDevice, i)):
# sig = inspect.signature(getattr(TurtleDevice, i))
# l.append(i + " " + str(sig))
#return l
for i in inspect.getmembers(TurtleDevice):
# print(type(getattr(TurtleDevice, i)))
# print(type(getattr(TurtleDevice(), i))=='method')
if not (i[0].startswith("__") or i[0].startswith("_")) and inspect.isfunction(i[1]):
sig = inspect.signature(getattr(TurtleDevice, i[0]))
l.append(i[0]+str(sig))
return l
def execute(self, action_name: str, *args, **kwargs):
"""Execute action `action_name`, using `args` and `kwargs` as action argument."""
if self.state == 1:
f = getattr(self.turtle, action_name)
f(int(*args), **kwargs)
else:
print("It's not opened")
self.open()
#time.sleep(30)
f = getattr(self.turtle, action_name)
f(int(*args), **kwargs)
def read(self, trait_name: str):
"""Read physical state of trait `trait_name` from device."""
return getattr(self.turtle, trait_name)
def write(self, trait_name: str, value: Any) -> bool:
"""Pass `value` to trait `trait_name` of device."""
setattr(self.turtle, trait_name, value)
def invalidate(self, trait_name: str):
"""Invalidate logical state of trait `trait_name`"""
if self.read(trait_name) == self.__getitem__(trait_name):
print("Everything's okey")
else:
print(f"Something went wrong with {trait_name}.")
def __getitem__(self, trait_name: str) -> Optional[Any]:
"""Return logical state of trait `trait_name`."""
return getattr(self, trait_name)
#print(inspect.getmembers(Turtle))
#t = TurtleDevice()
#print(t.execute("forward", 3))

View File

@ -1,5 +1,9 @@
import cmd import cmd
import threading import threading
from threading import Thread
from threading import Event
import argparse
import time
from queue import Queue from queue import Queue
@ -7,11 +11,29 @@ from equipment.turtle_device import TurtleDevice
class TurtleDeviceThread(threading.Thread): class TurtleDeviceThread(threading.Thread):
# TODO(Homework 4)
# TODO(Homework 4) \begin
def __message_processing__(self):
while True:
new_message = self.queue.get()
#print(type(new_message))
#print(new_message)
#print("Name and args of action are {}".format(new_message))
self.device.execute(*new_message)
#time.sleep(30)
self.queue.task_done()
if self.event.is_set():
break
def __message_thread__(self):
thread = Thread(target = self.__message_processing__, daemon=True)
thread.start()
# TODO(Homework 4) \end
def __init__(self): def __init__(self):
super().__init__() super().__init__()
self.device = TurtleDevice() self.device = TurtleDevice()
self.queue = Queue() self.queue = Queue()
self.event = Event()
class NoBlockingTurtleShell(cmd.Cmd): class NoBlockingTurtleShell(cmd.Cmd):
@ -20,14 +42,24 @@ class NoBlockingTurtleShell(cmd.Cmd):
file = None file = None
def __init__(self, turtle_thread: TurtleDeviceThread): def __init__(self, turtle_thread: TurtleDeviceThread):
pass # TODO(Homework 4) # TODO(Homework 4) \begin
super(NoBlockingTurtleShell, self).__init__()
turtle_thread.__message_thread__()
# TODO(Homework 4) \end
def do_execute(self, arg): def do_execute(self, arg):
pass # TODO(Homework 4) # TODO(Homework 4) \begin
turtle_thread.queue.put(parse(arg))
# TODO(Homework 4) \end
def do_exit(self, arg): def do_exit(self, arg):
pass # TODO(Homework 4) # TODO(Homework 4) \begin
turtle_thread.event.set()
# TODO(Homework 4) \end
def parse(arg):
'Convert a series of zero or more numbers to an argument tuple'
return tuple(arg.split())
if __name__ == '__main__': if __name__ == '__main__':
turtle_thread = TurtleDeviceThread() turtle_thread = TurtleDeviceThread()

10
setup.py Normal file
View File

@ -0,0 +1,10 @@
setup(
name='first_project',
version='0.0.0',
description='This is my first project',
author='MarMi',
author_email='mikhailycheva.mv@phystech.edu',
url="https://git.sciprog.center/marmi/advanced-python-homework-2023-marmi.git",
license="CPOL",
packages=find_packages(include=['controls']),
)

View File

@ -10,6 +10,7 @@ class TurtleShell(cmd.Cmd):
# ----- basic turtle commands ----- # ----- basic turtle commands -----
def do_forward(self, arg): def do_forward(self, arg):
'Move the turtle forward by the specified distance: FORWARD 10' 'Move the turtle forward by the specified distance: FORWARD 10'
forward(*parse(arg)) forward(*parse(arg))
def do_right(self, arg): def do_right(self, arg):
'Turn turtle right by given number of degrees: RIGHT 20' 'Turn turtle right by given number of degrees: RIGHT 20'