Skip to content

Commit

Permalink
Add files
Browse files Browse the repository at this point in the history
  • Loading branch information
jotonedev committed Sep 16, 2024
1 parent a3d8005 commit 2377dbd
Show file tree
Hide file tree
Showing 10 changed files with 679 additions and 1 deletion.
225 changes: 225 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,225 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# 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/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839

# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf

# AWS User-specific
.idea/**/aws.xml

# Generated files
.idea/**/contentModel.xml

# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml

# Gradle
.idea/**/gradle.xml
.idea/**/libraries

# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr

# CMake
cmake-build-*/

# Mongo Explorer plugin
.idea/**/mongoSettings.xml

# File-based project format
*.iws

# IntelliJ
out/

# mpeltonen/sbt-idea plugin
.idea_modules/

# JIRA plugin
atlassian-ide-plugin.xml

# Cursive Clojure plugin
.idea/replstate.xml

# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties

# Editor-based Rest Client
.idea/httpRequests

# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser

.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace

# Local History for Visual Studio Code
.history/

# End of https://mrkandreev.name/snippets/gitignore-generator/#Python,PyCharm+all,VisualStudioCode
7 changes: 7 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Copyright 2024 John Toniutti

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.
23 changes: 22 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,22 @@
# pyown
# OpenWebNet parser for Python

This is a Python library to connect and parse OpenWebNet messages from Bticino/Legrand gateways.

Currently it's a WIP, but it's already able to connect to the gateway and parse some messages.

## What is OpenWebNet?

OpenWebNet is a home automation protocol developed by Bticino (now part of Legrand) to control domotic devices like lights, shutters, heating, etc.
It was developed around 2000 and it's still used today in many installations.
It does not implement any encryption, so it's not secure to use it over the internet.
Also many devices implement only the old password algorithm, which is easily bruteforceable.
So, when using OpenWebNet, be sure to use it only in a trusted network and taking security measures, like vlan separation.

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## Acknowledgments

* [openwebnet documentation](https://developer.legrand.com/Documentation/)
* [old password algorithm](https://rosettacode.org/wiki/OpenWebNet_password#Python)
Empty file added pyown/__init__.py
Empty file.
59 changes: 59 additions & 0 deletions pyown/__main__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import asyncio
import argparse

from tqdm import tqdm

from .client import OWNClient
from .message import *
from .constants.who import *


def build_active_power_request(device: str) -> RawMessage:
"""Build the active power request message."""
return RawMessage(["#" + ENERGY_MANAGEMENT, device, "113"])


async def main(host: str, port: int, password: int) -> None:
"""Run the OpenWebNet client."""
client = OWNClient(host, port, password)
await client.connect()


print(f"Connected to {host}:{port}")

# Scan the OpenWebNet bus for energy management devices
while True:
await asyncio.sleep(0.5)
print()
try:
for i in range(1, 4):
who = f"5{i}"

message = build_active_power_request(who)
await client.send(message)
response = await client.recv()

if response == ACK:
continue

if await client.recv() != ACK:
continue

device = int(response.tags[-3])
power = int(response.tags[-1])

print(f"Device: {device}, Power: {power}W")
except KeyboardInterrupt:
break

await client.close()
print("Disconnected")

if __name__ == "__main__":
parser = argparse.ArgumentParser(description="OpenWebNet client")
parser.add_argument("--host", type=str, help="The OpenWebNet gateway IP address", default="192.168.0.120")
parser.add_argument("--port", type=int, help="The OpenWebNet gateway port", default=20000)
parser.add_argument("--password", type=str, help="The OpenWebNet gateway password", default="12345")
args = parser.parse_args()

asyncio.run(main(args.host, args.port, args.password))
55 changes: 55 additions & 0 deletions pyown/auth/open.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
def ownCalcPass(password: str | int, nonce: str, test: bool = False) -> str:
start = True
num1 = 0
num2 = 0

if isinstance(password, str):
password = int(password)

if test:
print("password: %08x" % (password))
for c in nonce :
if c != "0":
if start:
num2 = password
start = False
if test:
print("c: %s num1: %08x num2: %08x" % (c, num1, num2))
if c == '1':
num1 = (num2 & 0xFFFFFF80) >> 7
num2 = num2 << 25
elif c == '2':
num1 = (num2 & 0xFFFFFFF0) >> 4
num2 = num2 << 28
elif c == '3':
num1 = (num2 & 0xFFFFFFF8) >> 3
num2 = num2 << 29
elif c == '4':
num1 = num2 << 1
num2 = num2 >> 31
elif c == '5':
num1 = num2 << 5
num2 = num2 >> 27
elif c == '6':
num1 = num2 << 12
num2 = num2 >> 20
elif c == '7':
num1 = num2 & 0x0000FF00 | (( num2 & 0x000000FF ) << 24 ) | (( num2 & 0x00FF0000 ) >> 16 )
num2 = ( num2 & 0xFF000000 ) >> 8
elif c == '8':
num1 = (num2 & 0x0000FFFF) << 16 | ( num2 >> 24 )
num2 = (num2 & 0x00FF0000) >> 8
elif c == '9':
num1 = ~num2
else :
num1 = num2

num1 &= 0xFFFFFFFF
num2 &= 0xFFFFFFFF
if (c not in "09"):
num1 |= num2
if test:
print(" num1: %08x num2: %08x" % (num1, num2))
num2 = num1

return str(num1)
Loading

0 comments on commit 2377dbd

Please sign in to comment.