pax_global_header00006660000000000000000000000064145553046030014517gustar00rootroot0000000000000052 comment=a4c97903d0b72a5df0a9c51d16ca12803e1b6d39 gjohansson-ST-pytrafikverket-a4c9790/000077500000000000000000000000001455530460300176265ustar00rootroot00000000000000gjohansson-ST-pytrafikverket-a4c9790/.gitignore000066400000000000000000000132571455530460300216260ustar00rootroot00000000000000## Ignore Visual Studio temporary files, build results, and ## files generated by popular Visual Studio add-ons. ## ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore # User-specific files *.suo *.user *.userosscache *.sln.docstates # User-specific files (MonoDevelop/Xamarin Studio) *.userprefs # Build results [Dd]ebug/ [Dd]ebugPublic/ [Rr]elease/ [Rr]eleases/ x64/ x86/ bld/ [Bb]in/ [Oo]bj/ [Ll]og/ # Visual Studio 2015 cache/options directory .vs/ # Uncomment if you have tasks that create the project's static files in wwwroot #wwwroot/ # MSTest test Results [Tt]est[Rr]esult*/ [Bb]uild[Ll]og.* # NUNIT *.VisualState.xml TestResult.xml # Build Results of an ATL Project [Dd]ebugPS/ [Rr]eleasePS/ dlldata.c # .NET Core project.lock.json project.fragment.lock.json artifacts/ **/Properties/launchSettings.json *_i.c *_p.c *_i.h *.ilk *.meta *.obj *.pch *.pdb *.pgc *.pgd *.rsp *.sbr *.tlb *.tli *.tlh *.tmp *.tmp_proj *.log *.vspscc *.vssscc .builds *.pidb *.svclog *.scc # Chutzpah Test files _Chutzpah* # Visual C++ cache files ipch/ *.aps *.ncb *.opendb *.opensdf *.sdf *.cachefile *.VC.db *.VC.VC.opendb # Visual Studio profiler *.psess *.vsp *.vspx *.sap # TFS 2012 Local Workspace $tf/ # Guidance Automation Toolkit *.gpState # ReSharper is a .NET coding add-in _ReSharper*/ *.[Rr]e[Ss]harper *.DotSettings.user # JustCode is a .NET coding add-in .JustCode # TeamCity is a build add-in _TeamCity* # DotCover is a Code Coverage Tool *.dotCover # Visual Studio code coverage results *.coverage *.coveragexml # NCrunch _NCrunch_* .*crunch*.local.xml nCrunchTemp_* # MightyMoose *.mm.* AutoTest.Net/ # Web workbench (sass) .sass-cache/ # Installshield output folder [Ee]xpress/ # DocProject is a documentation generator add-in DocProject/buildhelp/ DocProject/Help/*.HxT DocProject/Help/*.HxC DocProject/Help/*.hhc DocProject/Help/*.hhk DocProject/Help/*.hhp DocProject/Help/Html2 DocProject/Help/html # Click-Once directory publish/ # Publish Web Output *.[Pp]ublish.xml *.azurePubxml # TODO: Comment the next line if you want to checkin your web deploy settings # but database connection strings (with potential passwords) will be unencrypted *.pubxml *.publishproj # Microsoft Azure Web App publish settings. Comment the next line if you want to # checkin your Azure Web App publish settings, but sensitive information contained # in these scripts will be unencrypted PublishScripts/ # NuGet Packages *.nupkg # The packages folder can be ignored because of Package Restore **/packages/* # except build/, which is used as an MSBuild target. !**/packages/build/ # Uncomment if necessary however generally it will be regenerated when needed #!**/packages/repositories.config # NuGet v3's project.json files produces more ignorable files *.nuget.props *.nuget.targets # Microsoft Azure Build Output csx/ *.build.csdef # Microsoft Azure Emulator ecf/ rcf/ # Windows Store app package directories and files AppPackages/ BundleArtifacts/ Package.StoreAssociation.xml _pkginfo.txt # Visual Studio cache files # files ending in .cache can be ignored *.[Cc]ache # but keep track of directories ending in .cache !*.[Cc]ache/ # Others ClientBin/ ~$* *~ *.dbmdl *.dbproj.schemaview *.jfm *.pfx *.publishsettings orleans.codegen.cs # Since there are multiple workflows, uncomment next line to ignore bower_components # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) #bower_components/ # RIA/Silverlight projects Generated_Code/ # Backup & report files from converting an old project file # to a newer Visual Studio version. Backup files are not needed, # because we have git ;-) _UpgradeReport_Files/ Backup*/ UpgradeLog*.XML UpgradeLog*.htm # SQL Server files *.mdf *.ldf *.ndf # Business Intelligence projects *.rdl.data *.bim.layout *.bim_*.settings # Microsoft Fakes FakesAssemblies/ # GhostDoc plugin setting file *.GhostDoc.xml # Node.js Tools for Visual Studio .ntvs_analysis.dat node_modules/ # Typescript v1 declaration files typings/ # Visual Studio 6 build log *.plg # Visual Studio 6 workspace options file *.opt # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) *.vbw # Visual Studio LightSwitch build output **/*.HTMLClient/GeneratedArtifacts **/*.DesktopClient/GeneratedArtifacts **/*.DesktopClient/ModelManifest.xml **/*.Server/GeneratedArtifacts **/*.Server/ModelManifest.xml _Pvt_Extensions # Paket dependency manager .paket/paket.exe paket-files/ # FAKE - F# Make .fake/ # JetBrains Rider .idea/ *.sln.iml # CodeRush .cr/ # Python Tools for Visual Studio (PTVS) __pycache__/ *.pyc # Cake - Uncomment if you are using it # tools/** # !tools/packages.config # Telerik's JustMock configuration file *.jmconfig # BizTalk build output *.btp.cs *.btm.cs *.odx.cs *.xsd.cs # Python visual studio .ptvs/ Scripts/ pyvenv.cfg pip-selfcheck.json # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python env/ build/ develop-eggs/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ *.egg-info/ .installed.cfg *.egg dist/ # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *,cover .hypothesis/ # Translations *.mo *.pot # Django stuff: *.log # Sphinx documentation docs/_build/ # PyBuilder target/ #Ipython Notebook .ipynb_checkpoints .DS_Store .project .pydevproject .vscode # Virtual environment venv/ # Test purpose only ferry_test.py # Mypy cache .mypy_cache test.py gjohansson-ST-pytrafikverket-a4c9790/LICENSE000066400000000000000000000020601455530460300206310ustar00rootroot00000000000000MIT License Copyright (c) 2017 Peter Andersson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. gjohansson-ST-pytrafikverket-a4c9790/README.md000066400000000000000000000041051455530460300211050ustar00rootroot00000000000000# pytrafikverket python module for communicating with the swedish trafikverket api Development and testing done with 3.11 ## Code example ```python from pytrafikverket import TrafikverketTrain, StationInfo import aiohttp import asyncio from datetime import datetime async def main(loop): async with aiohttp.ClientSession(loop=loop) as session: train_api = TrafikverketTrain(session, "api_key_here") stations = await train_api.async_search_train_stations("kristianstad") for station in stations: print(station.name + " " + station.signature) from_station = await train_api.async_get_train_station("Sölvesborg") to_station = await train_api.async_get_train_station("Kristianstad C") product_description = "SJ Regional" # Optional search field print("from_station_signature: " + from_station.signature) print("to_station_signature: " + to_station.signature) train_stop = await train_api.async_get_train_stop(from_station, to_station, datetime(2022, 4, 11, 12, 57), product_description); print(train_stop.get_state()) loop = asyncio.get_event_loop() loop.run_until_complete(main(loop)) ``` ## CLI example ```bash $ py pytrafikverket.py -key -method search-for-station -station "Kristianstad" $ py pytrafikverket.py -key -method get-next-train-stop -from-station "Kristianstad C" -to-station "Sölvesborg" $ py pytrafikverket.py -key -method get-next-train-stop -from-station "Kristianstad C" -to-station "Sölvesborg" -train-product "SJ Regional" $ py pytrafikverket.py -key -method get-train-stop -from-station "Kristianstad C" -to-station "Sölvesborg" -date-time "2017-05-19T16:38:00" $ py pytrafikverket.py -key -method get-weather -station "Nöbbele" $ py pytrafikverket.py -key -method search-for-ferry-route -route "sund" $ py pytrafikverket.py -key -method get-ferry-route -route "Adelsöleden" $ py pytrafikverket.py -key -method get-next-ferry-stop -from-harbor "Ekerö" $ py pytrafikverket.py -key -method get-next-ferry-stop -from-harbor "Furusund" -date-time "2019-12-24T00:00:00" ``` gjohansson-ST-pytrafikverket-a4c9790/mypy.ini000066400000000000000000000012331455530460300213240ustar00rootroot00000000000000[mypy] python_version = 3.11 show_error_codes = true follow_imports = silent ignore_missing_imports = true local_partial_types = true strict_equality = true no_implicit_optional = true warn_incomplete_stub = true warn_redundant_casts = true warn_unused_configs = true warn_unused_ignores = true enable_error_code = ignore-without-code, redundant-self, truthy-iterable disable_error_code = annotation-unchecked strict_concatenate = false check_untyped_defs = true disallow_incomplete_defs = true disallow_subclassing_any = true disallow_untyped_calls = true disallow_untyped_decorators = true disallow_untyped_defs = true warn_return_any = true warn_unreachable = truegjohansson-ST-pytrafikverket-a4c9790/pylintrc000066400000000000000000000513231455530460300214210ustar00rootroot00000000000000[MAIN] # Analyse import fallback blocks. This can be used to support both Python 2 and # 3 compatible code, which means that the block might have code that exists # only in one or another interpreter, leading to false positives when analysed. analyse-fallback-blocks=no # Clear in-memory caches upon conclusion of linting. Useful if running pylint # in a server-like mode. clear-cache-post-run=no # Load and enable all available extensions. Use --list-extensions to see a list # all available extensions. #enable-all-extensions= # In error mode, messages with a category besides ERROR or FATAL are # suppressed, and no reports are done by default. Error mode is compatible with # disabling specific errors. #errors-only= # Always return a 0 (non-error) status code, even if lint errors are found. # This is primarily useful in continuous integration scripts. #exit-zero= # A comma-separated list of package or module names from where C extensions may # be loaded. Extensions are loading into the active Python interpreter and may # run arbitrary code. extension-pkg-allow-list= # A comma-separated list of package or module names from where C extensions may # be loaded. Extensions are loading into the active Python interpreter and may # run arbitrary code. (This is an alternative name to extension-pkg-allow-list # for backward compatibility.) extension-pkg-whitelist=lxml # Return non-zero exit code if any of these messages/categories are detected, # even if score is above --fail-under value. Syntax same as enable. Messages # specified are enabled, while categories only check already-enabled messages. fail-on= # Specify a score threshold under which the program will exit with error. fail-under=10 # Interpret the stdin as a python script, whose filename needs to be passed as # the module_or_package argument. #from-stdin= # Files or directories to be skipped. They should be base names, not paths. ignore=CVS # Add files or directories matching the regular expressions patterns to the # ignore-list. The regex matches against paths and can be in Posix or Windows # format. Because '\\' represents the directory delimiter on Windows systems, # it can't be used as an escape character. ignore-paths= # Files or directories matching the regular expression patterns are skipped. # The regex matches against base names, not paths. The default value ignores # Emacs file locks ignore-patterns=^\.# # List of module names for which member attributes should not be checked # (useful for modules/projects where namespaces are manipulated during runtime # and thus existing member attributes cannot be deduced by static analysis). It # supports qualified module names, as well as Unix pattern matching. ignored-modules= # Python code to execute, usually for sys.path manipulation such as # pygtk.require(). #init-hook= # Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the # number of processors available to use, and will cap the count on Windows to # avoid hangs. jobs=1 # Control the amount of potential inferred values when inferring a single # object. This can help the performance when dealing with large functions or # complex, nested conditions. limit-inference-results=100 # List of plugins (as comma separated values of python module names) to load, # usually to register additional checkers. load-plugins= # Pickle collected data for later comparisons. persistent=yes # Minimum Python version to use for version dependent checks. Will default to # the version used to run pylint. py-version=3.11 # Discover python modules and packages in the file system subtree. recursive=no # Add paths to the list of the source roots. Supports globbing patterns. The # source root is an absolute path or a path relative to the current working # directory used to determine a package namespace for modules located under the # source root. source-roots= # When enabled, pylint would attempt to guess common misconfiguration and emit # user-friendly hints instead of false-positive error messages. suggestion-mode=yes # Allow loading of arbitrary C extensions. Extensions are imported into the # active Python interpreter and may run arbitrary code. unsafe-load-any-extension=no # In verbose mode, extra non-checker-related info will be displayed. #verbose= [BASIC] # Naming style matching correct argument names. argument-naming-style=snake_case # Regular expression matching correct argument names. Overrides argument- # naming-style. If left empty, argument names will be checked with the set # naming style. #argument-rgx= # Naming style matching correct attribute names. attr-naming-style=snake_case # Regular expression matching correct attribute names. Overrides attr-naming- # style. If left empty, attribute names will be checked with the set naming # style. #attr-rgx= # Bad variable names which should always be refused, separated by a comma. bad-names=foo, bar, baz, toto, tutu, tata # Bad variable names regexes, separated by a comma. If names match any regex, # they will always be refused bad-names-rgxs= # Naming style matching correct class attribute names. class-attribute-naming-style=any # Regular expression matching correct class attribute names. Overrides class- # attribute-naming-style. If left empty, class attribute names will be checked # with the set naming style. #class-attribute-rgx= # Naming style matching correct class constant names. class-const-naming-style=UPPER_CASE # Regular expression matching correct class constant names. Overrides class- # const-naming-style. If left empty, class constant names will be checked with # the set naming style. #class-const-rgx= # Naming style matching correct class names. class-naming-style=PascalCase # Regular expression matching correct class names. Overrides class-naming- # style. If left empty, class names will be checked with the set naming style. #class-rgx= # Naming style matching correct constant names. const-naming-style=UPPER_CASE # Regular expression matching correct constant names. Overrides const-naming- # style. If left empty, constant names will be checked with the set naming # style. #const-rgx= # Minimum line length for functions/classes that require docstrings, shorter # ones are exempt. docstring-min-length=-1 # Naming style matching correct function names. function-naming-style=snake_case # Regular expression matching correct function names. Overrides function- # naming-style. If left empty, function names will be checked with the set # naming style. #function-rgx= # Good variable names which should always be accepted, separated by a comma. good-names=i, j, k, ex, Run, _ # Good variable names regexes, separated by a comma. If names match any regex, # they will always be accepted good-names-rgxs= # Include a hint for the correct naming format with invalid-name. include-naming-hint=no # Naming style matching correct inline iteration names. inlinevar-naming-style=any # Regular expression matching correct inline iteration names. Overrides # inlinevar-naming-style. If left empty, inline iteration names will be checked # with the set naming style. #inlinevar-rgx= # Naming style matching correct method names. method-naming-style=snake_case # Regular expression matching correct method names. Overrides method-naming- # style. If left empty, method names will be checked with the set naming style. #method-rgx= # Naming style matching correct module names. module-naming-style=snake_case # Regular expression matching correct module names. Overrides module-naming- # style. If left empty, module names will be checked with the set naming style. #module-rgx= # Colon-delimited sets of names that determine each other's naming style when # the name regexes allow several styles. name-group= # Regular expression which should only match function or class names that do # not require a docstring. no-docstring-rgx=^_ # List of decorators that produce properties, such as abc.abstractproperty. Add # to this list to register other decorators that produce valid properties. # These decorators are taken in consideration only for invalid-name. property-classes=abc.abstractproperty # Regular expression matching correct type alias names. If left empty, type # alias names will be checked with the set naming style. #typealias-rgx= # Regular expression matching correct type variable names. If left empty, type # variable names will be checked with the set naming style. #typevar-rgx= # Naming style matching correct variable names. variable-naming-style=snake_case # Regular expression matching correct variable names. Overrides variable- # naming-style. If left empty, variable names will be checked with the set # naming style. #variable-rgx= [CLASSES] # Warn about protected attribute access inside special methods check-protected-access-in-special-methods=no # List of method names used to declare (i.e. assign) instance attributes. defining-attr-methods=__init__, __new__, setUp, asyncSetUp, __post_init__ # List of member names, which should be excluded from the protected access # warning. exclude-protected=_asdict,_fields,_replace,_source,_make,os._exit # List of valid names for the first argument in a class method. valid-classmethod-first-arg=cls # List of valid names for the first argument in a metaclass class method. valid-metaclass-classmethod-first-arg=mcs [DESIGN] # List of regular expressions of class ancestor names to ignore when counting # public methods (see R0903) exclude-too-few-public-methods= # List of qualified class names to ignore when counting class parents (see # R0901) ignored-parents= # Maximum number of arguments for function / method. max-args=10 # Maximum number of attributes for a class (see R0902). max-attributes=7 # Maximum number of boolean expressions in an if statement (see R0916). max-bool-expr=5 # Maximum number of branch for function / method body. max-branches=12 # Maximum number of locals for function / method body. max-locals=15 # Maximum number of parents for a class (see R0901). max-parents=7 # Maximum number of public methods for a class (see R0904). max-public-methods=20 # Maximum number of return / yield for function / method body. max-returns=6 # Maximum number of statements in function / method body. max-statements=50 # Minimum number of public methods for a class (see R0903). min-public-methods=1 [EXCEPTIONS] # Exceptions that will emit a warning when caught. overgeneral-exceptions=builtins.BaseException,builtins.Exception [FORMAT] # Expected format of line ending, e.g. empty (any line ending), LF or CRLF. expected-line-ending-format= # Regexp for a line that is allowed to be longer than the limit. ignore-long-lines=^\s*(# )??$ # Number of spaces of indent required inside a hanging or continued line. indent-after-paren=4 # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 # tab). indent-string=' ' # Maximum number of characters on a single line. max-line-length=100 # Maximum number of lines in a module. max-module-lines=1000 # Allow the body of a class to be on the same line as the declaration if body # contains single statement. single-line-class-stmt=no # Allow the body of an if to be on the same line as the test if there is no # else. single-line-if-stmt=no [IMPORTS] # List of modules that can be imported at any level, not just the top level # one. allow-any-import-level= # Allow explicit reexports by alias from a package __init__. allow-reexport-from-package=no # Allow wildcard imports from modules that define __all__. allow-wildcard-with-all=no # Deprecated modules which should not be used, separated by a comma. deprecated-modules= # Output a graph (.gv or any supported image format) of external dependencies # to the given file (report RP0402 must not be disabled). ext-import-graph= # Output a graph (.gv or any supported image format) of all (i.e. internal and # external) dependencies to the given file (report RP0402 must not be # disabled). import-graph= # Output a graph (.gv or any supported image format) of internal dependencies # to the given file (report RP0402 must not be disabled). int-import-graph= # Force import order to recognize a module as part of the standard # compatibility libraries. known-standard-library= # Force import order to recognize a module as part of a third party library. known-third-party=enchant # Couples of modules and preferred modules, separated by a comma. preferred-modules= [LOGGING] # The type of string formatting that logging methods do. `old` means using % # formatting, `new` is for `{}` formatting. logging-format-style=old # Logging modules to check that the string format arguments are in logging # function parameter format. logging-modules=logging [MESSAGES CONTROL] # Only show warnings with the listed confidence levels. Leave empty to show # all. Valid levels: HIGH, CONTROL_FLOW, INFERENCE, INFERENCE_FAILURE, # UNDEFINED. confidence=HIGH, CONTROL_FLOW, INFERENCE, INFERENCE_FAILURE, UNDEFINED # Disable the message, report, category or checker with the given id(s). You # can either give multiple identifiers separated by comma (,) or put this # option multiple times (only on the command line, not in the configuration # file where it should appear only once). You can also use "--disable=all" to # disable everything first and then re-enable specific checks. For example, if # you want to run only the similarities checker, you can use "--disable=all # --enable=similarities". If you want to run only the classes checker, but have # no Warning level messages displayed, use "--disable=all --enable=classes # --disable=W". disable=raw-checker-failed, bad-inline-option, locally-disabled, file-ignored, suppressed-message, useless-suppression, deprecated-pragma, use-symbolic-message-instead # Enable the message, report, category or checker with the given id(s). You can # either give multiple identifier separated by comma (,) or put this option # multiple time (only on the command line, not in the configuration file where # it should appear only once). See also the "--disable" option for examples. enable=c-extension-no-member [METHOD_ARGS] # List of qualified names (i.e., library.method) which require a timeout # parameter e.g. 'requests.api.get,requests.api.post' timeout-methods=requests.api.delete,requests.api.get,requests.api.head,requests.api.options,requests.api.patch,requests.api.post,requests.api.put,requests.api.request [MISCELLANEOUS] # List of note tags to take in consideration, separated by a comma. notes=FIXME, XXX, TODO # Regular expression of note tags to take in consideration. notes-rgx= [REFACTORING] # Maximum number of nested blocks for function / method body max-nested-blocks=5 # Complete name of functions that never returns. When checking for # inconsistent-return-statements if a never returning function is called then # it will be considered as an explicit return statement and no message will be # printed. never-returning-functions=sys.exit,argparse.parse_error [REPORTS] # Python expression which should return a score less than or equal to 10. You # have access to the variables 'fatal', 'error', 'warning', 'refactor', # 'convention', and 'info' which contain the number of messages in each # category, as well as 'statement' which is the total number of statements # analyzed. This score is used by the global evaluation report (RP0004). evaluation=max(0, 0 if fatal else 10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)) # Template used to display messages. This is a python new-style format string # used to format the message information. See doc for all details. msg-template= # Set the output format. Available formats are text, parseable, colorized, json # and msvs (visual studio). You can also give a reporter class, e.g. # mypackage.mymodule.MyReporterClass. #output-format= # Tells whether to display a full report or only the messages. reports=no # Activate the evaluation score. score=yes [SIMILARITIES] # Comments are removed from the similarity computation ignore-comments=yes # Docstrings are removed from the similarity computation ignore-docstrings=yes # Imports are removed from the similarity computation ignore-imports=yes # Signatures are removed from the similarity computation ignore-signatures=yes # Minimum lines number of a similarity. min-similarity-lines=4 [SPELLING] # Limits count of emitted suggestions for spelling mistakes. max-spelling-suggestions=4 # Spelling dictionary name. No available dictionaries : You need to install # both the python package and the system dependency for enchant to work.. spelling-dict= # List of comma separated words that should be considered directives if they # appear at the beginning of a comment and should not be checked. spelling-ignore-comment-directives=fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy: # List of comma separated words that should not be checked. spelling-ignore-words= # A path to a file that contains the private dictionary; one word per line. spelling-private-dict-file= # Tells whether to store unknown words to the private dictionary (see the # --spelling-private-dict-file option) instead of raising a message. spelling-store-unknown-words=no [STRING] # This flag controls whether inconsistent-quotes generates a warning when the # character used as a quote delimiter is used inconsistently within a module. check-quote-consistency=no # This flag controls whether the implicit-str-concat should generate a warning # on implicit string concatenation in sequences defined over several lines. check-str-concat-over-line-jumps=no [TYPECHECK] # List of decorators that produce context managers, such as # contextlib.contextmanager. Add to this list to register other decorators that # produce valid context managers. contextmanager-decorators=contextlib.contextmanager # List of members which are set dynamically and missed by pylint inference # system, and so shouldn't trigger E1101 when accessed. Python regular # expressions are accepted. generated-members= # Tells whether to warn about missing members when the owner of the attribute # is inferred to be None. ignore-none=yes # This flag controls whether pylint should warn about no-member and similar # checks whenever an opaque object is returned when inferring. The inference # can return multiple potential results while evaluating a Python object, but # some branches might not be evaluated, which results in partial inference. In # that case, it might be useful to still emit no-member and other checks for # the rest of the inferred objects. ignore-on-opaque-inference=yes # List of symbolic message names to ignore for Mixin members. ignored-checks-for-mixins=no-member, not-async-context-manager, not-context-manager, attribute-defined-outside-init # List of class names for which member attributes should not be checked (useful # for classes with dynamically set attributes). This supports the use of # qualified names. ignored-classes=optparse.Values,thread._local,_thread._local,argparse.Namespace # Show a hint with possible names when a member name was not found. The aspect # of finding the hint is based on edit distance. missing-member-hint=yes # The minimum edit distance a name should have in order to be considered a # similar match for a missing member name. missing-member-hint-distance=1 # The total number of similar names that should be taken in consideration when # showing a hint for a missing member. missing-member-max-choices=1 # Regex pattern to define which classes are considered mixins. mixin-class-rgx=.*[Mm]ixin # List of decorators that change the signature of a decorated function. signature-mutators= [VARIABLES] # List of additional names supposed to be defined in builtins. Remember that # you should avoid defining new builtins when possible. additional-builtins= # Tells whether unused global variables should be treated as a violation. allow-global-unused-variables=yes # List of names allowed to shadow builtins allowed-redefined-builtins= # List of strings which can identify a callback function by name. A callback # name must start or end with one of those strings. callbacks=cb_, _cb # A regular expression matching the name of dummy variables (i.e. expected to # not be used). dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ # Argument names that match this expression will be ignored. ignored-argument-names=_.*|^ignored_|^unused_ # Tells whether we should check for unused import in __init__ files. init-import=no # List of qualified module names which can have objects that can redefine # builtins. redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io gjohansson-ST-pytrafikverket-a4c9790/pytrafikverket.py000066400000000000000000000001151455530460300232470ustar00rootroot00000000000000"""Trafikverket CLI.""" from pytrafikverket import __main__ __main__.main() gjohansson-ST-pytrafikverket-a4c9790/pytrafikverket.pyproj000066400000000000000000000063301455530460300241470ustar00rootroot00000000000000 Debug 2.0 fd896284-6d42-487a-9045-83b14edac487 . pytrafikverket.py . . pytrafikverket pytrafikverket MSBuild|pytrafikverket|$(MSBuildProjectFullPath) Standard Python launcher False False -key [api_key_here] -method get-next-train-stop -from-station "Kristianstad C" -to-station "Sölvesborg" true false true false pytrafikverket 3.6 pytrafikverket (Python 3.6 (64-bit)) Scripts\python.exe Scripts\pythonw.exe PYTHONPATH X64 Code Code Code Code Code Code Code gjohansson-ST-pytrafikverket-a4c9790/pytrafikverket.sln000066400000000000000000000014521455530460300234200ustar00rootroot00000000000000 Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 VisualStudioVersion = 15.0.26430.6 MinimumVisualStudioVersion = 10.0.40219.1 Project("{888888A0-9F3D-457C-B088-3A5042F75D52}") = "pytrafikverket", "pytrafikverket.pyproj", "{FD896284-6D42-487A-9045-83B14EDAC487}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {FD896284-6D42-487A-9045-83B14EDAC487}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {FD896284-6D42-487A-9045-83B14EDAC487}.Release|Any CPU.ActiveCfg = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal gjohansson-ST-pytrafikverket-a4c9790/pytrafikverket/000077500000000000000000000000001455530460300227005ustar00rootroot00000000000000gjohansson-ST-pytrafikverket-a4c9790/pytrafikverket/__init__.py000066400000000000000000000010761455530460300250150ustar00rootroot00000000000000"""Pytrafikverket module.""" # flake8: noqa from .trafikverket import (AndFilter, FieldFilter, FieldSort, Filter, FilterOperation, NodeHelper, OrFilter, SortOrder, Trafikverket) from .trafikverket_camera import CameraInfo, TrafikverketCamera from .trafikverket_ferry import FerryStop, FerryStopStatus, TrafikverketFerry from .trafikverket_train import (StationInfo, TrafikverketTrain, TrainStop, TrainStopStatus) from .trafikverket_weather import TrafikverketWeather, WeatherStationInfo gjohansson-ST-pytrafikverket-a4c9790/pytrafikverket/__main__.py000066400000000000000000000145051455530460300247770ustar00rootroot00000000000000"""CLI enabler for pytrafikverket.""" from __future__ import annotations import argparse import asyncio import json from datetime import datetime from typing import Any import aiohttp from .trafikverket_ferry import TrafikverketFerry from .trafikverket_train import TrafikverketTrain from .trafikverket_weather import TrafikverketWeather SEARCH_FOR_STATION = "search-for-station" GET_TRAIN_STOP = "get-train-stop" GET_NEXT_TRAIN_STOP = "get-next-train-stop" GET_WEATHER = "get-weather" GET_FERRY_ROUTE = "get-ferry-route" SEARCH_FOR_FERRY_ROUTE = "search-for-ferry-route" GET_NEXT_FERRY_STOP = "get-next-ferry-stop" DATE_TIME_INPUT = "%Y-%m-%dT%H:%M:%S" async def async_main(loop: Any) -> None: # pylint: disable=R0912, R0914, R0915 """Set up function to handle input and get data to present.""" async with aiohttp.ClientSession(loop=loop) as session: parser = argparse.ArgumentParser( description="CLI used to get data from trafikverket" ) parser.add_argument("-key", type=str, required=True) parser.add_argument( "-method", required=True, choices=( SEARCH_FOR_STATION, GET_TRAIN_STOP, GET_NEXT_TRAIN_STOP, GET_WEATHER, GET_FERRY_ROUTE, SEARCH_FOR_FERRY_ROUTE, GET_NEXT_FERRY_STOP, ), ) parser.add_argument("-station", type=str) parser.add_argument("-from-station", type=str) parser.add_argument("-to-station", type=str) parser.add_argument("-date-time", type=str) parser.add_argument("-route", type=str) parser.add_argument("-from-harbor", type=str) parser.add_argument("-to-harbor", type=str) parser.add_argument("-train-product", type=str) parser.add_argument( "-exclude-canceled-trains", action=argparse.BooleanOptionalAction, default=False, ) async with asyncio.timeout(10): args = parser.parse_args() train_api = TrafikverketTrain(session, args.key) weather_api = TrafikverketWeather(session, args.key) ferry_api = TrafikverketFerry(session, args.key) if args.method == SEARCH_FOR_STATION: if args.station is None: raise ValueError("-station is required") stations = await train_api.async_search_train_stations(args.station) for station in stations: print_values(station) elif args.method == GET_TRAIN_STOP: from_station = await train_api.async_get_train_station( args.from_station ) to_station = await train_api.async_get_train_station(args.to_station) print(f"from_station_signature: {from_station.signature}") print(f"to_station_signature: {to_station.signature}") time = datetime.strptime(args.date_time, DATE_TIME_INPUT) train_stop = await train_api.async_get_train_stop( from_station, to_station, time, product_description=args.train_product, exclude_canceled=args.exclude_canceled_trains, ) print_values(train_stop) elif args.method == GET_NEXT_TRAIN_STOP: from_station = await train_api.async_get_train_station( args.from_station ) to_station = await train_api.async_get_train_station(args.to_station) print(f"from_station_signature: {from_station.signature}") print(f"to_station_signature: {to_station.signature}") if args.date_time is not None: time = datetime.strptime(args.date_time, DATE_TIME_INPUT) else: time = datetime.now() train_stop = await train_api.async_get_next_train_stop( from_station, to_station, time, product_description=args.train_product, exclude_canceled=args.exclude_canceled_trains, ) print_values(train_stop) elif args.method == GET_WEATHER: if args.station is None: raise ValueError( '-station is required with name of Weather station\ (ex. -station "Nöbbele")' ) weather = await weather_api.async_get_weather(args.station) print_values(weather) elif args.method == GET_FERRY_ROUTE: if args.route is None: raise ValueError( '-route is required with name of Ferry route\ (ex. -route "Ekeröleden")' ) route = await ferry_api.async_get_ferry_route(args.route) print_values(route) elif args.method == SEARCH_FOR_FERRY_ROUTE: if args.route is None: raise ValueError("-route is required") routes = await ferry_api.async_search_ferry_routes(args.route) for route in routes: print_values(route) print(f"{route.name} {route.id}") elif args.method == GET_NEXT_FERRY_STOP: if args.from_harbor is None: raise ValueError( '-from-harbor is required with name of Ferry harbor\ (ex. -from-harbor "Ekerö")' ) if args.date_time is not None: time = datetime.strptime(args.date_time, DATE_TIME_INPUT) else: time = datetime.now() ferry_stop = await ferry_api.async_get_next_ferry_stop( args.from_harbor, args.to_harbor, time ) print_values(ferry_stop) def print_values(result: Any) -> None: """Print out values for all object members.""" print(json.dumps(result.__dict__, indent=4, ensure_ascii=False)) def main() -> None: """Initialize the loop.""" loop = asyncio.get_event_loop() loop.run_until_complete(async_main(loop)) gjohansson-ST-pytrafikverket-a4c9790/pytrafikverket/exceptions.py000066400000000000000000000023101455530460300254270ustar00rootroot00000000000000"""Exceptions for Trafikverket.""" from __future__ import annotations class NoCameraFound(Exception): """Error found no camera.""" class MultipleCamerasFound(Exception): """Error found multiple cameras.""" class NoRouteFound(Exception): """Error found no ferry route.""" class MultipleRoutesFound(Exception): """Error found multiple ferry routes.""" class NoFerryFound(Exception): """Error found no ferry.""" class NoDeviationFound(Exception): """Error found no deviation.""" class MultipleDeviationsFound(Exception): """Error found multiple deviations.""" class NoWeatherStationFound(Exception): """Error found no weather station.""" class MultipleWeatherStationsFound(Exception): """Error found multiple weather stations.""" class NoTrainStationFound(Exception): """Error found no train station.""" class MultipleTrainStationsFound(Exception): """Error found multiple train stations.""" class NoTrainAnnouncementFound(Exception): """Error found no train announcement.""" class InvalidAuthentication(Exception): """Error found multiple train announcements.""" class UnknownError(Exception): """Error found multiple train announcements.""" gjohansson-ST-pytrafikverket-a4c9790/pytrafikverket/models.py000066400000000000000000000057751455530460300245530ustar00rootroot00000000000000"""Data classes for Trafikverket.""" from __future__ import annotations from dataclasses import dataclass from datetime import datetime @dataclass class CameraInfoModel: # pylint: disable=R0902 """Dataclass for Trafikverket Camera.""" camera_name: str | None camera_id: str | None active: bool deleted: bool description: str | None direction: str | None fullsizephoto: bool location: str | None modified: datetime | None phototime: datetime | None photourl: str | None status: str | None camera_type: str | None @dataclass class FerryRouteInfoModel: # pylint: disable=R0902 """Dataclass for Trafikverket Ferry route info.""" ferry_route_id: str | None name: str | None short_name: str | None route_type: str | None @dataclass class DeviationInfoModel: # pylint: disable=R0902 """Dataclass for Trafikverket Ferry deviations.""" deviation_id: str | None header: str | None message: str | None start_time: datetime | None end_time: datetime | None icon_id: str | None location_desc: str | None @dataclass class FerryStopModel: # pylint: disable=R0902 """Dataclass for Trafikverket Ferry stop.""" ferry_stop_id: str | None deleted: bool departure_time: datetime | None other_information: list[str] | None deviation_id: list[str] | None modified_time: datetime | None from_harbor_name: str | None to_harbor_name: str | None @dataclass class StationInfoModel: # pylint: disable=R0902 """Dataclass for Trafikverket Train Station info.""" signature: str | None name: str | None advertised: str | None @dataclass class TrainStopModel: # pylint: disable=R0902 """Dataclass for Trafikverket Train stop.""" train_stop_id: str | None canceled: bool advertised_time_at_location: datetime | None estimated_time_at_location: datetime | None time_at_location: datetime | None other_information: list[str] | None deviations: list[str] | None modified_time: datetime | None product_description: list[str] | None @dataclass class WeatherStationInfoModel: # pylint: disable=R0902 """Dataclass for Trafikverket Weather info.""" weather_station_id: str station_name: str road_temp: float | None # celsius air_temp: float | None # celsius dew_point: float | None # celsius humidity: float | None # % visible_distance: float | None # meter precipitationtype: str | None raining: bool snowing: bool road_ice: bool road_ice_depth: float | None # mm road_snow: bool road_snow_depth: float | None # mm road_water: bool road_water_depth: float | None # mm road_water_equivalent_depth: float | None # mm winddirection: str | None # degrees wind_height: int | None # m windforce: float | None # m/s windforcemax: float | None # m/s measure_time: datetime | None precipitation_amount: float | None # mm/30min translated to mm/h modified_time: datetime | None gjohansson-ST-pytrafikverket-a4c9790/pytrafikverket/py.typed000066400000000000000000000000001455530460300243650ustar00rootroot00000000000000gjohansson-ST-pytrafikverket-a4c9790/pytrafikverket/trafikverket.py000066400000000000000000000225511455530460300257600ustar00rootroot00000000000000"""Module for communication with Trafikverket official API.""" from __future__ import annotations from abc import ABCMeta, abstractmethod from datetime import datetime from enum import Enum from typing import Any, cast import logging import aiohttp from lxml import etree from .exceptions import InvalidAuthentication, UnknownError LOGGER = logging.getLogger(__name__) class FilterOperation(Enum): """Contains all field filter operations.""" EQUAL = "EQ" EXISTS = "EXISTS" GREATER_THAN = "GT" GREATER_THAN_EQUAL = "GTE" LESS_THAN = "LT" LESS_THAN_EQUAL = "LTE" NOT_EQUAL = "NE" LIKE = "LIKE" NOT_LIKE = "NOTLIKE" # IN = "IN" NOT_IN = "NOTIN" WITH_IN = "WITHIN" class SortOrder(Enum): """Specifies how rows of data are sorted.""" ASCENDING = "asc" DECENDING = "desc" class FieldSort: """What field and how to sort on it.""" def __init__(self, field: str, sort_order: SortOrder) -> None: """Initialize the class.""" self._field = field self._sort_order = sort_order def to_string(self) -> str: """Sort_order as string.""" return self._field + " " + self._sort_order.value class Filter: """Base class for all filters.""" __metaclass__ = ABCMeta @abstractmethod def generate_node(self, parent_node: etree._Element) -> Any: """Generate node.""" class FieldFilter(Filter): """Used to filter on one field.""" def __init__(self, operation: FilterOperation, name: str, value: Any) -> None: """Initialize the class.""" self.operation = operation self.name = name self.value = value def generate_node(self, parent_node: etree._Element) -> Any: """Return element node for field filter.""" filter_node: etree._Element = etree.SubElement( parent_node, self.operation.value ) filter_node.attrib["name"] = self.name filter_node.attrib["value"] = self.value return filter_node class OrFilter(Filter): """Used to create a Or filter.""" def __init__(self, filters: list[Filter]) -> None: """Initialize the class.""" self.filters = filters def generate_node(self, parent_node: Any) -> Any: """Return element node for filter.""" or_node: etree._Element = etree.SubElement(parent_node, "OR") for sub_filter in self.filters: sub_filter.generate_node(or_node) return or_node class AndFilter(Filter): """Used to create a And filter.""" def __init__(self, filters: list[Filter]) -> None: """Initialize the class.""" self.filters = filters def generate_node(self, parent_node: Any) -> etree._Element: """Return element node for filter.""" or_node: etree._Element = etree.SubElement(parent_node, "AND") for sub_filter in self.filters: sub_filter.generate_node(or_node) return or_node class Trafikverket: """Class used to communicate with trafikverket api.""" _api_url = "https://api.trafikinfo.trafikverket.se/v2/data.xml" date_time_format = "%Y-%m-%dT%H:%M:%S.%f%z" date_time_format_for_modified = "%Y-%m-%dT%H:%M:%S.%fZ" def __init__(self, client_session: aiohttp.ClientSession, api_key: str) -> None: """Initialize TrafikInfo object.""" self._client_session = client_session self._api_key = api_key def _generate_request_data( self, objecttype: str, schemaversion: str, includes: list[str], filters: list[Filter], limit: int | None = None, sorting: list[FieldSort] | None = None, ) -> etree._Element: root_node = etree.Element("REQUEST") login_node = etree.SubElement(root_node, "LOGIN") login_node.attrib["authenticationkey"] = self._api_key query_node = etree.SubElement(root_node, "QUERY") query_node.attrib["objecttype"] = objecttype query_node.attrib["schemaversion"] = schemaversion if limit is not None: query_node.attrib["limit"] = str(limit) if sorting is not None and len(sorting) > 0: query_node.attrib["orderby"] = ", ".join([fs.to_string() for fs in sorting]) for include in includes: include_node = etree.SubElement(query_node, "INCLUDE") include_node.text = include filters_node = etree.SubElement(query_node, "FILTER") for _filter in filters: _filter.generate_node(filters_node) return root_node async def async_make_request( # pylint: disable=too-many-locals self, objecttype: str, schemaversion: str, includes: list[str], filters: list[Filter | FieldFilter], limit: int | None = None, sorting: list[FieldSort] | None = None, ) -> list[etree._ElementTree]: """Send request to trafikverket api and return a element node.""" request_data = self._generate_request_data( objecttype, schemaversion, includes, filters, limit, sorting ) request_data_text = etree.tostring(request_data, pretty_print=False) LOGGER.debug("Sending query with: %s", request_data_text) headers = {"content-type": "text/xml"} async with self._client_session.post( Trafikverket._api_url, data=request_data_text, headers=headers ) as response: content = await response.text() LOGGER.debug("Response recieved withwith: %s", content) error_nodes = etree.fromstring(content).xpath("/RESPONSE/RESULT/ERROR") if len(error_nodes) > 0: error_node = error_nodes[0] helper = NodeHelper(error_node) source = helper.get_text("SOURCE") message = helper.get_text("MESSAGE") if response.status == 401: raise InvalidAuthentication( f"Source: {source}, message: {message}" ", status: {response.status}" ) raise UnknownError( f"Source: {source}, message: {message}" ", status: {response.status}" ) result: list[etree._ElementTree] = etree.fromstring(content).xpath( "/RESPONSE/RESULT/" + objecttype ) return result class NodeHelper: """Helper class to get node content.""" def __init__(self, node: etree._ElementTree) -> None: """Initialize the class.""" self._node = node def get_text(self, field: str) -> str | None: """Return the text in 'field' from the node or None if not found.""" nodes: list[etree._Element] | None = self._node.xpath(field) if nodes is None: return None if len(nodes) == 0: return None if len(nodes) > 1: raise ValueError("Found multiple nodes should only 0 or 1 is allowed") value = nodes[0].text return value def get_number(self, field: str) -> float | None: """Return the number in 'field' from the node or None if not found.""" nodes: list[etree._Element] | None = self._node.xpath(field) if nodes is None: return None if len(nodes) == 0: return None if len(nodes) > 1: raise ValueError("Found multiple nodes should only 0 or 1 is allowed") try: value = float(nodes[0].text) except ValueError: return None return value def get_texts(self, field: str) -> list[str] | None: """Return a list of texts from the node selected by 'field' or None.""" nodes: list[etree._Element] | None = self._node.xpath(field) if nodes is None: return None result = [] for line in nodes: result.append(line.text) return result def get_datetime_for_modified(self, field: str) -> datetime | None: """Return datetime object from node, selected by 'field'. Format of the text is expected to be modifiedTime-format. """ nodes: list[etree._Element] | None = self._node.xpath(field) if nodes is None: return None if len(nodes) == 0: return None if len(nodes) > 1: raise ValueError("Found multiple nodes should only 0 or 1 is allowed") return datetime.strptime( nodes[0].text, Trafikverket.date_time_format_for_modified ) def get_datetime(self, field: str) -> datetime | None: """Return a datetime object from node, selected by 'field'.""" nodes: list[etree._Element] | None = self._node.xpath(field) if nodes is None: return None if len(nodes) == 0: return None if len(nodes) > 1: raise ValueError("Found multiple nodes should only 0 or 1 is allowed") return datetime.strptime(nodes[0].text, Trafikverket.date_time_format) def get_bool(self, field: str) -> bool: """Return True if value selected by field is 'true' else returns False.""" nodes: list[etree._Element] | None = self._node.xpath(field) if nodes is None: return False if len(nodes) == 0: return False if len(nodes) > 1: raise ValueError("Found multiple nodes should only 0 or 1 is allowed") value = nodes[0].text.lower() == "true" return value gjohansson-ST-pytrafikverket-a4c9790/pytrafikverket/trafikverket_camera.py000066400000000000000000000115161455530460300272670ustar00rootroot00000000000000"""Retrieve camera data from Trafikverket API.""" from __future__ import annotations from datetime import datetime import aiohttp from lxml import etree from .exceptions import MultipleCamerasFound, NoCameraFound from .trafikverket import ( FieldFilter, FilterOperation, NodeHelper, OrFilter, Trafikverket, ) CAMERA_INFO_REQUIRED_FIELDS = [ "Name", "Id", "Active", "Deleted", "Description", "Direction", "HasFullSizePhoto", "Location", "ModifiedTime", "PhotoTime", "PhotoUrl", "Status", "Type", ] class CameraInfo: # pylint: disable=R0902 """Fetch Camera data.""" def __init__( # pylint: disable=R0913 self, camera_name: str | None, camera_id: str | None, active: bool, deleted: bool, description: str | None, direction: str | None, fullsizephoto: bool, location: str | None, modified: datetime | None, phototime: datetime | None, photourl: str | None, status: str | None, camera_type: str | None, ) -> None: """Initialize the class.""" self.camera_name = camera_name self.camera_id = camera_id self.active = active self.deleted = deleted self.description = description self.direction = direction self.fullsizephoto = fullsizephoto self.location = location self.modified = modified self.phototime = phototime self.photourl = photourl self.status = status self.camera_type = camera_type @classmethod def from_xml_node( cls, node: etree._ElementTree ) -> CameraInfo: # pylint: disable=too-many-locals """Map XML path for values.""" node_helper = NodeHelper(node) camera_name = node_helper.get_text("Name") camera_id = node_helper.get_text("Id") active = node_helper.get_bool("Active") deleted = node_helper.get_bool("Deleted") description = node_helper.get_text("Description") direction = node_helper.get_text("Direction") fullsizephoto = node_helper.get_bool("HasFullSizePhoto") location = node_helper.get_text("Location") modified = node_helper.get_datetime_for_modified("ModifiedTime") phototime = node_helper.get_datetime("PhotoTime") photourl = node_helper.get_text("PhotoUrl") status = node_helper.get_text("Status") camera_type = node_helper.get_text("Type") return cls( camera_name, camera_id, active, deleted, description, direction, fullsizephoto, location, modified, phototime, photourl, status, camera_type, ) class TrafikverketCamera: """Class used to communicate with trafikverket's camera api.""" def __init__(self, client_session: aiohttp.ClientSession, api_key: str) -> None: """Initialize Camera object.""" self._api = Trafikverket(client_session, api_key) async def async_get_camera(self, search_string: str) -> CameraInfo: """Retrieve camera from API.""" cameras = await self._api.async_make_request( "Camera", "1.0", CAMERA_INFO_REQUIRED_FIELDS, [ OrFilter( [ FieldFilter(FilterOperation.LIKE, "Name", search_string), FieldFilter(FilterOperation.LIKE, "Location", search_string), FieldFilter(FilterOperation.LIKE, "Id", search_string), ] ) ], ) if len(cameras) == 0: raise NoCameraFound("Could not find a camera with the specified name") if len(cameras) > 1: raise MultipleCamerasFound("Found multiple camera with the specified name") return CameraInfo.from_xml_node(cameras[0]) async def async_get_cameras(self, search_string: str) -> list[CameraInfo]: """Retrieve multipple cameras from API.""" cameras = await self._api.async_make_request( "Camera", "1.0", CAMERA_INFO_REQUIRED_FIELDS, [ OrFilter( [ FieldFilter(FilterOperation.LIKE, "Name", search_string), FieldFilter(FilterOperation.LIKE, "Location", search_string), FieldFilter(FilterOperation.LIKE, "Id", search_string), ] ) ], ) if len(cameras) == 0: raise NoCameraFound("Could not find a camera with the specified name") camera_list = [] for camera in cameras: camera_list.append(CameraInfo.from_xml_node(camera)) return camera_list gjohansson-ST-pytrafikverket-a4c9790/pytrafikverket/trafikverket_ferry.py000066400000000000000000000230571455530460300271710ustar00rootroot00000000000000"""Enables retreival of ferry departure information from Trafikverket API.""" from __future__ import annotations from datetime import datetime from enum import Enum import aiohttp from lxml import etree from pytrafikverket.trafikverket import ( FieldFilter, FieldSort, Filter, FilterOperation, NodeHelper, SortOrder, Trafikverket, ) from .exceptions import ( MultipleDeviationsFound, MultipleRoutesFound, NoDeviationFound, NoFerryFound, NoRouteFound, ) # pylint: disable=W0622, C0103 ROUTE_INFO_REQUIRED_FIELDS = ["Id", "Name", "Shortname", "Type.Name"] DEVIATION_INFO_REQUIRED_FIELDS = [ "Deviation.Id", "Deviation.Header", "Deviation.EndTime", "Deviation.StartTime", "Deviation.Message", "Deviation.IconId", "Deviation.LocationDescriptor", ] FERRY_STOP_REQUIRED_FIELDS = [ "Id", "Deleted", "DepartureTime", "Route.Name", "DeviationId", "ModifiedTime", "FromHarbor", "ToHarbor", "Info", ] class RouteInfo: """Contains information about a FerryRoute.""" def __init__( self, id: str | None, name: str | None, short_name: str | None, route_type: str | None, ) -> None: """Initialize RouteInfo class.""" self.id = id self.name = name self.short_name = short_name self.route_type = route_type @classmethod def from_xml_node(cls, node: etree._ElementTree) -> RouteInfo: """Map route information in XML data.""" node_helper = NodeHelper(node) id = node_helper.get_text("Id") name = node_helper.get_text("Name") short_name = node_helper.get_text("Shortname") route_type = node_helper.get_text("Type/Name") return cls(id, name, short_name, route_type) class DeviationInfo: """Contains information about a Situation/Deviation.""" def __init__( self, id: str | None, header: str | None, message: str | None, start_time: datetime | None, end_time: datetime | None, icon_id: str | None, location_desc: str | None, ) -> None: """Initialize DeviationInfo class.""" self.id = id self.header = header self.message = message self.start_time = start_time self.end_time = end_time self.icon_id = icon_id self.location_desc = location_desc @classmethod def from_xml_node(cls, node: etree._ElementTree) -> DeviationInfo: """Map deviation information in XML data.""" node_helper = NodeHelper(node) id = node_helper.get_text("Deviation/Id") header = node_helper.get_text("Deviation/Header") message = node_helper.get_text("Deviation/Message") start_time = node_helper.get_datetime("Deviation/StartTime") end_time = node_helper.get_datetime("Deviation/EndTime") icon_id = node_helper.get_text("Deviation/IconId") location_desc = node_helper.get_text("Deviation/LocationDescriptor") return cls(id, header, message, start_time, end_time, icon_id, location_desc) class FerryStopStatus(Enum): """Contain the different ferry stop statuses.""" ON_TIME = "on_time" CANCELED = "canceled" DELETED = "deleted" class FerryStop: # pylint: disable=R0902 """Contain information about a ferry departure.""" def __init__( self, id: str | None, deleted: bool, departure_time: datetime | None, other_information: list[str] | None, deviation_id: list[str] | None, modified_time: datetime | None, from_harbor_name: str | None, to_harbor_name: str | None, ) -> None: """Initialize FerryStop.""" self.id = id self.deleted = deleted self.departure_time = departure_time self.other_information = other_information self.deviation_id = deviation_id self.modified_time = modified_time self.from_harbor_name = from_harbor_name self.to_harbor_name = to_harbor_name def get_state(self) -> FerryStopStatus: """Retrieve the state of the departure.""" if self.deleted: return FerryStopStatus.DELETED return FerryStopStatus.ON_TIME @classmethod def from_xml_node(cls, node: etree._ElementTree) -> FerryStop: """Map the path in the return XML data.""" node_helper = NodeHelper(node) id = node_helper.get_text("Id") deleted = node_helper.get_bool("Deleted") departure_time = node_helper.get_datetime("DepartureTime") other_information = node_helper.get_texts("Info") deviation_id = node_helper.get_texts("DeviationId") modified_time = node_helper.get_datetime_for_modified("ModifiedTime") from_harbor_name = node_helper.get_text("FromHarbor/Name") to_harbor_name = node_helper.get_text("ToHarbor/Name") return cls( id, deleted, departure_time, other_information, deviation_id, modified_time, from_harbor_name, to_harbor_name, ) class TrafikverketFerry: """Class used to communicate with trafikverket's ferry route api.""" def __init__(self, client_session: aiohttp.ClientSession, api_key: str) -> None: """Initialize FerryInfo object.""" self._api = Trafikverket(client_session, api_key) async def async_get_ferry_route(self, route_name: str) -> RouteInfo: """Retreive ferry route id based on name.""" routes = await self._api.async_make_request( "FerryRoute", "1.2", ROUTE_INFO_REQUIRED_FIELDS, [FieldFilter(FilterOperation.EQUAL, "Name", route_name)], ) if len(routes) == 0: raise NoRouteFound("Could not find a route with the specified name") if len(routes) > 1: raise MultipleRoutesFound("Found multiple routes with the specified name") return RouteInfo.from_xml_node(routes[0]) async def async_get_ferry_route_id(self, route_id: int) -> RouteInfo: """Retreive ferry route id based on routeId.""" routes = await self._api.async_make_request( "FerryRoute", "1.2", ROUTE_INFO_REQUIRED_FIELDS, [FieldFilter(FilterOperation.EQUAL, "Id", str(route_id))], ) if len(routes) == 0: raise NoRouteFound("Could not find a route with the specified name") if len(routes) > 1: raise MultipleRoutesFound("Found multiple routes with the specified name") return RouteInfo.from_xml_node(routes[0]) async def async_search_ferry_routes(self, name: str) -> list[RouteInfo]: """Search for ferry routes based on the route name.""" routes = await self._api.async_make_request( "FerryRoute", "1.2", ROUTE_INFO_REQUIRED_FIELDS, [FieldFilter(FilterOperation.LIKE, "Name", name)], ) if len(routes) == 0: raise NoRouteFound("Could not find a ferry route with the specified name") result = [] for route in routes: result.append(RouteInfo.from_xml_node(route)) return result async def async_get_next_ferry_stops( self, from_harbor_name: str, to_harnbor_name: str = "", after_time: datetime = datetime.now(), number_of_stops: int = 1, ) -> list[FerryStop]: """Enable retreival of next departures.""" date_as_text = after_time.strftime(Trafikverket.date_time_format) filters: list[FieldFilter | Filter] = [ FieldFilter(FilterOperation.EQUAL, "FromHarbor.Name", from_harbor_name), FieldFilter( FilterOperation.GREATER_THAN_EQUAL, "DepartureTime", date_as_text ), ] if to_harnbor_name: filters.append( FieldFilter(FilterOperation.EQUAL, "ToHarbor.Name", to_harnbor_name) ) sorting = [FieldSort("DepartureTime", SortOrder.ASCENDING)] ferry_announcements = await self._api.async_make_request( "FerryAnnouncement", "1.2", FERRY_STOP_REQUIRED_FIELDS, filters, number_of_stops, sorting, ) if len(ferry_announcements) == 0: raise NoFerryFound("No FerryAnnouncement found") stops = [] for announcement in ferry_announcements: stops.append(FerryStop.from_xml_node(announcement)) return stops async def async_get_next_ferry_stop( self, from_harbor_name: str, to_harnbor_name: str = "", after_time: datetime = datetime.now(), ) -> FerryStop: """Enable retreival of next departure.""" stops = await self.async_get_next_ferry_stops( from_harbor_name, to_harnbor_name, after_time, 1 ) return stops[0] async def async_get_deviation(self, id: str) -> DeviationInfo: """Retreive deviation info from Deviation Id.""" filters: list[FieldFilter | Filter] = [ FieldFilter(FilterOperation.EQUAL, "Deviation.Id", id) ] deviations = await self._api.async_make_request( "Situation", "1.5", DEVIATION_INFO_REQUIRED_FIELDS, filters, ) if len(deviations) == 0: raise NoDeviationFound("No Deviation found") if len(deviations) > 1: raise MultipleDeviationsFound("Multiple Deviations found") deviation = deviations[0] return DeviationInfo.from_xml_node(deviation) gjohansson-ST-pytrafikverket-a4c9790/pytrafikverket/trafikverket_train.py000066400000000000000000000301171455530460300271520ustar00rootroot00000000000000"""Enables retreival of train departure information from Trafikverket API.""" from __future__ import annotations from datetime import datetime, timedelta from enum import Enum import aiohttp from lxml import etree from .exceptions import ( MultipleTrainStationsFound, NoTrainAnnouncementFound, NoTrainStationFound, ) from .trafikverket import ( FieldFilter, FieldSort, FilterOperation, NodeHelper, OrFilter, SortOrder, Trafikverket, ) # pylint: disable=W0622, C0103 STATION_INFO_REQUIRED_FIELDS = ["LocationSignature", "AdvertisedLocationName"] TRAIN_STOP_REQUIRED_FIELDS = [ "ActivityId", "Canceled", "AdvertisedTimeAtLocation", "EstimatedTimeAtLocation", "TimeAtLocation", "OtherInformation", "Deviation", "ModifiedTime", "ProductInformation", ] class StationInfo: """Contains information about a train station.""" def __init__( self, signature: str | None, name: str | None, advertised: str | None ) -> None: """Initialize StationInfo class.""" self.signature = signature self.name = name self.advertised = advertised @classmethod def from_xml_node(cls, node: etree._ElementTree) -> StationInfo: """Map station information in XML data.""" node_helper = NodeHelper(node) location_signature = node_helper.get_text("LocationSignature") advertised_location_name = node_helper.get_text("AdvertisedLocationName") location_advertised = node_helper.get_text("Advertised") return cls(location_signature, advertised_location_name, location_advertised) class TrainStopStatus(Enum): """Contain the different train stop statuses.""" ON_TIME = "on_time" DELAYED = "delayed" CANCELED = "canceled" class TrainStop: # pylint: disable=too-many-instance-attributes """Contain information about a train stop.""" def __init__( self, id: str | None, canceled: bool, advertised_time_at_location: datetime | None, estimated_time_at_location: datetime | None, time_at_location: datetime | None, other_information: list[str] | None, deviations: list[str] | None, modified_time: datetime | None, product_description: list[str] | None, ) -> None: """Initialize TrainStop.""" self.id = id self.canceled = canceled self.advertised_time_at_location = advertised_time_at_location self.estimated_time_at_location = estimated_time_at_location self.time_at_location = time_at_location self.other_information = other_information self.deviations = deviations self.modified_time = modified_time self.product_description = product_description def get_state(self) -> TrainStopStatus: """Retrieve the state of the departure.""" if self.canceled: return TrainStopStatus.CANCELED if ( self.advertised_time_at_location is not None and self.time_at_location is not None and self.advertised_time_at_location != self.time_at_location ): return TrainStopStatus.DELAYED if ( self.advertised_time_at_location is not None and self.estimated_time_at_location is not None and self.advertised_time_at_location != self.estimated_time_at_location ): return TrainStopStatus.DELAYED return TrainStopStatus.ON_TIME def get_delay_time(self) -> timedelta | None: """Calculate the delay of a departure.""" if self.canceled: return None if ( self.advertised_time_at_location is not None and self.time_at_location is not None and self.advertised_time_at_location != self.time_at_location ): return self.time_at_location - self.advertised_time_at_location if ( self.advertised_time_at_location is not None and self.estimated_time_at_location is not None and self.advertised_time_at_location != self.estimated_time_at_location ): return self.estimated_time_at_location - self.advertised_time_at_location return None @classmethod def from_xml_node(cls, node: etree._ElementTree) -> TrainStop: """Map the path in the return XML data.""" node_helper = NodeHelper(node) activity_id = node_helper.get_text("ActivityId") canceled = node_helper.get_bool("Canceled") advertised_time_at_location = node_helper.get_datetime( "AdvertisedTimeAtLocation" ) estimated_time_at_location = node_helper.get_datetime("EstimatedTimeAtLocation") time_at_location = node_helper.get_datetime("TimeAtLocation") other_information = node_helper.get_texts("OtherInformation/Description") deviations = node_helper.get_texts("Deviation/Description") modified_time = node_helper.get_datetime_for_modified("ModifiedTime") product_description = node_helper.get_texts("ProductInformation/Description") return cls( activity_id, canceled, advertised_time_at_location, estimated_time_at_location, time_at_location, other_information, deviations, modified_time, product_description, ) class TrafikverketTrain: """Class used to communicate with trafikverket's train api.""" def __init__(self, client_session: aiohttp.ClientSession, api_key: str) -> None: """Initialize TrainInfo object.""" self._api = Trafikverket(client_session, api_key) async def async_get_train_station(self, location_name: str) -> StationInfo: """Retreive train station id based on name.""" train_stations = await self._api.async_make_request( "TrainStation", "1.4", STATION_INFO_REQUIRED_FIELDS, [ FieldFilter( FilterOperation.EQUAL, "AdvertisedLocationName", location_name ), FieldFilter(FilterOperation.EQUAL, "Advertised", "true"), ], ) if len(train_stations) == 0: raise NoTrainStationFound( "Could not find a station with the specified name" ) if len(train_stations) > 1: raise MultipleTrainStationsFound( "Found multiple stations with the specified name" ) return StationInfo.from_xml_node(train_stations[0]) async def async_search_train_stations( self, location_name: str ) -> list[StationInfo]: """Search for train stations.""" train_stations = await self._api.async_make_request( "TrainStation", "1.4", ["AdvertisedLocationName", "LocationSignature", "Advertised", "Deleted"], [ FieldFilter( FilterOperation.LIKE, "AdvertisedLocationName", location_name ), FieldFilter(FilterOperation.EQUAL, "Advertised", "true"), ], ) if len(train_stations) == 0: raise NoTrainStationFound( "Could not find a station with the specified name" ) result = [] for train_station in train_stations: result.append(StationInfo.from_xml_node(train_station)) return result async def async_get_train_stop( self, from_station: StationInfo, to_station: StationInfo, time_at_location: datetime, product_description: str | None = None, exclude_canceled: bool = False, ) -> TrainStop: """Retrieve the train stop.""" date_as_text = time_at_location.strftime(Trafikverket.date_time_format) filters = [ FieldFilter(FilterOperation.EQUAL, "ActivityType", "Avgang"), FieldFilter( FilterOperation.EQUAL, "LocationSignature", from_station.signature ), FieldFilter( FilterOperation.EQUAL, "AdvertisedTimeAtLocation", date_as_text ), OrFilter( [ FieldFilter( FilterOperation.EQUAL, "ViaToLocation.LocationName", to_station.signature, ), FieldFilter( FilterOperation.EQUAL, "ToLocation.LocationName", to_station.signature, ), ] ), ] if product_description: filters.append( FieldFilter( FilterOperation.LIKE, "ProductInformation.Description", product_description, ) ) if exclude_canceled: filters.append(FieldFilter(FilterOperation.EQUAL, "Canceled", "false")) train_announcements = await self._api.async_make_request( "TrainAnnouncement", "1.8", TRAIN_STOP_REQUIRED_FIELDS, filters, 1, ) if len(train_announcements) == 0: raise NoTrainAnnouncementFound("No TrainAnnouncement found") train_announcement = train_announcements[0] return TrainStop.from_xml_node(train_announcement) async def async_get_next_train_stops( self, from_station: StationInfo, to_station: StationInfo, after_time: datetime, product_description: str | None = None, exclude_canceled: bool = False, number_of_stops: int = 1, ) -> list[TrainStop]: """Enable retreival of next departures.""" date_as_text = after_time.strftime(Trafikverket.date_time_format) filters = [ FieldFilter(FilterOperation.EQUAL, "ActivityType", "Avgang"), FieldFilter( FilterOperation.EQUAL, "LocationSignature", from_station.signature ), FieldFilter( FilterOperation.GREATER_THAN_EQUAL, "AdvertisedTimeAtLocation", date_as_text, ), OrFilter( [ FieldFilter( FilterOperation.EQUAL, "ViaToLocation.LocationName", to_station.signature, ), FieldFilter( FilterOperation.EQUAL, "ToLocation.LocationName", to_station.signature, ), ] ), ] if product_description: filters.append( FieldFilter( FilterOperation.LIKE, "ProductInformation.Description", product_description, ) ) if exclude_canceled: filters.append(FieldFilter(FilterOperation.EQUAL, "Canceled", "false")) sorting = [FieldSort("AdvertisedTimeAtLocation", SortOrder.ASCENDING)] train_announcements = await self._api.async_make_request( "TrainAnnouncement", "1.8", TRAIN_STOP_REQUIRED_FIELDS, filters, number_of_stops, sorting, ) if len(train_announcements) == 0: raise NoTrainAnnouncementFound("No TrainAnnouncement found") stops = [] for announcement in train_announcements: stops.append(TrainStop.from_xml_node(announcement)) return stops async def async_get_next_train_stop( self, from_station: StationInfo, to_station: StationInfo, after_time: datetime, product_description: str | None = None, exclude_canceled: bool = False, ) -> TrainStop: """Enable retreival of next departure.""" stops = await self.async_get_next_train_stops( from_station, to_station, after_time, product_description, exclude_canceled, 1, ) return stops[0] gjohansson-ST-pytrafikverket-a4c9790/pytrafikverket/trafikverket_weather.py000066400000000000000000000221521455530460300274740ustar00rootroot00000000000000"""Retrieve weather station data from Trafikverket API.""" from __future__ import annotations from datetime import datetime import aiohttp from lxml import etree from .exceptions import MultipleWeatherStationsFound, NoWeatherStationFound from .trafikverket import FieldFilter, FilterOperation, NodeHelper, Trafikverket WEATHER_REQUIRED_FIELDS = [ "Name", # string, replaced "Id", # string, replaced "ModifiedTime", # datetime, new, Tidpunkt då dataposten ändrades i cachen "Observation.Sample", # datetime, replaced, Tidpunkt som observationen avser, inklusive tidzon för att hantera sommartid och normaltid. "Observation.Air.Temperature.Value", # float, replaced, Lufttemperatur. Value [C] "Observation.Air.RelativeHumidity.Value", # float, replaced, Relativ luftfuktighet. Andel av den fukt som luften kan bära. Vid 100% är luften mättad. Value [%] "Observation.Air.Dewpoint.Value", # float, new, Daggpunkt, den temperatur där vatten kondenserar. Value [C] "Observation.Air.VisibleDistance.Value", # float, new, Den sträcka det finns sikt. Value [m] "Observation.Wind.Direction.Value", # int, replaced, Mått på vindriktning vid en viss tidpunkt. Medelvärde över tiominutersperiod t.o.m. tidpunkten. Value [grader] "Observation.Wind.Height", # int, new, Vindsensorns höjdplacering [m] "Observation.Wind.Speed.Value", # float, replaced, Mått på vindhastighet vid en viss tidpunkt. Medelvärde över tiominutersperiod t.o.m. tidpunkten. Value [m/s] "Observation.Aggregated30minutes.Wind.SpeedMax.Value", # float, replaced, Högst uppmätt 3-sekundersmedelvärde under perioden. Value [m/s] "Observation.Weather.Precipitation", # string, replaced, Vilken typ av nederbörd som detekterats "Observation.Aggregated30minutes.Precipitation.TotalWaterEquivalent.Value", # float, replaced, Mängd vatten som nederbörden under perioden motsvarar. Value [mm] "Observation.Aggregated30minutes.Precipitation.Rain", # bool, new, Förekomst av regn. "Observation.Aggregated30minutes.Precipitation.Snow", # bool, new, Förekomst av snö. "Observation.Surface.Temperature.Value", # float, replaced, Vägytans temperatur. Value [C] "Observation.Surface.Ice", # bool, new, Förekomst av is på vägytan. "Observation.Surface.IceDepth.Value", # float, new, Isdjup på vägytan. Value [mm] "Observation.Surface.Snow", # bool, new, Förekomst av snö på vägytan. "Observation.Surface.SnowDepth.Solid.Value", # float, new, Mängd snö. Value [mm] "Observation.Surface.SnowDepth.WaterEquivalent.Value", # float, new, Mängd vatten som snön motsvarar i smält form. Value [mm] "Observation.Surface.Water", # bool, new, Förekomst av vatten på vägytan. "Observation.Surface.WaterDepth.Value", # float, new, Vattendjup på vägytan. Value [mm] ] """ Precipitation possible values are: no rain freezing_rain snow sleet yes """ class WeatherStationInfo: # pylint: disable=R0902 """Fetch Weather data from specified weather station.""" def __init__( # pylint: disable=R0914, R0913 self, station_name: str, station_id: str, road_temp: float | None, # celsius air_temp: float | None, # celsius dew_point: float | None, # celsius humidity: float | None, # % visible_distance: float | None, # meter precipitationtype: str | None, raining: bool, snowing: bool, road_ice: bool, road_ice_depth: float | None, # mm road_snow: bool, road_snow_depth: float | None, # mm road_water: bool, road_water_depth: float | None, # mm road_water_equivalent_depth: float | None, # mm winddirection: str | None, # degrees wind_height: int | None, # m windforce: float | None, # m/s windforcemax: float | None, # m/s measure_time: datetime | None, precipitation_amount: float | None, # mm/30min translated to mm/h modified_time: datetime | None, ) -> None: """Initialize the class.""" self.station_name = station_name self.station_id = station_id self.road_temp = road_temp self.air_temp = air_temp self.dew_point = dew_point self.humidity = humidity self.visible_distance = visible_distance self.precipitationtype = precipitationtype self.raining = raining self.snowing = snowing self.road_ice = road_ice self.road_ice_depth = road_ice_depth self.road_snow = road_snow self.road_snow_depth = road_snow_depth self.road_water = road_water self.road_water_depth = road_water_depth self.road_water_equivalent_depth = road_water_equivalent_depth self.winddirection = winddirection self.wind_height = wind_height self.windforce = windforce self.windforcemax = windforcemax self.measure_time = measure_time self.precipitation_amount = precipitation_amount self.modified_time = modified_time @classmethod def from_xml_node( cls, node: etree._ElementTree ) -> WeatherStationInfo: # pylint: disable=R0914 """Map XML path for values.""" node_helper = NodeHelper(node) station_name = node_helper.get_text("Name") station_id = node_helper.get_text("Id") air_temp = node_helper.get_number("Observation/Air/Temperature/Value") road_temp = node_helper.get_number("Observation/Surface/Temperature/Value") dew_point = node_helper.get_number("Observation/Air/Dewpoint/Value") humidity = node_helper.get_number("Observation/Air/RelativeHumidity/Value") visible_distance = node_helper.get_number( "Observation/Air/VisibleDistance/Value" ) precipitationtype = node_helper.get_text("Observation/Weather/Precipitation") raining = node_helper.get_bool( "Observation/Aggregated30minutes/Precipitation/Rain" ) snowing = node_helper.get_bool( "Observation/Aggregated30minutes/Precipitation/Snow" ) road_ice = node_helper.get_bool("Observation/Surface/Ice") road_ice_depth = node_helper.get_number("Observation/Surface/IceDepth/Value") road_snow = node_helper.get_bool("Observation/Surface/Snow") road_snow_depth = node_helper.get_number( "Observation/Surface/SnowDepth.Solid/Value" ) road_water = node_helper.get_bool("Observation/Surface/Water") road_water_depth = node_helper.get_number( "Observation/Surface/WaterDepth/Value" ) road_water_equivalent_depth = node_helper.get_number( "Observation/Surface/SnowDepth/WaterEquivalent/Value" ) winddirection = node_helper.get_text("Observation/Wind/Direction/Value") wind_height = node_helper.get_number("Observation/Wind/Height") windforce = node_helper.get_number("Observation/Wind/Speed/Value") windforcemax = node_helper.get_number( "Observation/Aggregated30minutes/Wind/SpeedMax/Value" ) measure_time = node_helper.get_datetime("Observation/Sample") precipitation_amount = node_helper.get_number( "Observation/Aggregated30minutes/Precipitation/TotalWaterEquivalent/Value" ) if precipitation_amount: precipitation_amount = precipitation_amount * 2 # mm/30min to mm/h modified_time = node_helper.get_datetime_for_modified("ModifiedTime") return cls( station_name, station_id, road_temp, air_temp, dew_point, humidity, visible_distance, precipitationtype, raining, snowing, road_ice, road_ice_depth, road_snow, road_snow_depth, road_water, road_water_depth, road_water_equivalent_depth, winddirection, wind_height, windforce, windforcemax, measure_time, precipitation_amount, modified_time, ) class TrafikverketWeather: """Class used to communicate with trafikverket's weather api.""" def __init__(self, client_session: aiohttp.ClientSession, api_key: str) -> None: """Initialize Weather object.""" self._api = Trafikverket(client_session, api_key) async def async_get_weather(self, location_name: str) -> WeatherStationInfo: """Retrieve weather from API.""" weather_stations = await self._api.async_make_request( "WeatherMeasurepoint", "2.0", WEATHER_REQUIRED_FIELDS, [FieldFilter(FilterOperation.EQUAL, "Name", location_name)], ) if len(weather_stations) == 0: raise NoWeatherStationFound( "Could not find a weather station with the specified name" ) if len(weather_stations) > 1: raise MultipleWeatherStationsFound( "Found multiple weather stations with the specified name" ) return WeatherStationInfo.from_xml_node(weather_stations[0]) gjohansson-ST-pytrafikverket-a4c9790/requirements.txt000066400000000000000000000001761455530460300231160ustar00rootroot00000000000000aiohttp==3.9.1 attrs==23.1.0 chardet==3.0.4 idna>=2.6 idna-ssl>=1.0.1 lxml>=4.9.3 multidict==4.5.0 pip setuptools yarl==1.9.4 gjohansson-ST-pytrafikverket-a4c9790/setup.cfg000066400000000000000000000004631455530460300214520ustar00rootroot00000000000000[flake8] exclude = .venv,venv,.git,.tox,docs,bin,lib,deps,build doctests = True # Default for Black max-line-length = 88 # D202 No blank lines allowed after function docstring # W503: Line break occurred before a binary operator # W504 line break after binary operator ignore = D202, W503, W504 gjohansson-ST-pytrafikverket-a4c9790/setup.py000066400000000000000000000017701455530460300213450ustar00rootroot00000000000000"""Setup for pytrafikverket.""" from setuptools import find_packages, setup with open("README.md", "r", encoding="UTF-8") as fh: long_description = fh.read() setup( name="pytrafikverket", version="0.3.10", description="Retreive values from public API at the Swedish Transport Administration (Trafikverket).", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/gjohansson-ST/pytrafikverket", author="Peter Andersson, Jonas Karlsson, G Johansson", license="MIT", classifiers=[ "Development Status :: 5 - Production/Stable", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3.11", ], install_requires=["aiohttp", "lxml"], packages=find_packages(), include_package_data=True, zip_safe=True, entry_point={ "console_scripts": ["pytrafikverket=pytrafikverket.pytrafikverket:main"] }, package_data={"pytrafikverket": ["py.typed"]}, ) gjohansson-ST-pytrafikverket-a4c9790/upload.ps1000066400000000000000000000001141455530460300215330ustar00rootroot00000000000000py setup.py sdist bdist_wheel pause twine upload dist/* Remove-Item ./dist/*