pax_global_header00006660000000000000000000000064152375656030014526gustar00rootroot0000000000000052 comment=a188922c944c2b705ed4098075bce19ef2d545a5 OnFreund-pycoolmasternet-async-67d5b6f/000077500000000000000000000000001523756560300202345ustar00rootroot00000000000000OnFreund-pycoolmasternet-async-67d5b6f/.github/000077500000000000000000000000001523756560300215745ustar00rootroot00000000000000OnFreund-pycoolmasternet-async-67d5b6f/.github/workflows/000077500000000000000000000000001523756560300236315ustar00rootroot00000000000000OnFreund-pycoolmasternet-async-67d5b6f/.github/workflows/pr-build.yml000066400000000000000000000020561523756560300260750ustar00rootroot00000000000000name: PR Build on: pull_request: types: [opened, synchronize, reopened] concurrency: group: pr-build-${{ github.event.pull_request.number }} cancel-in-progress: true permissions: contents: read actions: write jobs: build: name: Build PR wheel runs-on: ubuntu-latest steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 with: python-version: "3.x" - run: pip install build - name: Build wheel run: python -m build --wheel env: SETUPTOOLS_SCM_PRETEND_VERSION: 0.0.0.dev${{ github.event.pull_request.number }} - name: Save PR metadata run: | echo "${{ github.event.pull_request.number }}" > dist/PR_NUMBER echo "${{ github.event.pull_request.head.sha }}" > dist/PR_HEAD_SHA - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: pr-wheel path: dist/ OnFreund-pycoolmasternet-async-67d5b6f/.github/workflows/pr-cleanup.yml000066400000000000000000000015041523756560300264220ustar00rootroot00000000000000name: PR Cleanup on: pull_request_target: types: [closed] permissions: contents: write issues: write jobs: cleanup: name: Delete PR pre-release runs-on: ubuntu-latest env: PR: ${{ github.event.pull_request.number }} GH_TOKEN: ${{ github.token }} GH_REPO: ${{ github.repository }} steps: - name: Delete PR release and tag run: gh release delete "pr-${PR}" --cleanup-tag --yes || true - name: Delete PR comment run: | gh api "repos/${GH_REPO}/issues/${PR}/comments" \ --paginate \ --jq '.[] | select(.user.login == "github-actions[bot]") | select(.body | startswith("")) | .id' \ | while read -r ID; do gh api "repos/${GH_REPO}/issues/comments/${ID}" -X DELETE done OnFreund-pycoolmasternet-async-67d5b6f/.github/workflows/pr-publish.yml000066400000000000000000000101141523756560300264360ustar00rootroot00000000000000name: PR Publish on: workflow_run: workflows: ["PR Build"] types: [completed] workflow_dispatch: inputs: run_id: description: 'PR Build run ID to publish (find it in the Actions URL)' required: true concurrency: group: pr-publish-${{ github.event.workflow_run.pull_requests[0].number || github.event.inputs.run_id || github.run_id }} cancel-in-progress: true permissions: contents: write issues: write pull-requests: write actions: read jobs: publish: name: Publish PR pre-release runs-on: ubuntu-latest if: > github.event_name == 'workflow_dispatch' || github.event.workflow_run.conclusion == 'success' steps: - name: Resolve run ID id: run run: | if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then echo "id=${{ github.event.inputs.run_id }}" >> "$GITHUB_OUTPUT" else echo "id=${{ github.event.workflow_run.id }}" >> "$GITHUB_OUTPUT" fi - uses: actions/download-artifact@95815c38cf2ff2164869cbab79da8d1f422bc89e # v4.2.1 with: name: pr-wheel run-id: ${{ steps.run.outputs.id }} github-token: ${{ github.token }} path: dist/ - name: Read PR metadata id: pr run: | echo "number=$(cat dist/PR_NUMBER)" >> "$GITHUB_OUTPUT" echo "head_sha=$(cat dist/PR_HEAD_SHA)" >> "$GITHUB_OUTPUT" - name: Validate wheel id: wheel run: | PR="$(cat dist/PR_NUMBER)" WHL_COUNT=$(ls dist/pycoolmasternet_async-0.0.0.dev${PR}-*.whl 2>/dev/null | wc -l) if [ "$WHL_COUNT" -ne 1 ]; then echo "Expected exactly 1 wheel matching pycoolmasternet_async-0.0.0.dev${PR}-*.whl, found ${WHL_COUNT}:" ls dist/ || true exit 1 fi WHEEL_FILE=$(ls dist/pycoolmasternet_async-0.0.0.dev${PR}-*.whl) echo "basename=$(basename "$WHEEL_FILE")" >> "$GITHUB_OUTPUT" - name: Delete existing PR release (if any) run: gh release delete "pr-${{ steps.pr.outputs.number }}" --cleanup-tag --yes || true env: GH_TOKEN: ${{ github.token }} GH_REPO: ${{ github.repository }} - name: Create GitHub pre-release run: | gh release create "pr-${{ steps.pr.outputs.number }}" "dist/${{ steps.wheel.outputs.basename }}" \ --prerelease \ --target "${{ steps.pr.outputs.head_sha }}" \ --repo "${{ github.repository }}" \ --title "PR #${{ steps.pr.outputs.number }} test build" \ --notes "Test build for PR #${{ steps.pr.outputs.number }}." env: GH_TOKEN: ${{ github.token }} - name: Post PR comment (first build only) run: | PR="${{ steps.pr.outputs.number }}" TAG="pr-${PR}" REPO="${{ github.repository }}" BASE="https://github.com/${REPO}/releases/download/${TAG}" WHEEL_URL="${BASE}/${{ steps.wheel.outputs.basename }}" EXISTING=$(gh api "repos/${REPO}/issues/${PR}/comments" \ --paginate \ --jq '.[] | select(.user.login == "github-actions[bot]") | select(.body | startswith("")) | .id' \ | head -1) if [ -n "$EXISTING" ]; then echo "Comment already exists, skipping." exit 0 fi BODY_FILE=$(mktemp) printf '%s\n' \ '' \ '## Test build ready' \ '' \ '**pip:**' \ '```' \ "pip install ${WHEEL_URL}" \ '```' \ '' \ "**Home Assistant** — temporarily update your integration's \`manifest.json\`:" \ '```json' \ '{' \ " \"requirements\": [\"pycoolmasternet-async @ ${WHEEL_URL}\"]" \ '}' \ '```' \ 'Revert to the pinned version after testing.' \ > "$BODY_FILE" gh pr comment "$PR" --repo "$REPO" --body-file "$BODY_FILE" env: GH_TOKEN: ${{ github.token }} OnFreund-pycoolmasternet-async-67d5b6f/.github/workflows/release.yml000066400000000000000000000024561523756560300260030ustar00rootroot00000000000000name: Release on: release: types: [published] permissions: contents: read actions: write # needed by actions/upload-artifact in the build job jobs: build: name: Build distributions runs-on: ubuntu-latest steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 with: fetch-depth: 0 # required for setuptools-scm to read git tags - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 with: python-version: "3.x" - run: pip install build - run: python -m build - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: dist path: dist/ publish: name: Publish to PyPI needs: build runs-on: ubuntu-latest environment: name: pypi url: https://pypi.org/p/pycoolmasternet-async permissions: id-token: write # OIDC for trusted publishing + PEP 740 attestations actions: read # needed by actions/download-artifact steps: - uses: actions/download-artifact@95815c38cf2ff2164869cbab79da8d1f422bc89e # v4.2.1 with: name: dist path: dist/ - uses: pypa/gh-action-pypi-publish@76f52bc884231f62b9a034ebfe128415bbaabdfc # v1.12.4 OnFreund-pycoolmasternet-async-67d5b6f/.gitignore000066400000000000000000000000641523756560300222240ustar00rootroot00000000000000build/ dist/ *.egg-info/ __pycache__/ .*.swp *.pyc OnFreund-pycoolmasternet-async-67d5b6f/LICENSE000066400000000000000000000021241523756560300212400ustar00rootroot00000000000000The MIT License (MIT) Copyright (c) 2020 On Freund Copyright (c) 2019 Steven Grimm 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. OnFreund-pycoolmasternet-async-67d5b6f/README.md000066400000000000000000000043601523756560300215160ustar00rootroot00000000000000# pycoolmasternet-async A Python 3 library for interacting with a [CoolMasterNet](https://coolautomation.com/products/coolmasternet/) HVAC bridge. This is a fork of [pycoolmaster](https://github.com/koreth/pycoolmasternet), modified to present an async interface and some other small changes. ## Installation You can install pycoolmasternet-async from [PyPI](https://pypi.org/project/pycoolmasternet-async/): pip3 install pycoolmasternet-async Python 3.13 and above are supported. ## How to use ```python from pycoolmasternet_async import CoolMasterNet cool = CoolMasterNet("coolmaster") # Supply the IP address and optional port number (default 10102). cool = CoolMasterNet("192.168.0.123", port=12345, read_timeout=1) # General information info = await cool.info() # Returns a dict of CoolMasterNetUnit objects. Keys are the unit IDs units = await cool.status() unit = units["L1.001"] unit.unit_id # Temperature unit: Imperial, Celsius unit.temperature_unit # Current reading of unit's thermometer unit.temperature # Current setting of unit's thermostat unit.thermostat # Setters return a new instance with updated info unit = await unit.set_thermostat(28) # True if unit is turned on unit.is_on unit = await unit.turn_on() unit = await unit.turn_off() # Fan speed: low, med, high, auto unit.fan_speed unit = await unit.set_fan_speed('med') # Mode of operation: auto, cool, dry, fan, heat unit.mode unit = await unit.set_mode('cool') # True while the unit is actively calling for heating/cooling, False when it # is on but idle. None if the bridge's status format doesn't report demand. unit.demand # Get fresh info unit = await unit.refresh() ``` ## Errors Errors raised by this library derive from `CoolMasterNetError`: - `CoolMasterNetConnectionError` - the bridge could not be reached, or did not answer as expected. Also a `ConnectionError`, and so an `OSError`. - `CoolMasterNetCommandError` - the bridge rejected a command. Also a `ValueError`. They subclass the builtins previously raised, so existing `except OSError` or `except ValueError` handlers keep working. Note that connection failures raised by `asyncio` itself (for example `TimeoutError`, or `socket.gaierror` for an unresolvable host) still propagate as plain `OSError` subclasses. OnFreund-pycoolmasternet-async-67d5b6f/pycoolmasternet_async/000077500000000000000000000000001523756560300246615ustar00rootroot00000000000000OnFreund-pycoolmasternet-async-67d5b6f/pycoolmasternet_async/__init__.py000066400000000000000000000003521523756560300267720ustar00rootroot00000000000000from .coolmasternet import CoolMasterNet from .coolmasternet import SWING_MODES from .coolmasternet import CoolMasterNetError from .coolmasternet import CoolMasterNetConnectionError from .coolmasternet import CoolMasterNetCommandErrorOnFreund-pycoolmasternet-async-67d5b6f/pycoolmasternet_async/coolmasternet.py000066400000000000000000000236101523756560300301140ustar00rootroot00000000000000import asyncio import re _MODES = ["auto", "cool", "dry", "fan", "heat"] _SWING_CHAR_TO_NAME = { "a": "auto", "h": "horizontal", "3": "30", "4": "45", "6": "60", "v": "vertical", "x": "stop", } _SWING_NAME_TO_CHAR = {value: key for key, value in _SWING_CHAR_TO_NAME.items()} SWING_MODES = list(_SWING_CHAR_TO_NAME.values()) class CoolMasterNetError(Exception): """Base class for errors raised by this library.""" class CoolMasterNetConnectionError(CoolMasterNetError, ConnectionError): """The bridge could not be reached, or did not answer as expected. Subclasses ConnectionError, and so OSError, so that callers already catching those keep working. """ class CoolMasterNetCommandError(CoolMasterNetError, ValueError): """The bridge rejected a command. Subclasses ValueError for backwards compatibility, which also keeps the ls2/stat2 fallback in _status working. """ class CoolMasterNet(): """A connection to a coolmasternet bridge.""" def __init__(self, host, port=10102, read_timeout=1, swing_support=False, send_initial_line_feed=False): """Initialize this CoolMasterNet instance to connect to a particular host at a particular port.""" self._host = host self._port = port self._read_timeout = read_timeout self._swing_support = swing_support self._send_initial_line_feed = send_initial_line_feed self._status_cmd = None self._concurrent_reads = asyncio.Semaphore(3) async def _make_request(self, request): """Send a request to the CoolMasterNet and returns the response.""" async with self._concurrent_reads: reader, writer = await asyncio.open_connection(self._host, self._port) try: if self._send_initial_line_feed: writer.write(("\n").encode("ascii")) prompt = await asyncio.wait_for(reader.readuntil((b"\r\n>", b">>")), self._read_timeout) if prompt not in (b"\r\n>", b">>"): raise CoolMasterNetConnectionError("CoolMasterNet prompt not found") else: prompt = await asyncio.wait_for(reader.readuntil(b">"), self._read_timeout) if prompt != b">": raise CoolMasterNetConnectionError("CoolMasterNet prompt not found") writer.write((request + "\n").encode("ascii")) response = await asyncio.wait_for(reader.readuntil(b"\n>"), self._read_timeout) data = response.decode("ascii") if data.endswith("\n>"): data = data[:-1] if data.endswith("OK\r\n"): data = data[:-4] if "Unknown command" in data: cmd = request.split(" ", 1)[0] raise CoolMasterNetCommandError(f"Command '{cmd}' is not supported") return data finally: writer.close() await writer.wait_closed() async def info(self): """Get the general info the this CoolMasterNet.""" raw = await self._make_request("set") lines = raw.strip().split("\r\n") key_values = [re.split(r"\s*:\s*", line, 1) for line in lines] return dict(key_values) async def _status(self, status_cmd=None, unit_id=None): """Fetch the status of all units or a single one, falls back to legacy format if necessary""" if status_cmd is None: cmds = ['ls2', 'stat2'] else: cmds = [status_cmd] for cmd in cmds: try: final_cmd = f"{cmd} {unit_id}" if unit_id is not None else cmd status_lines = (await self._make_request(final_cmd)).strip().split("\r\n") break except ValueError: continue else: raise CoolMasterNetError("failed to execute status commands") return cmd, status_lines async def status(self): """Return a list of CoolMasterNetUnit objects with current status.""" self._status_cmd, status_lines = await self._status(self._status_cmd) return { key: unit for unit, key in await asyncio.gather( *(CoolMasterNetUnit.create( self, line.split(" ", 1)[0], line, self._status_cmd) for line in status_lines ) ) } class CoolMasterNetUnit(): """An immutable snapshot of a unit.""" def __init__(self, bridge, unit_id, raw, swing_raw, status_cmd): """Initialize a unit snapshot.""" self._raw = raw self._status_cmd = status_cmd self._swing_raw = swing_raw self._unit_id = unit_id self._bridge = bridge self._parse() @classmethod async def create(cls, bridge, unit_id, raw=None, status_cmd=None): if raw is None or status_cmd is None: status_cmd, status_lines = await bridge._status(status_cmd, unit_id) raw = status_lines[0] swing_raw = ((await bridge._make_request(f"query {unit_id} s")).strip() if bridge._swing_support else "") return CoolMasterNetUnit(bridge, unit_id, raw, swing_raw, status_cmd), unit_id def _parse(self): fields = re.split(r"\s+", self._raw.strip()) if len(fields) not in (8, 9): raise CoolMasterNetConnectionError("Unexpected status line format: " + str(fields)) self._is_on = fields[1] == "ON" self._temperature_unit = "imperial" if fields[2][-1] == "F" else "celsius" self._thermostat = float(fields[2][:-1]) self._temperature = float(fields[3][:-1].replace(",", ".")) self._fan_speed = fields[4].lower() self._mode = fields[5].lower() self._error_code = fields[6] if fields[6] != "OK" else None self._clean_filter = fields[7] in ("#", "1") # Only the 9-field form (ls/ls2) carries the demand flag as the last # field. The 8-field form (stat2) stops at the filter sign, so demand # is unknown there rather than assumed to be off. self._demand = fields[8] != "0" if len(fields) > 8 else None self._swing = _SWING_CHAR_TO_NAME.get(self._swing_raw) async def _make_unit_request(self, request): return await self._bridge._make_request(request.replace("UID", self._unit_id)) async def refresh(self): """Refresh the data from CoolMasterNet and return it as a new instance.""" return (await CoolMasterNetUnit.create(self._bridge, self._unit_id, None, self._status_cmd))[0] @property def unit_id(self): """The unit id.""" return self._unit_id @property def is_on(self): """Is the unit on.""" return self._is_on @property def thermostat(self): """The target temperature.""" return self._thermostat @property def temperature(self): """The current temperature.""" return self._temperature @property def fan_speed(self): """The fan spped.""" return self._fan_speed @property def mode(self): """The current mode (e.g. heat, cool).""" return self._mode @property def error_code(self): """Error code on error, otherwise None.""" return self._error_code @property def clean_filter(self): """True when the air filter needs to be cleaned.""" return self._clean_filter @property def demand(self): """True when the unit is actively calling for heating/cooling. A unit can be on while idle, for example in dry mode once the room is already below the set point. Returns None when the bridge's status format does not report demand. """ return self._demand @property def swing(self): """The current swing mode (e.g. horizontal).""" return self._swing @property def temperature_unit(self): return self._temperature_unit async def set_fan_speed(self, value): """Set the fan speed.""" await self._make_unit_request(f"fspeed UID {value}") return await self.refresh() async def set_mode(self, value): """Set the mode.""" if not value in _MODES: raise ValueError( f"Unrecognized mode {value}. Valid values: {' '.join(_MODES)}" ) await self._make_unit_request(value + " UID") return await self.refresh() async def set_thermostat(self, value): """Set the target temperature.""" rounded = round(value, 1) await self._make_unit_request(f"temp UID {rounded}") return await self.refresh() async def set_swing(self, value): """Set the swing mode.""" if not value in SWING_MODES: raise ValueError( f"Unrecognized swing mode {value}. Valid values: {', '.join(SWING_MODES)}" ) return_value = await self._make_unit_request(f"swing UID {_SWING_NAME_TO_CHAR[value]}") if return_value.startswith("Unsupported Feature"): raise CoolMasterNetCommandError( f"Unit {self._unit_id} doesn't support swing mode {value}." ) return await self.refresh() async def turn_on(self): """Turn a unit on.""" await self._make_unit_request("on UID") return await self.refresh() async def turn_off(self): """Turn a unit off.""" await self._make_unit_request("off UID") return await self.refresh() async def reset_filter(self): """Report that the air filter was cleaned and reset the timer.""" await self._make_unit_request(f"filt UID") return await self.refresh() async def feed(self, value): """Provides ambient temperature hint to the unit.""" rounded = round(value, 1) await self._make_unit_request(f"feed UID {rounded}") OnFreund-pycoolmasternet-async-67d5b6f/pyproject.toml000066400000000000000000000016631523756560300231560ustar00rootroot00000000000000[build-system] requires = ["setuptools>=61", "setuptools-scm>=8"] build-backend = "setuptools.build_meta" [project] name = "pycoolmasternet-async" dynamic = ["version"] description = "A python library to control CoolMasterNet HVAC bridges over asyncio." readme = "README.md" license = { text = "MIT" } authors = [{ name = "On Freund", email = "onfreund@gmail.com" }] requires-python = ">=3.13" dependencies = [] classifiers = [ "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.13", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", ] [project.urls] Homepage = "https://github.com/OnFreund/pycoolmasternet-async" [tool.setuptools.packages.find] exclude = ["tests*"] [tool.setuptools_scm] # version derived from git tags (e.g. v0.2.4 → 0.2.4)