69 Commits

Author SHA1 Message Date
b2faf57d09 Prepare for 1.8.0 release 2022-04-17 10:47:56 -05:00
c95c9f8ce5 Fix day-of-week handling again
Saturday isn't 0, it's 7.

Add tests to make sure this is working now and forever!
2022-04-17 10:47:45 -05:00
79bff51c17 Satisfy linter 2022-04-15 16:38:29 -05:00
485b494ea8 Add support for reading unit history data
unit.getHistoryData(fromTime, toTime) will request data about sensor and circuit changes over time, then `getHistoryData` will be emitted when the data is ready to be handled.

Fixes #59
2022-04-15 16:38:24 -05:00
4de8a63140 Fix readme typo 2022-04-15 16:24:33 -05:00
e0136a01cd Fix SLDateTime day-of-week calculation
Turns out we were offsetting the wrong direction. This offsets the correct way (verified against a Wireshark capture of the official app).
2022-04-15 16:17:18 -05:00
de8bba63a0 Alphabetize most of the readme sections
And indent the individual messages a bit to help the layout presentation.
2022-04-15 16:13:50 -05:00
77b034ce57 Add reading of SLTimes 2022-04-15 14:55:26 -05:00
0db9e4945e Run npm update 2022-02-01 09:35:32 -06:00
ada16cd355 Run npm audit fix 2022-02-01 09:33:38 -06:00
cbe64bbb2e Update dependencies 2022-01-07 14:34:40 -06:00
4cfffdd9df Drop support for nodejs 10.x, add 14.x and 16.x
Update package.json version
2021-10-13 14:14:41 -05:00
ba6dac4399 Update changelog, dependencies 2021-10-13 14:12:05 -05:00
f406bccb5d Update coolSetPoint documentation per user findings
Closes #57
2021-09-06 23:09:44 -05:00
a5d207d3aa Add support for setting the current system date/time
#56
2021-09-06 23:02:02 -05:00
f271554d89 Add DateTime writing support to SLMessages
There may be some value in providing a read version of this as well, but
it is comprised of so many properties that I'm leaving that out for now.
If it becomes a need in the future, it will be straightforward to add.
2021-09-06 23:01:42 -05:00
37d40b3386 Add support for retrieving the current system date/time
#56
2021-09-06 23:00:51 -05:00
6f1ee3c13f Add info about add/remove client function events 2021-09-06 22:56:16 -05:00
0b990bbc28 Add links to time conversion functions 2021-09-06 21:51:50 -05:00
2aa14cc114 Fix SLGetScheduleData documentation 2021-09-06 21:51:50 -05:00
bef8e6a379 Bump glob-parent from 5.1.1 to 5.1.2
Bumps [glob-parent](https://github.com/gulpjs/glob-parent) from 5.1.1 to 5.1.2.
- [Release notes](https://github.com/gulpjs/glob-parent/releases)
- [Changelog](https://github.com/gulpjs/glob-parent/blob/main/CHANGELOG.md)
- [Commits](https://github.com/gulpjs/glob-parent/compare/v5.1.1...v5.1.2)

---
updated-dependencies:
- dependency-name: glob-parent
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-06-11 07:23:37 -05:00
5bbbfb6f41 Bump lodash from 4.17.20 to 4.17.21
Bumps [lodash](https://github.com/lodash/lodash) from 4.17.20 to 4.17.21.
- [Release notes](https://github.com/lodash/lodash/releases)
- [Commits](https://github.com/lodash/lodash/compare/4.17.20...4.17.21)

Signed-off-by: dependabot[bot] <support@github.com>
2021-05-10 22:26:51 -05:00
fa43b3c03e Bump y18n from 4.0.0 to 4.0.1
Bumps [y18n](https://github.com/yargs/y18n) from 4.0.0 to 4.0.1.
- [Release notes](https://github.com/yargs/y18n/releases)
- [Changelog](https://github.com/yargs/y18n/blob/master/CHANGELOG.md)
- [Commits](https://github.com/yargs/y18n/commits)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-31 14:36:05 -05:00
789f75f4a6 Add missing break 2020-12-12 21:14:41 -06:00
1ea8548991 Add handling/documentation for the scheduleChanged event
See discussion on #44 for more info
2020-12-12 21:12:15 -06:00
542d2f3e94 Disabled scheduled CodeQL runs 2020-11-28 19:44:23 -06:00
5f5b52f1ab Tag new version, update dev dependencies 2020-11-23 08:15:44 -06:00
7f76cb2a54 Update changelog for release 2020-11-23 08:13:43 -06:00
863cd7b1e6 Create codeql-analysis.yml 2020-10-01 11:57:43 -05:00
a53909eaa2 Add table of contents to readme 2020-08-22 21:33:24 -05:00
27bdf0380e Ensure all messages populate the response senderId
Fixed `addClient` and `removeClient` events returning `SLCancelDelay` objects. This shouldn't really make a difference as there are no properties to worry about on one or the other, but it was still incorrect and could cause bugs if stuff was added to those messages in the future.
2020-08-12 08:51:44 -05:00
8294947f8c Update dev dependencies due to vulnerabilities 2020-08-11 22:31:18 -05:00
b0225c69bd Update to point at the new default branch name 2020-08-11 22:28:07 -05:00
89b8775ce3 Add support for specifying the sender id to each call
This parameter is optional, so compatibility shouldn't be affected. Each SLMessage can set its own sender ID which is present on the returned message. This allows callers to fire multiple requests at once, even of the same type, while being able to identify which response went with which request. If not specified, the default value is 0.

Also went ahead and documented some of the helper functions present on SLMessage (so, available on all message instances).

Finally, since I was in and messing with each message anyway, I simplified and removed some repeated code from each derived message and had it call into the super to take advantage of shared decoding functionality.

The lambdas ("arrow functions") in test functions were removed per advice from Mocha's documentation where the implicit `this` rebinding can apparently cause problems. This should probably have been its own commit, but, again, I was already in there messing with stuff, so...oh well.

Closes #43
2020-08-11 22:20:58 -05:00
ab36d17a38 Increase version for NPM-specific fix
I had local changes to the example script that inadvertently were pushed to npm as part of 1.6.0, so that release on npm didn't match the repo's contents.
2020-07-15 20:58:41 -05:00
c36e4cbaa2 Fix changelog release date
Time is meaningless these days anyway...
2020-07-14 15:55:34 -05:00
df22901ea1 Add another missed attribution 2020-07-14 12:51:05 -05:00
b23f488822 Remove specific node versions tested against
These change frequently and it's probably not worth documenting anyway. I'm pretty sure these versions were no longer valid anyway since, for example, Mocha no longer supports node v8.
2020-07-14 12:50:50 -05:00
d7d10d7408 Update outdated dependencies, fix npm audit 2020-07-14 12:47:21 -05:00
b80807448d Update changelog/package.json for release 2020-07-14 12:46:43 -05:00
2e5203fb85 Adds keepalive setting to socket 2020-06-28 15:40:14 -05:00
0a0c8c7cd0 Bug Fix for decodeValveData / improvedNaming / CIRCUIT_VALUE_MAP (#33)
* initial code to interpret valveDataArray

* Some additional comments on the valveDataArray decoding message

* Adds decodeSensorData, decodeValveData, decodeDelayData, decodeMiscData

* reverts unintended change to index.js

* Refactor / rename variables
	- renamed variables to better describe their use
	- created a helper function 'isValvePresent' to simplify code
	- changed while loop to for loop

* - Fixes bug in decodeValveData where only last valve's data was returned
- renames some variables based on testing to more descriptive names
- add CIRCUIT_NAME_VALUE_MAP for fixed values that the system uses (determined by testing on my system)

* refactored decodeMiscData to simplify code

* - Changed CIRCUIT_NAME_VALUE_MAP to array of objects
- Refactored getCircuitByDeviceId
- Added getCircuitsMap as helper to getCircuitByDeviceId and as a utility function to help in UI development
2020-06-19 09:57:51 -05:00
1e13036faf decodeSensorData, decodeValveData, decodeDelayData, decodeMiscData (#32)
* initial code to interpret valveDataArray

* Some additional comments on the valveDataArray decoding message

* Adds decodeSensorData, decodeValveData, decodeDelayData, decodeMiscData

* reverts unintended change to index.js

* Refactor / rename variables
	- renamed variables to better describe their use
	- created a helper function 'isValvePresent' to simplify code
	- changed while loop to for loop
2020-06-18 16:22:58 -05:00
addd89bec5 Day mask helper functions / Refactor of time functions (#31)
* added helper methods for decode/encode dayMask

* moved isBitSet to SLMessage.js as this method is needed for several message types

* Refactored reusable functions to SLMessage
2020-06-16 21:22:22 -05:00
1aea09d95e Missed these new ones 2020-06-12 13:44:09 -05:00
9e158ae903 Made readme and changelog markdownlint compliant 2020-06-12 13:42:25 -05:00
b2439cd90c Added SLAddClient / SLRemoveClient messages (#30) 2020-06-10 08:05:32 -05:00
71c606cb94 Updated changelog 2020-06-09 16:52:36 -05:00
98f759c717 Added debug logging, updated readme with new message+event 2020-06-09 16:51:41 -05:00
407a4ec1f2 Added attribution to changelog items 2020-06-09 16:46:01 -05:00
db522ba5db SLCancelDelay message added (#29) 2020-06-09 16:43:09 -05:00
626ca5b64f Added recent work to the changelog 2020-06-09 09:31:14 -05:00
51d5b5a620 Added dependency on debug package, converted console.log to debug logs
I find these console logs valuable for development but don't want them on all the time for everyone. It's cumbersome to comment/uncomment them continually, so this package helps nicely. I generally don't like adding dependencies, but this one seems wildly popular and itself only has one dependency (and that dependencies doesn't depend on anything else). So it seems acceptable to use.

I also enabled these debug logs by default when running the example configuration from VSCode.
2020-06-09 09:25:40 -05:00
71dad9a51b Disabled max-len eslint rule for the entire project
Personally I've never found value in keeping line lengths low and it just leads to code that's awkward to write and read. No sense in disabling this per-file.
2020-06-09 09:22:25 -05:00
c0ac043d7b Added constants for heat modes 2020-06-09 08:47:32 -05:00
ee30cd815e GetPumpStatus isRPMs changed to bool to be consistent with SetPumpStatus 2020-06-09 08:42:26 -05:00
bf3902efe8 Updated formatting/semantics, added missing event/method documentation 2020-06-09 08:41:15 -05:00
e6acd36562 Added helper to get the number of pumps installed in a system 2020-06-09 08:39:38 -05:00
75d642cbfc GetPumpStatus / SetPumpFlow commands (#28)
* added GetPumpStatus / SetPumpFlow commands

* Updated README.md with GetPumpStatus / SetPumpFlow information

* rename `setPointType` to `isRPMs`

* renamed val0 to pumpType and val1 to isRunning

* added `unknown command` case

* fixed lint error

* Renamed unknown values to pumpUnknown1 and pumpUnknown2

* renamed 30 to unknownCommand
2020-06-09 07:49:24 -05:00
219ce110ea Added an extra GitHub action to run SLMessage tests 2020-06-08 22:21:06 -05:00
cd981c19ef Added ability to get circuit info by the device id
This is useful for EquipmentConfiguration and upcoming PumpStatus messages.
2020-06-08 22:14:31 -05:00
8d908aad5d WIP interpretation of equipment configuration properties 2020-06-08 19:05:45 -05:00
6013410525 Ran npm install 2020-06-06 19:04:00 -05:00
95140d112e Preparing for release 2020-06-06 19:02:29 -05:00
db28ef4bbc Updated outdated dependencies 2020-06-06 18:59:39 -05:00
c1ceacbd98 Updated Readme / Added EggTimer Support (#25)
* added setCircuitRuntimeById function
2020-06-06 18:57:58 -05:00
9c72e7b61d Schedule Editing Additions (#24)
* Added support for: adding schedule events, deleting schedule events, listing schedule events and updating scheduled events
2020-06-03 22:07:33 -05:00
def2d8aad4 Fixed typo in github action script 2020-05-25 14:09:56 -05:00
2d6d694aa5 Create nodejs.yml 2020-05-25 14:06:19 -05:00
40 changed files with 4572 additions and 2171 deletions

View File

@ -1,7 +1,7 @@
{
"extends": "strongloop",
"rules": {
"max-len": [2, 120, 8]
"max-len": "off"
},
"parserOptions": {
"ecmaVersion": 6

69
.github/workflows/codeql-analysis.yml vendored Normal file
View File

@ -0,0 +1,69 @@
# For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository.
#
# You may wish to alter this file to override the set of languages analyzed,
# or to provide custom queries or build logic.
name: "CodeQL"
on:
push:
branches: [main]
pull_request:
# The branches below must be a subset of the branches above
branches: [main]
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
# Override automatic language detection by changing the below list
# Supported options are ['csharp', 'cpp', 'go', 'java', 'javascript', 'python']
language: ['javascript']
# Learn more...
# https://docs.github.com/en/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#overriding-automatic-language-detection
steps:
- name: Checkout repository
uses: actions/checkout@v2
with:
# We must fetch at least the immediate parents so that if this is
# a pull request then we can checkout the head.
fetch-depth: 2
# If this run was triggered by a pull request event, then checkout
# the head of the pull request instead of the merge commit.
- run: git checkout HEAD^2
if: ${{ github.event_name == 'pull_request' }}
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v1
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# queries: ./path/to/local/query, your-org/your-repo/queries@main
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v1
# Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
# and modify them (or add more) to build your code if your project
# uses a compiled language
#- run: |
# make bootstrap
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1

30
.github/workflows/nodejs.yml vendored Normal file
View File

@ -0,0 +1,30 @@
# This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node
# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions
name: Node.js CI
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [12.x, 14.x, 16.x]
steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- run: npm ci
- run: npm run build --if-present
- run: npm run pretest
- run: npm run test-slmessage

7
.markdownlint.json Normal file
View File

@ -0,0 +1,7 @@
{
"default": true,
"no-duplicate-header": {
"siblings_only": true
},
"line-length": false
}

5
.vscode/launch.json vendored
View File

@ -11,7 +11,10 @@
"program": "${workspaceFolder}/example.js",
"skipFiles": [
"<node_internals>/**"
]
],
"env": {
"DEBUG": "sl:*"
}
}
]
}

View File

@ -1,56 +1,133 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## v1.4.0 - 2020-05-25
## v1.8.0 - 2022-04-17
### Added
* Added support for reading ScreenLogic time packets.
* Added support for getting system history data. This includes temperature readings over time as well as circuit on/off changes over time.
### Fixed
* Updated dependencies to safer versions of some packages.
* Fixed day-of-week conversion from Javascript Date objects to ScreenLogic times (SLTimes are 1-based starting on Sunday).
### Changed
* Alphabetized the readme.
## v1.7.0 - 2021-10-13
### Added
* Added handling/documentation for the scheduleChanged event (#44).
* Added support for getting and setting the system date/time.
### Fixed
* Documentation updates for `SLGetScheduleData`, more linkage for easy navigation, `addClient`/`removeClient` methods, clarified `coolSetPoint` for spas.
## v1.6.1 - 2020-11-23
### Added
* Every call now can optionally specify an ID that will be returned with the result, allowing tracking of simultaneous commands.
## v1.6.0 - 2020-07-14
### Added
* Fleshed out the still-undocumented `SLEquipmentConfigurationMessage` with a few more helper methods for interpreting the data inside.
* Helper method for getting a circuit from its device ID on an `SLControllerConfigMessage`.
* Support for getting the status of pumps and setting flow speeds per-pump-per-circuit.
* Constants for interpreting heat command/mode properties on various messages:
* ScreenLogic.HEAT_MODE_OFF
* ScreenLogic.HEAT_MODE_SOLAR
* ScreenLogic.HEAT_MODE_SOLARPREFERRED
* ScreenLogic.HEAT_MODE_HEATPUMP
* ScreenLogic.HEAT_MODE_DONTCHANGE
* Debug logs using the "debug" NPM package. You'll need to run an `npm install` after updating to this version.
* Ability to cancel delays in pool equipment. #20 - thanks @bshep
* Ability to register for push messages from the equipment so the connection can be kept open instead of repeatedly reconnecting and polling for changes. See the `addClient()` and `removeClient()` functions on the `UnitConnection` docs. Thanks @bshep
## v1.5.0 - 2020-06-06
### Added
* Added support for adding, deleting, listing, and updating scheduled events - thanks @bshep
* Added egg timer support - thanks @bshep
## v1.4.0 - 2020-05-25
### Added
* Support for controlling the salt cell generator's output levels.
* Helper methods for interpreting `controllerType`.
* Experimental support for an Equipment Configuration message (not documented as of yet - `SLEquipmentConfigurationMessage` / `getEquipmentConfiguration()`). This message returns arrays of various information about the equipment, but I don't know how to interpret the information in those arrays yet. Any assistance with decoding this information would be hugely helpful.
* `error` handler on all objects for reacting to unhandled node errors.
* `error` handler on all objects for reacting to unhandled node errors - thanks @schemers
### Fixed
* VSCode "Example" configuration can now be launched on non-Windows platforms.
### Changed
* Minor memory/performance optimizations.
* Running tests no longer changes any state of any pool equipment.
## v1.3.1 - 2019-12-27
### Added
* Several methods added to SLControllerConfigMessage for interpreting the equipFlags value.
### Fixed
* server.gatewayName no longer cuts off the last character of the name. #14 - thanks @mikemucc
## v1.3.0 - 2019-11-26
### Added
* Ability to set heat setpoint.
* Ability to set heat mode.
* Event for supplying incorrect parameters to `set` functions.
* Ability to send limited selection of light commands.
## v1.2.1 - 2019-03-26
### Fixed
* Messages larger than 1024 bytes are now handled properly.
## v1.2.0 - 2019-02-22
### Added
* Remote connection through Pentair servers
* Connecting to password-protected systems (this is only enforced by the ScreenLogic system on remote connections)
## v1.1.0 - 2018-04-23
### Added
* Ability to set circuit state.
### Fixed
* FindUnits.sendServerBroadcast() was failing in certain environments.
## v1.0.1 - 2018-03-31
### Added
* Direct connection support.
## v1.0.0 - 2018-03-31
* Initial release

View File

@ -1,5 +1,3 @@
/* eslint max-len: "off" */
'use strict';
const BLOCK_SIZE = 16;

669
README.md
View File

@ -2,9 +2,42 @@
This is a Node.JS library for interfacing with Pentair ScreenLogic systems over your local network or remotely through the Pentair dispatcher. Local connections require a Pentair ScreenLogic device on the same network (a network which supports UDP broadcasts).
Tested on node v8.11.1, v10.15.1 with a system on firmware versions 5.2 Build 736.0 Rel, 5.2 Build 738.0 Rel
Tested with a Pentair ScreenLogic system on firmware versions 5.2 Build 736.0 Rel, 5.2 Build 738.0 Rel
# Usage
* [Usage](#usage)
* [Notes](#notes)
* [Packet format](#packet-format)
* [API reference](#api-reference)
* [FindUnits](#findunits)
* [RemoteLogin](#remotelogin)
* [UnitConnection](#unitconnection)
* [All messages](#all-messages)
* [SLAddClient](#sladdclient)
* [SLAddNewScheduleEvent](#sladdnewscheduleevent)
* [SLCancelDelay](#slcanceldelay)
* [SLChemDataMessage](#slchemdatamessage)
* [SLControllerConfigMessage](#slcontrollerconfigmessage)
* [SLDeleteScheduleEventById](#sldeletescheduleeventbyid)
* [SLGetGatewayDataMessage](#slgetgatewaydatamessage)
* [SLGetHistoryData](#slgethistorydata)
* [SLGetPumpStatus](#slgetpumpstatus)
* [SLGetScheduleData](#slgetscheduledata)
* [SLGetSystemTime](#slgetsystemtime)
* [SLLightControlMessage](#sllightcontrolmessage)
* [SLPoolStatusMessage](#slpoolstatusmessage)
* [SLRemoveClient](#slremoveclient)
* [SLSaltCellConfigMessage](#slsaltcellconfigmessage)
* [SLSetCircuitRuntimeById](#slsetcircuitruntimebyid)
* [SLSetCircuitStateMessage](#slsetcircuitstatemessage)
* [SLSetHeatModeMessage](#slsetheatmodemessage)
* [SLSetHeatSetPointMessage](#slsetheatsetpointmessage)
* [SLSetPumpFlow](#slsetpumpflow)
* [SLSetSaltCellConfigMessage](#slsetsaltcellconfigmessage)
* [SLSetScheduleEventById](#slsetscheduleeventbyid)
* [SLSetSystemTime](#slsetsystemtime)
* [SLVersionMessage](#slversionmessage)
## Usage
See example.js for an example of interfacing with the library. Broadly, import the library with
@ -51,48 +84,51 @@ or
```javascript
new ScreenLogic.UnitConnection(unit.port, unit.ipAddr, '1234')
```
where `'1234'` is the remote login password.
Once you've connected with `connect()`, there are a number of methods available and corresponding events for when they've completed successfully. See [UnitConnection](#unitconnection) API reference.
All communication with a ScreenLogic unit is done via TCP, so responses will come back in the order they were requested.
# Notes
## Notes
Contributions welcome. There are lots of available messages supported by ScreenLogic that the app doesn't support yet, but can be added pretty easily as needed.
# Packet format
## Packet format
All ScreenLogic packets are sent with an 8-byte header. The first 2 bytes are a little-endian-encoded sender ID (which is normally specified when making the original request). The second 2 bytes are a little-endian-encoded message ID. The final 4 bytes are a little-endian-encoded length of the data payload on the packet. The data payload is handled per-message.
# API Reference
## API Reference
Pull requests to document undocumented properties are most welcome.
## FindUnits
### FindUnits
### constructor()
#### constructor()
Examples:
```javascript
const ScreenLogic = require('node-screenlogic');
var finder = new ScreenLogic.FindUnits();
```
### search()
#### search()
Begins a UDP broadcast search for available units.
### close()
#### close()
Closes the socket.
### Events
#### Events
* `serverFound` - Indicates that a ScreenLogic unit has been found. Event handler receives a [`UnitConnection`](#unitconnection) object.
Examples:
```javascript
finder.on('serverFound', function(server) {
var client = new ScreenLogic.UnitConnection(server);
@ -101,39 +137,41 @@ finder.on('serverFound', function(server) {
* `error` - Indicates that an unhandled error was caught (such as the connection timing out)
## RemoteLogin
### RemoteLogin
### constructor(systemName)
#### constructor(systemName)
Argument is the name of a system to connect to in "Pentair: xx-xx-xx" format.
Example:
```javascript
const ScreenLogic = require('./index');
var remoteLogin = new ScreenLogic.RemoteLogin('Pentair: xx-xx-xx');
```
### connect()
#### connect()
Connects to the dispatcher service and searches for the unit passed to its constructor.
### close()
#### close()
Closes the connection
### Events
#### Events
* `gatewayFound` - Indicates that the search for the named unit has completed (may or may not be successful). Event handler receives a [`SLGetGatewayDataMessage`](#slgetgatewaydatamessage) argument.
* `error` - Indicates that an unhandled error was caught (such as the connection timing out)
## UnitConnection
### UnitConnection
### constructor(server)
#### constructor(server)
Argument is a server returned from [`FindUnits`](#findunits) `serverFound` event.
Examples:
```javascript
finder.on('serverFound', function(server) {
var client = new ScreenLogic.UnitConnection(server);
@ -148,89 +186,159 @@ remoteLogin.on('gatewayFound', function(unit) {
});
```
### constructor(port, address, password)
#### constructor(port, address, password)
Port is an integer. Address is an IPv4 address of the server as a string. Password is optional; should be the 4-digit password in string form, e.g. `'1234'`.
Examples:
```javascript
var client = new ScreenLogic.UnitConnection(80, '10.0.0.85', '1234')
```
### connect()
#### connect()
Connects to the server passed to its constructor.
Examples:
```javascript
var client = new ScreenLogic.UnitConnection(server);
client.connect();
```
### close()
#### close()
Closes the connection.
### getVersion()
#### addClient(clientId, senderId)
Requests the system version string from the connected unit. Emits the `version` event when the response comes back.
Registers to receive updates from controller when something changes. Takes a random number `clientId` to identify the client. Emits the `poolStatus` event when something changes on the controller, and the `addClient` event when the request to add a client is acknowledged. `senderId` is an optional 16-bit integer and will be present as the `senderId` field on the returned message.
### getPoolStatus()
#### addNewScheduleEvent(scheduleType, senderId)
Requests pool status from the connected unit. Emits the `poolStatus` event when the response comes back.
Adds a new event to the specified schedule type. See [`SLAddNewScheduleEvent`](#sladdnewscheduleevent) documentation for argument values. Emits either the `addNewScheduleEvent` or `scheduleChanged` event when response is acknowledged (listen for both). `senderId` is an optional 16-bit integer and will be present as the `senderId` field on the returned message.
### getChemicalData()
#### cancelDelay(senderId)
Requests chemical data from the connected unit (may require an IntelliChem or similar). Emits the `chemicalData` event when the response comes back.
Cancels any delays on the system. See [`SLCancelDelay`](#slcanceldelay) documentation. Emits the `cancelDelay` event when response is acknowledged. `senderId` is an optional 16-bit integer and will be present as the `senderId` field on the returned message.
### getSaltCellConfig()
#### deleteScheduleEventById(scheduleId, senderId)
Requests salt cell status/configuration from the connected unit (requires an IntelliChlor or compatible salt cell). Emits the `saltCellConfig` event when the response comes back.
Deletes a scheduled event with specified id. See [`SLDeleteScheduleEventById`](#sldeletescheduleeventbyid) documentation for argument values. Emits the `deleteScheduleById` or `scheduleChanged` event when response is acknowledged (listen for both). `senderId` is an optional 16-bit integer and will be present as the `senderId` field on the returned message.
### getControllerConfig()
#### getChemicalData(senderId)
Requests controller configuration from the connected unit. Emits the `controllerConfig` event when the response comes back.
Requests chemical data from the connected unit (may require an IntelliChem or similar). Emits the `chemicalData` event when the response comes back. `senderId` is an optional 16-bit integer and will be present as the `senderId` field on the returned message.
### setCircuitState(controllerId, circuitId, circuitState)
#### getControllerConfig(senderId)
Activates or deactivates a circuit. See [`SLSetCircuitStateMessage`](#slsetcircuitstatemessage) documentation for argument values. Emits the `circuitStateChanged` event when response is acknowledged.
Requests controller configuration from the connected unit. Emits the `controllerConfig` event when the response comes back. `senderId` is an optional 16-bit integer and will be present as the `senderId` field on the returned message.
### setSetPoint(controllerId, bodyType, temperature)
#### getHistoryData(fromTime, toTime, senderId)
Sets the heating setpoint for any body. See [`SLSetHeatSetPointMessage`](#slsetheatsetpointmessage) documentation for argument values. Emits the `setPointChanged` event when response is acknowledged.
Requests history data from the connected unit. This is information like what various temperature sensors (air, water) read over time, changes in heat setpoints, and when various circuits (pool, spa, solar, heater, and lights) were turned on and off. `fromTime` is the time (as a Javascript Date object) that you want to get events from and `toTime` is the time (as a Javascript Date object) that you want to get events until. Emits the `getHistoryDataPending` event when the request to get data is confirmed, then the `getHistoryData` event when the history data is actually ready to be handled. `senderId` is an optional 16-bit integer and will be present as the `senderId` field on the returned message.
### setHeatMode(controllerId, bodyType, heatMode)
#### getPoolStatus(senderId)
Sets the preferred heat mode. See [`SLSetHeatModeMessage`](#slsetheatmodemessage) documentation for argument values. Emits the `heatModeChanged` event when response is acknowledged.
Requests pool status from the connected unit. Emits the `poolStatus` event when the response comes back. `senderId` is an optional 16-bit integer and will be present as the `senderId` field on the returned message.
### sendLightCommand(controllerId, command)
#### getPumpStatus(pumpId, senderId)
Sends a lighting command. See [`SLLightControlMessage`](#sllightcontrolmessage) documentation for argument values. Emits the `sentLightCommand` event when response is acknowledged.
Gets information about the specified pump. See [`SLGetPumpStatus`](#slgetpumpstatus) documentation for argument values. Emits the `getPumpStatus` event when response is acknowledged. `senderId` is an optional 16-bit integer and will be present as the `senderId` field on the returned message.
#### getSaltCellConfig(senderId)
Requests salt cell status/configuration from the connected unit (requires an IntelliChlor or compatible salt cell). Emits the `saltCellConfig` event when the response comes back. `senderId` is an optional 16-bit integer and will be present as the `senderId` field on the returned message.
#### getScheduleData(scheduleType, senderId)
Retrieves a list of schedule events of the specified type. See [`SLGetScheduleData`](#slgetscheduledata) documentation for argument values. Emits the `getScheduleData` event when response is acknowledged. `senderId` is an optional 16-bit integer and will be present as the `senderId` field on the returned message.
#### getSystemTime(senderId)
Retrieves the current time the system is set to. Emits the `getSystemTime` event when response is received. `senderId` is an optional 16-bit integer and will be present as the `senderId` field on the returned message.
#### getVersion(senderId)
Requests the system version string from the connected unit. Emits the `version` event when the response comes back. `senderId` is an optional 16-bit integer and will be present as the `senderId` field on the returned message.
#### removeClient(clientId, senderId)
No longer receive `poolStatus` messages from controller. Emits the `removeClient` event when the request to remove a client is acknowledged. Takes a random number `clientId` that should match a previously registered client with `addClient`. `senderId` is an optional 16-bit integer and will be present as the `senderId` field on the returned message.
#### sendLightCommand(controllerId, command, senderId)
Sends a lighting command. See [`SLLightControlMessage`](#sllightcontrolmessage) documentation for argument values. Emits the `sentLightCommand` event when response is acknowledged. `senderId` is an optional 16-bit integer and will be present as the `senderId` field on the returned message.
Note that better/more complete handling of lighting is desired, but I have yet to find all the commands I need to implement to make that happen. This currently sends each command to all lights and there is no ability to send to an individual light. Pull requests adding more functionality here would be most welcome.
### setSaltCellOutput(controllerId, poolOutput, spaOutput)
#### setCircuitRuntimebyId(circuitId, runTime, senderId)
Sets the salt cell's output levels. See [`SLSetSaltCellConfigMessage`](#slsetsaltcellconfigmessage) documentation for argument values. Emits the `setSaltCellConfig` event when response is acknowledged.
Configures default run-time of a circuit, usually referred to as the 'egg timer'. This also applies to 'run-once' programs as this will set the length of the program. See [`SLSetCircuitRuntimeById`](#slsetcircuitruntimebyid) documentation for argument values. Emits the `setCircuitRuntimeById` event when response is acknowledged. `senderId` is an optional 16-bit integer and will be present as the `senderId` field on the returned message.
#### setCircuitState(controllerId, circuitId, circuitState, senderId)
Activates or deactivates a circuit. See [`SLSetCircuitStateMessage`](#slsetcircuitstatemessage) documentation for argument values. Emits the `circuitStateChanged` event when response is acknowledged. `senderId` is an optional 16-bit integer and will be present as the `senderId` field on the returned message.
#### setHeatMode(controllerId, bodyType, heatMode, senderId)
Sets the preferred heat mode. See [`SLSetHeatModeMessage`](#slsetheatmodemessage) documentation for argument values. Emits the `heatModeChanged` event when response is acknowledged. `senderId` is an optional 16-bit integer and will be present as the `senderId` field on the returned message.
#### setSaltCellOutput(controllerId, poolOutput, spaOutput, senderId)
Sets the salt cell's output levels. See [`SLSetSaltCellConfigMessage`](#slsetsaltcellconfigmessage) documentation for argument values. Emits the `setSaltCellConfig` event when response is acknowledged. `senderId` is an optional 16-bit integer and will be present as the `senderId` field on the returned message.
#### setScheduleEventById(scheduleId, circuitId, startTime, stopTime, dayMask, flags, heatCmd, heatSetPoint, senderId)
Configures a schedule event. See [`SLSetScheduleEventById`](#slsetscheduleeventbyid) documentation for argument values. Emits the `setScheduleEventById` or `scheduleChanged` event when response is acknowledged (listen for both). `senderId` is an optional 16-bit integer and will be present as the `senderId` field on the returned message.
#### setSetPoint(controllerId, bodyType, temperature, senderId)
Sets the heating setpoint for any body. See [`SLSetHeatSetPointMessage`](#slsetheatsetpointmessage) documentation for argument values. Emits the `setPointChanged` event when response is acknowledged. `senderId` is an optional 16-bit integer and will be present as the `senderId` field on the returned message.
#### setPumpFlow(pumpId, circuitId, setPoint, isRPMs, senderId)
Sets flow setting for a pump/circuit combination. See [`SLSetPumpFlow`](#slsetpumpflow) documentation for argument values. Emits the `setPumpFlow` event when response is acknowledged. `senderId` is an optional 16-bit integer and will be present as the `senderId` field on the returned message.
#### setSystemTime(date, adjustForDST, senderId)
Sets the current date and time of the ScreenLogic system. Emits the `setSystemTime` event when request is acknowledged. `date` must be a `Date` instance holding the date/time to set, and `adjustForDST` must be a boolean indicating whether the system should adjust for daylight saving time or not. `senderId` is an optional 16-bit integer and will be present as the `senderId` field on the returned message.
### Events
* `loggedIn` - Indicates that a connection to the server has been established and the login process completed. `get` methods can be called once this event has been emitted.
* `version` - Indicates that a response to `getVersion()` has been received. Event handler receives a [`SLVersionMessage`](#slversionmessage) object.
* `poolStatus` - Indicates that a response to `getPoolStatus()` has been received. Event handler receives a [`SLPoolStatusMessage`](#slpoolstatusmessage) object.
* `chemicalData` - Indicates that a response to `getChemicalData()` has been received. Event handler receives a [`SLChemDataMessage`](#slchemdatamessage) object.
* `saltCellConfig` - Indicates that a response to `getSaltCellConfig()` has been received. Event handler receives a [`SLSaltCellConfigMessage`](#slsaltcellconfigmessage) object.
* `controllerConfig` - Indicates that a response to `getControllerConfig()` has been received. Event handler receives a [`SLControllerConfigMessage`](#slcontrollerconfigmessage) object.
* `circuitStateChanged` - Indicates that a response to `setCircuitState()` has been received. Event handler receives a [`SLSetCircuitStateMessage`](#slsetcircuitstatemessage) object.
* `setPointChanged` - Indicates that a response to `setSetPoint()` has been received. Event handler receives a [`SLSetHeatSetPointMessage`](#slsetheatsetpointmessage) object.
* `heatModeChanged` - Indicates that a response to `setHeatMode()` has been received. Event handler receives a [`SLSetHeatModeMessage`](#slsetheatmodemessage) object.
* `sentLightCommand` - Indicates that a response to `sendLightCommand()` has been received. Event handler receives a [`SLLightControlMessage`](#sllightcontrolmessage) object.
* `setSaltCellConfig` - Indicates that a response to `setSaltCellOutput()` has been received. Event handler receives a [`SLSetSaltCellConfigMessage`](#slsetsaltcellconfigmessage) object.
* `loginFailed` - Indicates that a remote login attempt via supplying a system address and password to `UnitConnection` has failed likely due to the incorrect password being used.
* `addClient` - Indicates that a response to `addClient()` has been received. Event handler receives a [`SLAddClient`](#sladdclient) object.
* `addNewScheduleEvent` - Indicates that a response to `addNewScheduleEvent()` has been received which contains the created `scheduleId` to be used later for setting up the properties. Event handler receives a [`SLAddNewScheduleEvent`](#sladdnewscheduleevent) object.
* `badParameter` - Indicates that a bad parameter has been supplied to a function. This can be triggered, for example, by sending the wrong controller ID to a `set` function.
* `cancelDelay` - Indicates that a response to `cancelDelay()` has been received. Event handler receives a [`SLCancelDelay`](#slcanceldelay) object.
* `chemicalData` - Indicates that a response to `getChemicalData()` has been received. Event handler receives a [`SLChemDataMessage`](#slchemdatamessage) object.
* `circuitStateChanged` - Indicates that a response to `setCircuitState()` has been received. Event handler receives a [`SLSetCircuitStateMessage`](#slsetcircuitstatemessage) object.
* `controllerConfig` - Indicates that a response to `getControllerConfig()` has been received. Event handler receives a [`SLControllerConfigMessage`](#slcontrollerconfigmessage) object.
* `deleteScheduleById` - Indicates that a response to `deleteScheduleById()` has been received. Event handler receives a [`SLDeleteScheduleEventById`](#sldeletescheduleeventbyid) object.
* `error` - Indicates that an unhandled error was caught (such as the connection timing out)
* `getHistoryData` - Indicates that history data for the requested timeframe is ready. Event handler receives a [`SLGetHistoryData`](#slgethistorydata) object.
* `getHistoryDataPending` - Indicates that the `getHistoryData()` request has been received and is being processed.
* `getPumpStatus` - Indicates that a response to `getPumpStatus()` has been received. Event handler receives a [`SLGetPumpStatus`](#slgetpumpstatus) object.
* `getScheduleData` - Indicates that a response to `getScheduleData()` has been received. Event handler receives a [`SLGetScheduleData`](#slgetscheduledata) object.
* `getSystemTime` - Indicates that a response to `getSystemTime()` has been received. Event handler receives a [`SLGetSystemTime`](#slgetsystemtime) object.
* `heatModeChanged` - Indicates that a response to `setHeatMode()` has been received. Event handler receives a [`SLSetHeatModeMessage`](#slsetheatmodemessage) object.
* `loggedIn` - Indicates that a connection to the server has been established and the login process completed. `get` methods can be called once this event has been emitted.
* `loginFailed` - Indicates that a remote login attempt via supplying a system address and password to `UnitConnection` has failed likely due to the incorrect password being used.
* `poolStatus` - Indicates that a response to `getPoolStatus()` has been received. Event handler receives a [`SLPoolStatusMessage`](#slpoolstatusmessage) object.
* `removeClient` - Indicates that a response to `removeClient()` has been received. Event handler receives a [`SLRemoveClient`](#slremoveclient) object.
* `saltCellConfig` - Indicates that a response to `getSaltCellConfig()` has been received. Event handler receives a [`SLSaltCellConfigMessage`](#slsaltcellconfigmessage) object.
* `scheduleChanged` - Indicates that a response to adding, deleting, or setting a schedule has been received. Event handler receives nothing. This seems to be arbitrarily returned sometimes instead of a normal ack by the system.
* `sentLightCommand` - Indicates that a response to `sendLightCommand()` has been received. Event handler receives a [`SLLightControlMessage`](#sllightcontrolmessage) object.
* `setCircuitRuntimeById` - Indicates that a response to `setCircuitRuntimeById()` has been received. Event handler receives a [`SLSetCircuitRuntimeById`](#slsetcircuitruntimebyid) object.
* `setPumpFlow` - Indicates that a response to `setPumpFlow()` has been received. Event handler receives a [`SLSetPumpFlow`](#slsetpumpflow) object.
* `setPointChanged` - Indicates that a response to `setSetPoint()` has been received. Event handler receives a [`SLSetHeatSetPointMessage`](#slsetheatsetpointmessage) object.
* `setSaltCellConfig` - Indicates that a response to `setSaltCellOutput()` has been received. Event handler receives a [`SLSetSaltCellConfigMessage`](#slsetsaltcellconfigmessage) object.
* `setScheduleEventById` - Indicates that a response to `setScheduleEventById()` has been received. Event handler receives a [`SLSetScheduleEventById`](#slsetscheduleeventbyid) object.
* `setSystemTime` - Indicates that a response to `setSystemTime()` has been received. Event handler receives a [`SLSetSystemTime`](#slsetsystemtime) object if the request was valid, or `null` if the request was invalid (input parameters were not of the required types).
* `unknownCommand` - Indicates that an unknown command was issued to ScreenLogic (should not be possible to trigger when using the supplied `UnitConnection` methods).
* `version` - Indicates that a response to `getVersion()` has been received. Event handler receives a [`SLVersionMessage`](#slversionmessage) object.
### Properties
#### Properties
* `address` - string representing the IPv4 address of the found server
* `type` - integer representing the type of server found (will always be 2)
@ -239,72 +347,70 @@ Sets the salt cell's output levels. See [`SLSetSaltCellConfigMessage`](#slsetsal
* `gatewaySubtype` - byte
* `gatewayName` - string representing the server's name. Will be in the format Pentair: xx-xx-xx
## SLVersionMessage
### All messages
Passed as an argument to the emitted `version` event handler.
Information about features common to all the below SL Message types.
### Properties
#### decodeTime(time)
* `version` - a string representing the system's version
Interprets a time integer recorded as minutes past midnight and returns the ScreenLogic string representation of it in 24-hour time.
## SLPoolStatusMessage
#### encodeTime(time)
Passed as an argument to the emitted `poolStatus` event handler.
Interprets the string representing 24-hour time and returns an integer of minutes past midnight.
### isDeviceReady()
#### decodeDayMask(mask)
Returns a bool indicating whether the device is in a normal operating state.
Converts a day mask from, for example, `SLGetScheduleData`'s events[idx].days property into a `DAY_VALUES` array for ease of use.
### isDeviceSync()
#### encodeDayMask(days)
Returns a bool.
Converts an array of DAY_VALUES into a mask used by, for example, `SLGetScheduleData`'s events[idx].days property.
### isDeviceServiceMode()
#### getDayValue(dayName)
Returns a bool indicating whether the device is in service mode or not.
Returns the value of a given `DAY_VALUES` day name.
### isSpaActive()
`DAY_VALUES` is defined as the following array for simplicity of checking whether a specific day is set in a mask:
Returns a bool indicating whether the spa is currently active or not.
```js
const DAY_VALUES = [
['Mon', 0x1 ],
['Tue', 0x2 ],
['Wed', 0x4 ],
['Thu', 0x8 ],
['Fri', 0x10 ],
['Sat', 0x20 ],
['Sun', 0x40 ],
];
```
### isPoolActive()
#### Properties
Returns a bool indicating whether the pool is currently active or not.
* `senderId` - an integer matching whatever was passed as the `senderId` argument when making the initial request (default 0)
* `messageId` - an integer indicating the ScreenLogic ID for this message
### Properties
### SLAddClient
* `ok` - can be interpreted with `isDevice...` methods.
* `freezeMode` - byte representing whether the device is in freeze mode or not.
* `remotes` - byte
* `poolDelay` - byte
* `spaDelay` - byte
* `cleanerDelay` - byte
* `airTemp` - integer representing the current temperature (check controller config to see if it's in celsius or fahrenheit)
* `currentTemp` - array of size 0-2 indicating current temperature of each body as an integer (pool: 0, spa: 1) (check controller config to see if it's in celsius or fahrenheit)
* `heatStatus` - array of size 0-2 indicating whether heat is active or not for each body as an integer (pool: 0, spa: 1)
* `setPoint` - array of size 0-2 holding the heating set point for each body as an integer (pool: 0, spa: 1) (check controller config to see if it's in celsius or fahrenheit)
* `coolSetPoint` - array of size 0-2 holding the cooling set point for each body as an integer (pool: 0, spa: 1) (check controller config to see if it's in celsius or fahrenheit)
* `heatMode` - array of size 0-2 indicating whether heating is enabled or not for each body as an integer (pool: 0, spa: 1)
* `circuitArray` - array holding all circuits in the system
* `id` - integer representing the circuit's ID (spa is 500, pool is 505)
* `state` - integer indicating whether the circuit is on or not (0/1)
* `colorSet` - byte
* `colorPos` - byte
* `colorStagger` - byte
* `delay` - byte
* `pH` - float indicating the current pH level (e.g.: 7.62)
* `orp` - integer indicating the current ORP value if available (e.g.: 650)
* `saturation` - float indicating the water balance/saturation level (e.g.: -0.13)
* `saltPPM` - integer indicating the salt level in parts-per-million (e.g.: 3000)
* `pHTank` - integer indicating the fill level of the pH tank (e.g.: 4)
* `orpTank` - integer indicating the fill level of the ORP tank
* `alarms` - integer indicating how many alarms are currently active
Passed as an argument to the emitted `addClient` event.
## SLChemDataMessage
### SLAddNewScheduleEvent
Passed as an argument to the emitted `addNewScheduleEvent` event. Adds a new event to the specified schedule type, either 0 for regular events or 1 for one-time events.
#### Properties
* `scheduleType` - 0 indicates regular scheduled events, 1 indicates a run-once event
### SLCancelDelay
Passed as an argument to the emitted `cancelDelay` event.
### SLChemDataMessage
Passed as an argument to the emitted `chemicalData` event handler.
### Properties
#### Properties
* `isValid` - boolean indicating whether we got a valid response back or not
* `pH` - float indicating the current pH level
@ -323,56 +429,55 @@ Passed as an argument to the emitted `chemicalData` event handler.
* `scaling` - boolean indicating whether the water balance is scaling or not
* `error` - boolean indicating whether there's currently an error in the chem system or not
## SLSaltCellConfigMessage
Passed as an argument to the emitted `saltCellConfig` event handler.
### Properties
* `installed` - boolean indicating whether a salt cell is installed or not
* `status` - integer bitmask
* `level1` - integer indicating the output level of the salt cell for the pool. I believe this operates on a 0-100 scale
* `level2` - integer indicating the output level of the salt cell for the spa. I believe this operates on a 0-100 scale
* `salt` - integer indicating salt level in parts-per-million
* `flags` - integer bitmask
* `superChlorTimer` - integer
## SLSetSaltCellConfigMessage
Passed as an argument to the emitted `setSaltCellConfig` event. The passed version is empty, however, since the response is just an acknowledgement of receipt of the set command.
### Properties
* `controllerId` - integer indicating the ID of the controller to send this command to.
* Note that while `SLControllerConfigMessage` includes a controllerId, this ID, in my experience, should always be 0.
* `poolOutput` - integer indicating the output level of the salt cell for the pool. I believe this operates on a 0-100 scale.
* `spaOutput` - integer indicating the output level of the salt cell for the spa. I believe this operates on a 0-100 scale.
## SLControllerConfigMessage
### SLControllerConfigMessage
Passed as an argument to the emitted `controllerConfig` event handler.
### hasSolar()
#### hasSolar()
Returns a bool indicating whether the system has solar present. (Helper method for interpreting the value in `equipFlags`.)
### hasSolarAsHeatpump()
#### hasSolarAsHeatpump()
Returns a bool indicating whether the system has a solar heatpump (UltraTemp, ThermalFlo) present. (Helper method for interpreting the value in `equipFlags`.)
### hasChlorinator()
#### hasChlorinator()
Returns a bool indicating whether the system has a chlorinator present. (Helper method for interpreting the value in `equipFlags`.)
### hasCooling()
#### hasCooling()
Returns a bool indicating whether the system has a cooler present. (Helper method for interpreting the value in `equipFlags`.)
### hasIntellichem()
#### hasIntellichem()
Returns a bool indicating whether the system has an IntelliChem chemical management system present. (Helper method for interpreting the value in `equipFlags`.)
### Properties
#### isEasyTouch()
Returns a bool indicating whether the system is an EasyTouch system or not. (Helper method for interpreting the value in `controllerType`.)
#### isIntelliTouch()
Returns a bool indicating whether the system is an IntelliTouch system or not. (Helper method for interpreting the value in `controllerType`.)
#### isEasyTouchLite()
Returns a bool indicating whether the system is an EasyTouch Lite system or not. (Helper method for interpreting the value in `controllerType` and `hwType`.)
#### isDualBody()
Returns a bool indicating whether the system is dual-body or not. (Helper method for interpreting the value in `controllerType`.)
#### isChem2()
Returns a bool indicating whether the system is a Chem2 system or not. (Helper method for interpreting the value in `controllerType` and `hwType`.)
#### getCircuitByDeviceId(deviceId)
Returns the `bodyArray` entry for the circuit matching the given device id. This is most useful with an [`SLGetPumpStatus`](#slgetpumpstatus) message.
#### Properties
* `controllerId` - integer indicating the controller's ID
* `minSetPoint` - array (size 2) indicating the minimum setpoint available for the pool (index 0) or spa (index 1)
@ -402,45 +507,116 @@ Returns a bool indicating whether the system has an IntelliChem chemical managem
* `interfaceTabFlags` - integer
* `showAlarms` - integer
## SLSetCircuitStateMessage
### SLDeleteScheduleEventById
Passed as an argument to the emitted `circuitStateChanged` event. The passed version is empty, however, since the response is just an acknowledgement of receipt of the set command.
Passed as an argument to the emitted `deleteScheduleEventById` event. Deletes a scheduled event with specified id.
### Properties
#### Properties
* `controllerId` - integer indicating the ID of the controller to send this command to.
* Note that while `SLControllerConfigMessage` includes a controllerId, this ID, in my experience, should always be 0.
* `circuitId` - integer indicating the ID of the circuit to set the state of.
* This ID can be retrieved from `SLControllerConfigMessage`'s `bodyArray` property.
* `circuitState` - integer indicating whether to switch the circuit on (`1`) or off (`0`).
* `scheduleId` - the scheduleId of the schedule to be deleted
## SLSetHeatSetPointMessage
### SLGetGatewayDataMessage
Passed as an argument to the emitted `setPointChanged` event. The passed version is empty, however, since the response is just an acknowledgement of receipt of the set command.
Passed as an argument to the emitted `gatewayFound` event. Contains information about the remote unit's status and access properties.
### Properties
#### Properties
* `controllerId` - integer indicating the ID of the controller to send this command to.
* Note that while `SLControllerConfigMessage` includes a controllerId, this ID, in my experience, should always be 0.
* `bodyType` - integer indicating the type of body to set the setpoint of. The pool is body `0` and the spa is body `1`.
* `temperature` - integer indicating the desired setpoint. This is presumably in whatever units your system is set to (celsius or fahrenheit).
* `gatewayFound` - boolean indicating whether a unit was found
* `licenseOK` - boolean indicating if the license is valid (I've never seen this be false)
* `ipAddr` - string containing the ipv4 address to remotely connect to this unit
* `port` - number containing the port to connect to the unit
* `portOpen` - boolean indicating whether or not the port is open and able to be connected to
* `relayOn` - boolean indicating whether the relay is on (unsure what exactly this indicates; it's always been false in my tests)
## SLSetHeatModeMessage
### SLGetHistoryData
Passed as an argument to the emitted `heatModeChanged` event. The passed version is empty, however, since the response is just an acknowledgement of receipt of the set command.
Passed as an argument to the emitted `getHistoryData` event. Contains information about the remote unit's temperature and circuit on/off times over time.
### Properties
#### Properties
* `controllerId` - integer indicating the ID of the controller to send this command to.
* Note that while `SLControllerConfigMessage` includes a controllerId, this ID, in my experience, should always be 0.
* `bodyType` - integer indicating the type of body to set the setpoint of. The pool is body `0` and the spa is body `1`.
* `heatMode` - integer indicating the desired heater mode. Valid values are: 0: "Off", 1: "Solar", 2 : "Solar Preferred", 3 : "Heat Pump", 4: "Don't Change"
* `airTemps` - array of objects containing the air temperature over time. Each object contains a `time` key containing a Javascript Date object, and a `temp` key containing the temperature as an integer.
* `poolTemps` - array of objects containing the pool temperature over time. Each object contains a `time` key containing a Javascript Date object, and a `temp` key containing the temperature as an integer.
* `poolSetPointTemps` - array of objects containing the pool setpoint over time. Each object contains a `time` key containing a Javascript Date object, and a `temp` key containing the temperature as an integer.
* `spaTemps` - array of objects containing the spa temperature over time. Each object contains a `time` key containing a Javascript Date object, and a `temp` key containing the temperature as an integer.
* `spaSetPointTemps` - array of objects containing the spa setpoint over time. Each object contains a `time` key containing a Javascript Date object, and a `temp` key containing the temperature as an integer.
* `poolRuns` - array of objects containing the pool on/off times over time. Each object contains an `on` key containing a Javascript Date object for when the circuit turned on, and an `off` key containing a Javascript Date object for when the circuit turned off.
* `spaRuns` - array of objects containing the spa on/off times over time. Each object contains an `on` key containing a Javascript Date object for when the circuit turned on, and an `off` key containing a Javascript Date object for when the circuit turned off.
* `solarRuns` - array of objects containing the solar on/off times over time. Each object contains an `on` key containing a Javascript Date object for when the circuit turned on, and an `off` key containing a Javascript Date object for when the circuit turned off.
* `heaterRuns` - array of objects containing the heater on/off times over time. Each object contains an `on` key containing a Javascript Date object for when the circuit turned on, and an `off` key containing a Javascript Date object for when the circuit turned off.
* `lightRuns` - array of objects containing the light on/off times over time. Each object contains an `on` key containing a Javascript Date object for when the circuit turned on, and an `off` key containing a Javascript Date object for when the circuit turned off.
## SLLightControlMessage
### SLGetPumpStatus
Passed as an argument to the emitted `sentLightCommand` event. The passed version is empty, however, since the response is just an acknowledgement of receipt of the light command.
Passed as an argument to the emitted `getPumpStatus` event. Gets information about the specified pump.
### Properties
#### Properties
* `pumpId` - id of pump to get information about, first pump is 0
#### Return Values
* `isRunning` - boolean that says if pump is running
* `pumpType` - 0 if invalid pump id or one of the IntelliFlo constants:
* ScreenLogic.PUMP_TYPE_INTELLIFLOVF
* ScreenLogic.PUMP_TYPE_INTELLIFLOVS
* ScreenLogic.PUMP_TYPE_INTELLIFLOVSF
* `pumpWatts` - current Watts usage of the pump
* `pumpRPMs` - current RPMs of the pump
* `pumpGPMs` - current GPMs of the pump
* `pumpSetting` - Array of 8 items each containing
* `circuitId` - Circuit Id (CircuitId matched data returned by [`SLControllerConfigMessage`](#slcontrollerconfigmessage)'s `getCircuitByDeviceId()`)
* `pumpSetPoint` - the set point for this pump/circuit combo (in either RPMs or GPMs depending on the value of `isRPMs`)
* `isRPMs` - boolean indicating if the set point is in RPMs (false means it's in GPMs)
* `pumpUnknown1` - unknown data; always 0
* `pumpUnknown2` - unknown data; always 255
### SLGetScheduleData
Passed as an argument to the emitted `getScheduleData` event. Retrieves a list of schedule events of the specified type, either 0 for regular events or 1 for one-time events.
#### Properties
* `eventCount` - the number of `events` returned
* `events` - array containing:
* `scheduleId` - the associated scheduleId
* `circuitId` - the circuit this schedule affects
* `startTime` - the start time of the event, specified as a string in 24-hour time, so, for example, 6:00AM would be '0600' (see [conversion functions](#decodetimetime))
* `stopTime` - the stop time of the event, specified as a string in 24-hour time, so, for example, 6:00AM would be '0600' (see [conversion functions](#decodetimetime))
* `dayMask` - 7-bit mask that determines which days the schedule is active for, MSB is always 0, valid numbers 1-127 (see [conversion functions](#decodedaymaskmask))
* `flags`
* bit 0 is the schedule type, if 0 then regular event, if 1 its a run-once
* bit 1 indicates whether heat setPoint should be changed
* `heatCmd` - integer indicating the desired heater mode. Valid values are:
* ScreenLogic.HEAT_MODE_OFF
* ScreenLogic.HEAT_MODE_SOLAR
* ScreenLogic.HEAT_MODE_SOLARPREFERRED
* ScreenLogic.HEAT_MODE_HEATPUMP
* ScreenLogic.HEAT_MODE_DONTCHANGE
* `heatSetPoint` - the temperature set point if heat is to be changed (ignored if bit 1 of flags is 0)
* `days` - which days this schedule is active for; this is just the `dayMask` property run through [`decodeDayMask()`](#decodedaymaskmask) for convenience
### SLGetSystemTime
Contains information about the system's current time and date. Passed as an argument to the emitted `getSystemTime` event.
#### Properties
* `date` - `Date` instance representing the current system datetime (preferred, the other properties are derived from this one and provided for backward compatibility purposes)
* `year` - short representing current system year
* `month` - short representing current system month (where 1 is January, 2 is February, etc.)
* `day` - short representing current system day of the month
* `dayOfWeek` - short representing current system day of the week (where 1 is Sunday and 7 is Saturday)
* `hour` - short representing current system hour (24-hour time where 0 is midnight, 13 is 1PM, etc.)
* `minute` - short representing current system minute
* `second` - short representing current system second
* `millisecond` - short representing current system millisecond
* `adjustForDST` - bool indicating whether the system should adjust for daylight saving time or not
### SLLightControlMessage
Passed as an argument to the emitted `sentLightCommand` event.
#### Properties
* `controllerId` - integer indicating the ID of the controller to send this command to.
* Note that while `SLControllerConfigMessage` includes a controllerId, this ID, in my experience, should always be 0.
@ -464,15 +640,180 @@ Passed as an argument to the emitted `sentLightCommand` event. The passed versio
* ScreenLogic.LIGHT_CMD_COLOR_WHITE
* ScreenLogic.LIGHT_CMD_COLOR_PURPLE
## SLGetGatewayDataMessage
### SLPoolStatusMessage
Passed as an argument to the emitted `gatewayFound` event. Contains information about the remote unit's status and access properties.
Passed as an argument to the emitted `poolStatus` event handler.
### Properties
#### isDeviceReady()
* `gatewayFound` - boolean indicating whether a unit was found
* `licenseOK` - boolean indicating if the license is valid (I've never seen this be false)
* `ipAddr` - string containing the ipv4 address to remotely connect to this unit
* `port` - number containing the port to connect to the unit
* `portOpen` - boolean indicating whether or not the port is open and able to be connected to
* `relayOn` - boolean indicating whether the relay is on (unsure what exactly this indicates; it's always been false in my tests)
Returns a bool indicating whether the device is in a normal operating state.
#### isDeviceSync()
Returns a bool.
#### isDeviceServiceMode()
Returns a bool indicating whether the device is in service mode or not.
#### isSpaActive()
Returns a bool indicating whether the spa is currently active or not.
#### isPoolActive()
Returns a bool indicating whether the pool is currently active or not.
#### Properties
* `ok` - can be interpreted with `isDevice...` methods.
* `freezeMode` - byte representing whether the device is in freeze mode or not.
* `remotes` - byte
* `poolDelay` - byte
* `spaDelay` - byte
* `cleanerDelay` - byte
* `airTemp` - integer representing the current temperature (check controller config to see if it's in celsius or fahrenheit)
* `currentTemp` - array of size 0-2 indicating current temperature of each body as an integer (pool: 0, spa: 1) (check controller config to see if it's in celsius or fahrenheit)
* `heatStatus` - array of size 0-2 indicating whether heat is active or not for each body as an integer (pool: 0, spa: 1)
* `setPoint` - array of size 0-2 holding the heating set point for each body as an integer (pool: 0, spa: 1) (check controller config to see if it's in celsius or fahrenheit)
* `coolSetPoint` - array of size 0-2 holding the cooling set point for each body as an integer (pool: 0, spa: 1; the spa seems to always track air temperature for this, however) (check controller config to see if it's in celsius or fahrenheit)
* `heatMode` - array of size 0-2 indicating whether heating is enabled or not for each body as an integer (pool: 0, spa: 1)
* `circuitArray` - array holding all circuits in the system
* `id` - integer representing the circuit's ID (spa is 500, pool is 505)
* `state` - integer indicating whether the circuit is on or not (0/1)
* `colorSet` - byte
* `colorPos` - byte
* `colorStagger` - byte
* `delay` - byte
* `pH` - float indicating the current pH level (e.g.: 7.62)
* `orp` - integer indicating the current ORP value if available (e.g.: 650)
* `saturation` - float indicating the water balance/saturation level (e.g.: -0.13)
* `saltPPM` - integer indicating the salt level in parts-per-million (e.g.: 3000)
* `pHTank` - integer indicating the fill level of the pH tank (e.g.: 4)
* `orpTank` - integer indicating the fill level of the ORP tank
* `alarms` - integer indicating how many alarms are currently active
### SLRemoveClient
Passed as an argument to the emitted `removeClient` event.
### SLSaltCellConfigMessage
Passed as an argument to the emitted `saltCellConfig` event handler.
#### Properties
* `installed` - boolean indicating whether a salt cell is installed or not
* `status` - integer bitmask
* `level1` - integer indicating the output level of the salt cell for the pool. I believe this operates on a 0-100 scale
* `level2` - integer indicating the output level of the salt cell for the spa. I believe this operates on a 0-100 scale
* `salt` - integer indicating salt level in parts-per-million
* `flags` - integer bitmask
* `superChlorTimer` - integer
### SLSetCircuitRuntimeById
Passed as an argument to the emitted `setCircuitRuntimebyId` event. Configures default run-time of a circuit, usually referred to as the 'egg timer'. This also applies to 'run-once' programs as this will set the length of the program.
#### Properties
* `circuitId` - id of the circuit to which this event applies to
* `runTime` - integer specifying the run time in minutes
### SLSetCircuitStateMessage
Passed as an argument to the emitted `circuitStateChanged` event.
#### Properties
* `controllerId` - integer indicating the ID of the controller to send this command to.
* Note that while `SLControllerConfigMessage` includes a controllerId, this ID, in my experience, should always be 0.
* `circuitId` - integer indicating the ID of the circuit to set the state of.
* This ID can be retrieved from `SLControllerConfigMessage`'s `bodyArray` property.
* `circuitState` - integer indicating whether to switch the circuit on (`1`) or off (`0`).
### SLSetHeatModeMessage
Passed as an argument to the emitted `heatModeChanged` event.
#### Properties
* `controllerId` - integer indicating the ID of the controller to send this command to.
* Note that while `SLControllerConfigMessage` includes a controllerId, this ID, in my experience, should always be 0.
* `bodyType` - integer indicating the type of body to set the setpoint of. The pool is body `0` and the spa is body `1`.
* `heatMode` - integer indicating the desired heater mode. Valid values are:
* ScreenLogic.HEAT_MODE_OFF
* ScreenLogic.HEAT_MODE_SOLAR
* ScreenLogic.HEAT_MODE_SOLARPREFERRED
* ScreenLogic.HEAT_MODE_HEATPUMP
* ScreenLogic.HEAT_MODE_DONTCHANGE
### SLSetHeatSetPointMessage
Passed as an argument to the emitted `setPointChanged` event.
#### Properties
* `controllerId` - integer indicating the ID of the controller to send this command to.
* Note that while `SLControllerConfigMessage` includes a controllerId, this ID, in my experience, should always be 0.
* `bodyType` - integer indicating the type of body to set the setpoint of. The pool is body `0` and the spa is body `1`.
* `temperature` - integer indicating the desired setpoint. This is presumably in whatever units your system is set to (celsius or fahrenheit).
### SLSetPumpFlow
Passed as an argument to the emitted `setPumpFlow` event. Sets flow setting for a pump/circuit combination.
#### Properties
* `pumpId` - id of pump to get information about, first pump is 0
* `circuitId` - index of circuit for which to change the set point (index is relative to data returned by [`SLGetPumpStatus`](#slgetpumpstatus))
* `setPoint` - the value for which to set the pump/circuit combo
* `isRPMs` - boolean, `true` for RPMs, `false` for GPMs
### SLSetSaltCellConfigMessage
Passed as an argument to the emitted `setSaltCellConfig` event.
#### Properties
* `controllerId` - integer indicating the ID of the controller to send this command to.
* Note that while `SLControllerConfigMessage` includes a controllerId, this ID, in my experience, should always be 0.
* `poolOutput` - integer indicating the output level of the salt cell for the pool. I believe this operates on a 0-100 scale.
* `spaOutput` - integer indicating the output level of the salt cell for the spa. I believe this operates on a 0-100 scale.
### SLSetScheduleEventById
Passed as an argument to the emitted `setScheduleEventById` event. Configures an event with properties as described below.
#### Properties
* `scheduleId` - id of a schedule previously created, see [`SLAddNewScheduleEvent`](#sladdnewscheduleevent)
* `circuitId` - id of the circuit to which this event applies
* `startTime` - the start time of the event, specified as minutes since midnight (see [conversion functions](#encodetimetime))
* example: 6:00am would be 360
* example: 6:15am would be 375
* `stopTime` - the stop time of the event, specified as minutes since midnight (see [conversion functions](#encodetimetime))
* `dayMask`
* 7-bit mask that determines which days the schedule is active for, MSB is always 0, valid numbers 1-127
* `flags`
* bit 0 is the schedule type, if 0 then regular event, if 1 its a run-once
* bit 1 indicates whether heat setPoint should be changed
* `heatCmd` - integer indicating the desired heater mode. Valid values are:
* ScreenLogic.HEAT_MODE_OFF
* ScreenLogic.HEAT_MODE_SOLAR
* ScreenLogic.HEAT_MODE_SOLARPREFERRED
* ScreenLogic.HEAT_MODE_HEATPUMP
* ScreenLogic.HEAT_MODE_DONTCHANGE
* `heatSetPoint` - the temperature set point if heat is to be changed (ignored if bit 1 of flags is 0)
### SLSetSystemTime
Passed as an argument to the emitted `setSystemTime` event.
### SLVersionMessage
Passed as an argument to the emitted `version` event handler.
#### Properties
* `version` - a string representing the system's version

299
index.js
View File

@ -5,6 +5,9 @@ var net = require('net');
const EventEmitter = require('events');
const messages = require('./messages');
const Encoder = require('./PasswordEncoder').HLEncoder;
var debugFind = require('debug')('sl:find');
var debugRemote = require('debug')('sl:remote');
var debugUnit = require('debug')('sl:unit');
class FindUnits extends EventEmitter {
constructor() {
@ -14,8 +17,9 @@ class FindUnits extends EventEmitter {
this.finder.on('message', function(message, remote) {
_this.foundServer(message, remote);
}).on('close', function() {
// console.log('finder closed');
debugFind('closed');
}).on('error', function(e) {
debugFind('error: %O', e);
_this.emit('error', e);
});
}
@ -30,7 +34,7 @@ class FindUnits extends EventEmitter {
}
foundServer(message, remote) {
// console.log('Found something');
debugFind('found something');
if (message.length >= 40) {
var server = {
address: remote.address,
@ -41,11 +45,12 @@ class FindUnits extends EventEmitter {
gatewayName: message.toString('utf8', 12, 29),
};
// console.log(' type: ' + server.type + ', host: ' + server.address + ':' + server.port + ',
// identified as ' + server.gatewayName);
debugFind(' type: ' + server.type + ', host: ' + server.address + ':' + server.port + ', identified as ' + server.gatewayName);
if (server.type === 2) {
this.emit('serverFound', server);
}
} else {
debugFind(' unexpected message');
}
}
@ -53,7 +58,7 @@ class FindUnits extends EventEmitter {
var message = Buffer.alloc(8);
message[0] = 1;
this.finder.send(message, 0, message.length, 1444, '255.255.255.255');
// console.log("Looking for ScreenLogic hosts...");
debugFind('Looking for ScreenLogic hosts...');
}
close() {
@ -71,14 +76,15 @@ class RemoteLogin extends EventEmitter {
this.client.on('data', function(msg) {
_this.onClientMessage(msg);
}).on('close', function(had_error) {
// console.log('remote login server connection closed');
debugRemote('remote login server connection closed');
}).on('error', function(e) {
debugRemote('error: %o', e);
_this.emit('error', e);
});
}
connect() {
// console.log('connecting to dispatcher...');
debugRemote('connecting to dispatcher...');
var _this = this;
this.client.connect(500, 'screenlogicserver.pentair.com', function() {
_this.onConnected();
@ -86,13 +92,13 @@ class RemoteLogin extends EventEmitter {
}
onConnected() {
// console.log('connected to dispatcher');
debugRemote('connected to dispatcher');
this.client.write(new messages.SLGetGatewayDataMessage(this.systemName).toBuffer());
}
onClientMessage(msg) {
// console.log('received message of length ' + msg.length);
debugRemote('received message of length ' + msg.length);
if (msg.length < 4) {
return;
}
@ -100,11 +106,11 @@ class RemoteLogin extends EventEmitter {
var msgType = msg.readInt16LE(2);
switch (msgType) {
case messages.SLGetGatewayDataMessage.getResponseId():
// console.log(" it's a gateway response");
debugRemote(" it's a gateway response");
this.emit('gatewayFound', new messages.SLGetGatewayDataMessage(msg));
break;
default:
// console.log(" it's unknown. type: " + msgType);
debugRemote(" it's unknown. type: " + msgType);
break;
}
}
@ -127,6 +133,7 @@ class UnitConnection extends EventEmitter {
this.password = password;
this.client = new net.Socket();
this.client.setKeepAlive(true, 10 * 1000);
var _this = this;
var buffer = Buffer.alloc(1024);
var bufferIdx = 0;
@ -149,8 +156,9 @@ class UnitConnection extends EventEmitter {
bufferIdx = 0;
}
}).on('close', function(had_error) {
// console.log('unit connection closed');
debugUnit('closed');
}).on('error', function(e) {
debugUnit('error: %o', e);
_this.emit('error', e);
});
}
@ -160,7 +168,7 @@ class UnitConnection extends EventEmitter {
}
connect() {
// console.log("connecting...");
debugUnit('connecting...');
var _this = this;
this.client.connect(this.serverPort, this.serverAddress, function() {
_this.onConnected();
@ -168,72 +176,156 @@ class UnitConnection extends EventEmitter {
}
onConnected() {
// console.log('connected');
debugUnit('connected');
// console.log('sending init message...');
debugUnit('sending init message...');
this.client.write('CONNECTSERVERHOST\r\n\r\n');
// console.log('sending challenge message...');
debugUnit('sending challenge message...');
this.client.write(new messages.SLChallengeMessage().toBuffer());
}
login() {
// console.log('sending login message...');
debugUnit('sending login message...');
var password = new Encoder(this.password).getEncryptedPassword(this.challengeString);
this.client.write(new messages.SLLoginMessage(password).toBuffer());
}
getPoolStatus() {
// console.log('sending pool status query...');
this.client.write(new messages.SLPoolStatusMessage().toBuffer());
getPoolStatus(senderId) {
debugUnit('[%d] sending pool status query...', senderId || 0);
this.client.write(new messages.SLPoolStatusMessage(null, senderId).toBuffer());
}
getControllerConfig() {
// console.log('sending controller config query...');
this.client.write(new messages.SLControllerConfigMessage().toBuffer());
getControllerConfig(senderId) {
debugUnit('[%d] sending controller config query...', senderId || 0);
this.client.write(new messages.SLControllerConfigMessage(null, senderId).toBuffer());
}
getChemicalData() {
// console.log('sending chemical data query...');
this.client.write(new messages.SLChemDataMessage().toBuffer());
getChemicalData(senderId) {
debugUnit('[%d] sending chemical data query...', senderId || 0);
this.client.write(new messages.SLChemDataMessage(null, senderId).toBuffer());
}
getSaltCellConfig() {
// console.log('sending salt cell config query...');
this.client.write(new messages.SLSaltCellConfigMessage().toBuffer());
getSaltCellConfig(senderId) {
debugUnit('[%d] sending salt cell config query...', senderId || 0);
this.client.write(new messages.SLSaltCellConfigMessage(null, senderId).toBuffer());
}
getVersion() {
// console.log('sending version query...');
this.client.write(new messages.SLVersionMessage().toBuffer());
getVersion(senderId) {
debugUnit('[%d] sending version query...', senderId || 0);
this.client.write(new messages.SLVersionMessage(null, senderId).toBuffer());
}
getEquipmentConfiguration() {
this.client.write(new messages.SLEquipmentConfigurationMessage().toBuffer());
getEquipmentConfiguration(senderId) {
debugUnit('[%d] sending equipment configuration query...', senderId || 0);
this.client.write(new messages.SLEquipmentConfigurationMessage(null, senderId).toBuffer());
}
setCircuitState(controllerId, circuitId, circuitState) {
this.client.write(new messages.SLSetCircuitStateMessage(controllerId, circuitId, circuitState).toBuffer());
setCircuitState(controllerId, circuitId, circuitState, senderId) {
debugUnit('[%d] sending set circuit state command: controllerId: %d, circuitId: %d, circuitState: %d...', senderId || 0, controllerId, circuitId, circuitState);
this.client.write(new messages.SLSetCircuitStateMessage(controllerId, circuitId, circuitState, senderId).toBuffer());
}
setSetPoint(controllerId, bodyType, temperature) {
this.client.write(new messages.SLSetHeatSetPointMessage(controllerId, bodyType, temperature).toBuffer());
setSetPoint(controllerId, bodyType, temperature, senderId) {
debugUnit('[%d] sending set setpoint command: controllerId: %d, bodyType: %d, temperature: %d...', senderId || 0, controllerId, bodyType, temperature);
this.client.write(new messages.SLSetHeatSetPointMessage(controllerId, bodyType, temperature, senderId).toBuffer());
}
setHeatMode(controllerId, bodyType, heatMode) {
this.client.write(new messages.SLSetHeatModeMessage(controllerId, bodyType, heatMode).toBuffer());
setHeatMode(controllerId, bodyType, heatMode, senderId) {
debugUnit('[%d] sending set heatmode command: controllerId: %d, bodyType: %d, heatMode: %d...', senderId || 0, controllerId, bodyType, heatMode);
this.client.write(new messages.SLSetHeatModeMessage(controllerId, bodyType, heatMode, senderId).toBuffer());
}
sendLightCommand(controllerId, command) {
this.client.write(new messages.SLLightControlMessage(controllerId, command).toBuffer());
sendLightCommand(controllerId, command, senderId) {
debugUnit('[%d] sending light command: controllerId: %d, command: %d...', senderId || 0, controllerId, command);
this.client.write(new messages.SLLightControlMessage(controllerId, command, senderId).toBuffer());
}
setSaltCellOutput(controllerId, poolOutput, spaOutput) {
this.client.write(new messages.SLSetSaltCellConfigMessage(controllerId, poolOutput, spaOutput).toBuffer());
setSaltCellOutput(controllerId, poolOutput, spaOutput, senderId) {
debugUnit('[%d] sending set saltcell output command: controllerId: %d, poolOutput: %d, spaOutput: %d...', senderId || 0, controllerId, poolOutput, spaOutput);
this.client.write(new messages.SLSetSaltCellConfigMessage(controllerId, poolOutput, spaOutput, senderId).toBuffer());
}
getScheduleData(scheduleType, senderId) {
debugUnit('[%d] sending set schedule data query for scheduleType: %d...', senderId || 0, scheduleType);
this.client.write(new messages.SLGetScheduleData(null, scheduleType, senderId).toBuffer());
}
addNewScheduleEvent(scheduleType, senderId) {
debugUnit('[%d] sending add new schedule event command for scheduleType: %d...', senderId || 0, scheduleType);
this.client.write(new messages.SLAddNewScheduleEvent(null, scheduleType, senderId).toBuffer());
}
deleteScheduleEventById(scheduleId, senderId) {
debugUnit('[%d] sending delete schedule event command for scheduleId: %d...', senderId || 0, scheduleId);
this.client.write(new messages.SLDeleteScheduleEventById(scheduleId, senderId).toBuffer());
}
// todo: should this just accept a SLSetScheduleEventById message instead of all these args?
setScheduleEventById(scheduleId, circuitId, startTime, stopTime, dayMask, flags, heatCmd, heatSetPoint, senderId) {
debugUnit('[%d] sending set schedule event command for scheduleId: %d, circuitId: %d, startTime: %d, stopTime: %d, dayMask: %d, flags: %d, heatCmd: %d, heatSetPoint: %d...', senderId || 0, scheduleId, circuitId, startTime, stopTime, dayMask, flags, heatCmd, heatSetPoint);
this.client.write(new messages.SLSetScheduleEventById(null, scheduleId, circuitId, startTime, stopTime, dayMask, flags, heatCmd, heatSetPoint, senderId).toBuffer());
}
setCircuitRuntimebyId(circuitId, runTime, senderId) {
debugUnit('[%d] sending set circuit runtime command for circuitId: %d, runTime: %d...', senderId || 0, circuitId, runTime);
this.client.write(new messages.SLSetCircuitRuntimeById(circuitId, runTime, senderId).toBuffer());
}
getPumpStatus(pumpId, senderId) {
debugUnit('[%d] sending get pump status command for pumpId: %d...', senderId || 0, pumpId);
this.client.write(new messages.SLGetPumpStatus(null, pumpId, senderId).toBuffer());
}
setPumpFlow(pumpId, circuitId, setPoint, isRPMs, senderId) {
debugUnit('[%d] sending set pump flow command for pumpId: %d, circuitId: %d, setPoint: %d, isRPMs: %d...', senderId || 0, pumpId, circuitId, setPoint, isRPMs);
this.client.write(new messages.SLSetPumpFlow(pumpId, circuitId, setPoint, isRPMs, senderId).toBuffer());
}
cancelDelay(senderId) {
debugUnit('[%d] sending cancel delay command...', senderId || 0);
this.client.write(new messages.SLCancelDelay(senderId).toBuffer());
}
addClient(clientId, senderId) {
debugUnit('[%d] sending add client command, clientId %d...', senderId || 0, clientId);
this.client.write(new messages.SLAddClient(clientId, senderId).toBuffer());
}
removeClient(clientId, senderId) {
debugUnit('[%d] sending remove client command, clientId %d...', senderId || 0, clientId);
this.client.write(new messages.SLRemoveClient(clientId, senderId).toBuffer());
}
getSystemTime(senderId) {
debugUnit('[%d] sending get system time query...', senderId || 0);
this.client.write(new messages.SLGetSystemTime(null, senderId).toBuffer());
}
setSystemTime(date, shouldAdjustForDST, senderId) {
if (!(date instanceof Date)) {
debugUnit('setSystemTime() must receive valid Date object for the date argument');
this.emit('setSystemTime', null);
return;
}
if (typeof shouldAdjustForDST !== 'boolean') {
debugUnit('setSystemTime() must receive a boolean for the shouldAdjustForDST argument');
this.emit('setSystemTime', null);
return;
}
debugUnit('[%d] sending set system time command...', senderId || 0);
this.client.write(new messages.SLSetSystemTime(null, date, shouldAdjustForDST, senderId).toBuffer());
}
getHistoryData(fromTime, toTime, senderId) {
debugUnit('[%d] requesting history data from `%s` to `%s`', senderId || 0, fromTime || new Date(), toTime || new Date());
this.client.write(new messages.SLGetHistoryData(null, fromTime, toTime, senderId).toBuffer());
}
onClientMessage(msg) {
// console.log('received message of length ' + msg.length);
debugUnit('received message of length %d', msg.length);
if (msg.length < 4) {
return;
}
@ -241,67 +333,136 @@ class UnitConnection extends EventEmitter {
var msgType = msg.readInt16LE(2);
switch (msgType) {
case messages.SLChallengeMessage.getResponseId():
// console.log(" it's a challenge response");
debugUnit(" it's a challenge response");
this.challengeString = new messages.SLChallengeMessage(msg).challengeString;
this.login();
break;
case messages.SLLoginMessage.getResponseId():
// console.log(" it's a login response");
debugUnit(" it's a login response");
this.emit('loggedIn');
break;
case messages.SLPoolStatusMessage.getResponseId():
// console.log(" it's pool status");
debugUnit(" it's pool status");
this.emit('poolStatus', new messages.SLPoolStatusMessage(msg));
break;
case messages.SLControllerConfigMessage.getResponseId():
// console.log(" it's controller configuration");
debugUnit(" it's controller configuration");
this.emit('controllerConfig', new messages.SLControllerConfigMessage(msg));
break;
case messages.SLChemDataMessage.getResponseId():
// console.log(" it's chem data");
debugUnit(" it's chem data");
this.emit('chemicalData', new messages.SLChemDataMessage(msg));
break;
case messages.SLSaltCellConfigMessage.getResponseId():
// console.log(" it's salt cell config");
debugUnit(" it's salt cell config");
this.emit('saltCellConfig', new messages.SLSaltCellConfigMessage(msg));
break;
case messages.SLVersionMessage.getResponseId():
// console.log(" it's version");
debugUnit(" it's version");
this.emit('version', new messages.SLVersionMessage(msg));
break;
case messages.SLSetCircuitStateMessage.getResponseId():
// console.log(" it's circuit toggle ack");
this.emit('circuitStateChanged', new messages.SLSetCircuitStateMessage());
debugUnit(" it's circuit toggle ack");
this.emit('circuitStateChanged', new messages.SLSetCircuitStateMessage(msg));
break;
case messages.SLSetHeatSetPointMessage.getResponseId():
// console.log(" it's a setpoint ack");
this.emit('setPointChanged', new messages.SLSetHeatSetPointMessage());
debugUnit(" it's a setpoint ack");
this.emit('setPointChanged', new messages.SLSetHeatSetPointMessage(msg));
break;
case messages.SLSetHeatModeMessage.getResponseId():
// console.log(" it's a heater mode ack");
this.emit('heatModeChanged', new messages.SLSetHeatModeMessage());
debugUnit(" it's a heater mode ack");
this.emit('heatModeChanged', new messages.SLSetHeatModeMessage(msg));
break;
case messages.SLLightControlMessage.getResponseId():
// console.log(" it's a light control ack");
this.emit('sentLightCommand', new messages.SLLightControlMessage());
debugUnit(" it's a light control ack");
this.emit('sentLightCommand', new messages.SLLightControlMessage(msg));
break;
case messages.SLSetSaltCellConfigMessage.getResponseId():
// console.log(" it's a set salt cell config ack");
this.emit('setSaltCellConfig', new messages.SLSetSaltCellConfigMessage());
debugUnit(" it's a set salt cell config ack");
this.emit('setSaltCellConfig', new messages.SLSetSaltCellConfigMessage(msg));
break;
case messages.SLEquipmentConfigurationMessage.getResponseId():
debugUnit(" it's equipment configuration");
this.emit('equipmentConfiguration', new messages.SLEquipmentConfigurationMessage(msg));
break;
case messages.SLGetScheduleData.getResponseId():
debugUnit(" it's schedule data");
this.emit('getScheduleData', new messages.SLGetScheduleData(msg));
break;
case messages.SLAddNewScheduleEvent.getResponseId():
debugUnit(" it's a new schedule event ack");
this.emit('addNewScheduleEvent', new messages.SLAddNewScheduleEvent(msg));
break;
case messages.SLDeleteScheduleEventById.getResponseId():
debugUnit(" it's a delete schedule event ack");
this.emit('deleteScheduleEventById', new messages.SLDeleteScheduleEventById(msg));
break;
case messages.SLSetScheduleEventById.getResponseId():
debugUnit(" it's a set schedule event ack");
this.emit('setScheduleEventById', new messages.SLSetScheduleEventById(msg));
break;
case messages.SLSetCircuitRuntimeById.getResponseId():
debugUnit(" it's a set circuit runtime ack");
this.emit('setCircuitRuntimebyId', new messages.SLSetCircuitRuntimeById(msg));
break;
case messages.SLGetPumpStatus.getResponseId():
debugUnit(" it's pump status");
this.emit('getPumpStatus', new messages.SLGetPumpStatus(msg));
break;
case messages.SLSetPumpFlow.getResponseId():
debugUnit(" it's a set pump flow ack");
this.emit('setPumpFlow', new messages.SLSetPumpFlow(msg));
break;
case messages.SLCancelDelay.getResponseId():
debugUnit(" it's a cancel delay ack");
this.emit('cancelDelay', new messages.SLCancelDelay(msg));
break;
case messages.SLAddClient.getResponseId():
debugUnit(" it's an add client ack");
this.emit('addClient', new messages.SLAddClient(msg));
break;
case messages.SLRemoveClient.getResponseId():
debugUnit(" it's a remove client ack");
this.emit('removeClient', new messages.SLRemoveClient(msg));
break;
case messages.SLPoolStatusMessage.getAsyncResponseId():
debugUnit(" it's async pool status");
this.emit('poolStatus', new messages.SLPoolStatusMessage(msg));
break;
case messages.SLGetSystemTime.getResponseId():
debugUnit(" it's system time");
this.emit('getSystemTime', new messages.SLGetSystemTime(msg));
break;
case messages.SLSetSystemTime.getResponseId():
debugUnit(" it's a set system time ack");
this.emit('setSystemTime', new messages.SLSetSystemTime(msg));
break;
case messages.SLGetHistoryData.getResponseId():
debugUnit(" it's a history data query ack");
this.emit('getHistoryDataPending');
break;
case messages.SLGetHistoryData.getPayloadId():
debugUnit(" it's a history data payload");
this.emit('getHistoryData', new messages.SLGetHistoryData(msg));
break;
case 12501:
debugUnit(" it's a schedule changed notification");
this.emit('scheduleChanged');
break;
case 13:
// console.log(" it's a login failure.");
debugUnit(" it's a login failure.");
this.emit('loginFailed');
break;
case 30:
debugUnit(" it's an unknown command.");
this.emit('unknownCommand');
break;
case 31:
// console.log(" it's a parameter failure.");
debugUnit(" it's a parameter failure.");
this.emit('badParameter');
break;
default:
// console.log(" it's unknown. type: " + msgType);
debugUnit(" it's an unknown type: %d", msgType);
break;
}
}
@ -335,4 +496,12 @@ module.exports = {
LIGHT_CMD_COLOR_RED: 15,
LIGHT_CMD_COLOR_WHITE: 16,
LIGHT_CMD_COLOR_PURPLE: 17,
HEAT_MODE_OFF: 0,
HEAT_MODE_SOLAR: 1,
HEAT_MODE_SOLARPREFERRED: 2,
HEAT_MODE_HEATPUMP: 3,
HEAT_MODE_DONTCHANGE: 4,
PUMP_TYPE_INTELLIFLOVF: 1,
PUMP_TYPE_INTELLIFLOVS: 2,
PUMP_TYPE_INTELLIFLOVSF: 3,
};

29
messages/SLAddClient.js Normal file
View File

@ -0,0 +1,29 @@
'use strict';
const SLMessage = require('./SLMessage.js').SLMessage;
const MSG_ID = 12522;
exports.SLAddClient = class SLAddClient extends SLMessage {
constructor(clientId, senderId) {
if (typeof clientId === 'object') {
var size = clientId.readInt32LE(4) + 8;
super(clientId, MSG_ID, size);
} else {
super(senderId, MSG_ID);
this.clientId = clientId;
}
}
encode() {
this.writeInt32LE(0);
this.writeInt32LE(this.clientId);
super.encode();
}
static getResponseId() {
return MSG_ID + 1;
}
};

View File

@ -0,0 +1,30 @@
'use strict';
const SLMessage = require('./SLMessage.js').SLMessage;
const MSG_ID = 12544;
exports.SLAddNewScheduleEvent = class SLAddNewScheduleEvent extends SLMessage {
constructor(buf, scheduleType, senderId) {
if (buf) {
var size = buf.readInt32LE(4) + 8;
super(buf, MSG_ID, size);
} else {
super(senderId, MSG_ID);
this.writeInt32LE(0);
this.writeInt32LE(scheduleType);
}
}
decode() {
super.decode();
this.scheduleId = this.readUInt32LE();
}
static getResponseId() {
return MSG_ID + 1;
}
};

21
messages/SLCancelDelay.js Normal file
View File

@ -0,0 +1,21 @@
'use strict';
const SLMessage = require('./SLMessage.js').SLMessage;
const MSG_ID = 12580;
exports.SLCancelDelay = class SLCancelDelay extends SLMessage {
constructor(senderId) {
super(senderId, MSG_ID);
}
encode() {
this.writeInt32LE(0);
super.encode();
}
static getResponseId() {
return MSG_ID + 1;
}
};

View File

@ -5,20 +5,14 @@ const SLMessage = require('./SLMessage.js').SLMessage;
const MSG_ID = 12592;
exports.SLChemDataMessage = class SLChemDataMessage extends SLMessage {
constructor(buf) {
var size;
constructor(buf, senderId) {
if (buf) {
size = buf.readInt32LE(4) + 8;
}
super(0, MSG_ID, size);
if (!buf) {
this.writeInt32LE(0); // controller index
var size = buf.readInt32LE(4) + 8;
super(buf, MSG_ID, size);
} else {
this._wroteSize = true;
this.writeBuffer(buf, 0);
super(senderId, MSG_ID);
this.decode();
this.writeInt32LE(0); // controller index
}
}

View File

@ -4,22 +4,24 @@ const SLMessage = require('./SLMessage.js').SLMessage;
const MSG_ID = 12532;
const CIRCUIT_NAME_VALUE_MAP = [
{name: 'Unused', deviceId: 0},
{name: 'Solar Active', deviceId: 128},
{name: 'Pool or Spa Heater Active', deviceId: 129},
{name: 'Pool Heater Active', deviceId: 130},
{name: 'Spa Heater Active', deviceId: 131},
];
exports.SLControllerConfigMessage = class SLControllerConfigMessage extends SLMessage {
constructor(buf) {
var size;
constructor(buf, senderId) {
if (buf) {
size = buf.readInt32LE(4) + 8;
}
super(0, MSG_ID, size);
if (!buf) {
this.writeInt32LE(0);
this.writeInt32LE(0);
var size = buf.readInt32LE(4) + 8;
super(buf, MSG_ID, size);
} else {
this._wroteSize = true;
this.writeBuffer(buf, 0);
super(senderId, MSG_ID);
this.decode();
this.writeInt32LE(0);
this.writeInt32LE(0);
}
}
@ -127,4 +129,30 @@ exports.SLControllerConfigMessage = class SLControllerConfigMessage extends SLMe
isChem2() {
return this.controllerType === 252 && this.hwType === 2;
}
getCircuitByDeviceId(deviceId) {
var deviceArray = this.getCircuitsMap();
for (var i = 0; i < deviceArray.length; i++) {
if (deviceArray[i].deviceId === deviceId) {
return deviceArray[i];
}
}
return null;
}
getCircuitsMap() {
var deviceArray;
if (this.bodyArray) {
deviceArray = this.bodyArray.concat(CIRCUIT_NAME_VALUE_MAP);
} else {
deviceArray = [].concat(CIRCUIT_NAME_VALUE_MAP);
}
return deviceArray;
}
};

View File

@ -0,0 +1,18 @@
'use strict';
const SLMessage = require('./SLMessage.js').SLMessage;
const MSG_ID = 12546;
exports.SLDeleteScheduleEventById = class SLDeleteScheduleEventById extends SLMessage {
constructor(scheduleId, senderId) {
super(senderId, MSG_ID);
this.writeInt32LE(0);
this.writeInt32LE(scheduleId);
}
static getResponseId() {
return MSG_ID + 1;
}
};

View File

@ -5,21 +5,15 @@ const SLMessage = require('./SLMessage.js').SLMessage;
const MSG_ID = 12566;
exports.SLEquipmentConfigurationMessage = class SLEquipmentConfigurationMessage extends SLMessage {
constructor(buf) {
var size;
constructor(buf, senderId) {
if (buf) {
size = buf.readInt32LE(4) + 8;
}
super(0, MSG_ID, size);
if (!buf) {
this.writeInt32LE(0);
this.writeInt32LE(0);
var size = buf.readInt32LE(4) + 8;
super(buf, MSG_ID, size);
} else {
this._wroteSize = true;
this.writeBuffer(buf, 0);
super(senderId, MSG_ID);
this.decode();
this.writeInt32LE(0);
this.writeInt32LE(0);
}
}
@ -33,19 +27,185 @@ exports.SLEquipmentConfigurationMessage = class SLEquipmentConfigurationMessage
this.controllerData = this.readInt32LE();
this.versionDataArray = this.readSLArray();
this.speedDataArray = this.readSLArray();
this.valveDataArray = this.readSLArray();
this.valveDataArray = this.readSLArray(); // decodeValveData()
this.remoteDataArray = this.readSLArray();
this.sensorDataArray = this.readSLArray();
this.delayDataArray = this.readSLArray();
this.sensorDataArray = this.readSLArray(); // decodeSensorData()
this.delayDataArray = this.readSLArray(); // decodeDelayData()
this.macroDataArray = this.readSLArray();
this.miscDataArray = this.readSLArray();
this.miscDataArray = this.readSLArray(); // decodeMiscData()
this.lightDataArray = this.readSLArray();
this.flowDataArray = this.readSLArray();
this.sgDataArray = this.readSLArray();
this.spaFlowDataArray = this.readSLArray();
}
getVersion() {
if (this.versionDataArray === null || this.versionDataArray.length < 2) {
return 0;
}
return (this.versionDataArray[0] * 1000) + (this.versionDataArray[1]);
}
getSecondariesCount() {
return (this.controllerData & 0x11000000) >> 6;
}
getPumpType(pumpIndex) {
if (typeof (pumpIndex) !== 'number') {
return 0;
}
if (this.flowDataArray === null || this.flowDataArray.length < (pumpIndex + 1) * 45) {
return 0;
}
let pumpType = this.flowDataArray[(45 * pumpIndex) + 2];
if (pumpType <= 3) {
return pumpType;
}
return 0;
}
getCircuitRPMs(pumpIndex, circuitDeviceId) {
if (typeof (pumpIndex) !== 'number' || typeof (circuitDeviceId) !== 'number') {
return 0;
}
if (pumpIndex < 0 || pumpIndex >= 8) {
return 0;
}
if (this.flowDataArray === null || this.flowDataArray.length < (pumpIndex + 1) * 45) {
return 0;
}
for (var i = 0; i < 8; i++) {
let offset = (45 * pumpIndex) + 4 + (i * 2);
if (this.flowDataArray[offset] === circuitDeviceId) {
let upperBits = this.flowDataArray[offset + 1];
let lowerBits = this.flowDataArray[offset + (16 - (i * 2)) + 1 + i];
return (upperBits << 8) + lowerBits;
}
}
return 0;
}
getNumPumps() {
if (this.flowDataArray === null) {
return 0;
}
let numPumps = 0;
for (var i = 0; i < this.flowDataArray.length; i += 45) {
if (this.flowDataArray[i + 2] !== 0) {
numPumps++;
}
}
return numPumps;
}
static getResponseId() {
return MSG_ID + 1;
}
decodeSensorData() {
var sensors = this.sensorDataArray;
this.sensors = {};
this.sensors.poolSolarPresent = this.isBitSet(sensors[0], 1);
this.sensors.spaSolarPresent = this.isBitSet(sensors[0], 4);
this.sensors.thermaFloCoolPresent = this.isBitSet(sensors[1], 1);
this.sensors.solarHeatPumpPresent = this.isBitSet(sensors[2], 4);
this.sensors.thermaFloPresent = this.isBitSet(sensors[2], 5);
}
decodeValveData() {
var secondaries = this.getSecondariesCount();
var isSolarValve0 = false;
var isSolarValve1 = false;
if (!this.sensors) {
this.decodeSensorData();
}
if (this.sensors.poolSolarPresent && !this.sensors.solarHeatPumpPresent) {
isSolarValve0 = true;
}
if (this.isDualBody()) {
if (this.sensors.spaSolarPresent && !this.sensors.thermaFloPresent) {
isSolarValve1 = true;
}
}
var valveArray = [];
for (var loadCenterIndex = 0; loadCenterIndex <= secondaries; loadCenterIndex++) {
var loadCenterValveData = this.valveDataArray[loadCenterIndex];
for (var valveIndex = 0; valveIndex < 5; valveIndex++) {
var valveObject = {};
var isSolarValve = false;
if (loadCenterIndex === 0) {
if (valveIndex === 0 && isSolarValve0) {
isSolarValve = true;
}
if (valveIndex === 1 && isSolarValve1) {
isSolarValve = true;
}
}
if (this.isValvePresent(valveIndex, loadCenterValveData)) {
var valveDataIndex = (loadCenterIndex * 5) + 4 + valveIndex;
var deviceId = this.valveDataArray[valveDataIndex];
if (deviceId === 0) {
// console.log('unused valve, loadCenterIndex = ' + loadCenterIndex + ' valveIndex = ' + valveIndex);
} else if (isSolarValve === true){
// console.log('used by solar');
} else {
valveObject.loadCenterIndex = loadCenterIndex;
valveObject.valveIndex = valveIndex;
valveObject.valveName = String.fromCharCode(65 + valveIndex);
valveObject.loadCenterName = (loadCenterIndex + 1).toString();
valveObject.deviceId = deviceId;
valveArray.push(valveObject);
}
}
}
}
this.valves = valveArray;
}
isValvePresent(valveIndex, loadCenterValveData) {
if (valveIndex < 2) {
return true;
} else {
return this.isBitSet(loadCenterValveData, valveIndex);
}
}
decodeDelayData() {
this.delays = {};
this.delays.poolPumpOnDuringHeaterCooldown = this.isBitSet(this.delayDataArray[0], 0);
this.delays.spaPumpOnDuringHeaterCooldown = this.isBitSet(this.delayDataArray[0], 1);
this.delays.pumpOffDuringValveAction = this.isBitSet(this.delayDataArray[0], 7);
}
decodeMiscData() {
this.misc = {};
this.misc.intelliChem = this.isBitSet(this.miscDataArray[3], 0);
this.misc.spaManualHeat = this.miscDataArray[4] !== 0;
}
isDualBody() {
return this.controllerType === 5;
}
};

View File

@ -0,0 +1,87 @@
'use strict';
const SLMessage = require('./SLMessage.js').SLMessage;
const MSG_ID = 12534;
const PAYLOAD_MSG_ID = 12502;
exports.SLGetHistoryData = class SLGetHistoryData extends SLMessage {
constructor(buf, fromTime, toTime, senderId) {
if (buf) {
var size = buf.readInt32LE(4) + 8;
super(buf, MSG_ID, size);
} else {
super(senderId, MSG_ID);
this.writeInt32LE(0);
this.writeSLDateTime(fromTime);
this.writeSLDateTime(toTime);
this.writeInt32LE(senderId || 0);
}
}
decode() {
super.decode();
this.airTemps = this.readTimeTempPointsPairs();
this.poolTemps = this.readTimeTempPointsPairs();
this.poolSetPointTemps = this.readTimeTempPointsPairs();
this.spaTemps = this.readTimeTempPointsPairs();
this.spaSetPointTemps = this.readTimeTempPointsPairs();
this.poolRuns = this.readTimeTimePointsPairs();
this.spaRuns = this.readTimeTimePointsPairs();
this.solarRuns = this.readTimeTimePointsPairs();
this.heaterRuns = this.readTimeTimePointsPairs();
this.lightRuns = this.readTimeTimePointsPairs();
}
readTimeTempPointsPairs() {
let retval = [];
// 4 bytes for the length
if (this.length >= this.readOffset + 4) {
let points = this.readInt32LE();
// 16 bytes per time, 4 bytes per temperature
if (this.length >= this.readOffset + (points * (16 + 4))) {
for (let i = 0; i < points; i++) {
let time = this.readSLDateTime();
let temp = this.readInt32LE();
retval.push({
time: time,
temp: temp,
});
}
}
}
return retval;
}
readTimeTimePointsPairs() {
let retval = [];
// 4 bytes for the length
if (this.length >= this.readOffset + 4) {
let points = this.readInt32LE();
// 16 bytes per on time, 16 bytes per off time
if (this.length >= this.readOffset + (points * (16 + 16))) {
for (let i = 0; i < points; i++) {
let onTime = this.readSLDateTime();
let offTime = this.readSLDateTime();
retval.push({
on: onTime,
off: offTime,
});
}
}
}
return retval;
}
static getResponseId() {
return MSG_ID + 1;
}
static getPayloadId() {
return PAYLOAD_MSG_ID;
}
};

View File

@ -0,0 +1,44 @@
'use strict';
const SLMessage = require('./SLMessage.js').SLMessage;
const MSG_ID = 12584;
exports.SLGetPumpStatus = class SLGetPumpStatus extends SLMessage {
constructor(buf, pumpId, senderId) {
if (buf) {
var size = buf.readInt32LE(4) + 8;
super(buf, MSG_ID, size);
} else {
super(senderId, MSG_ID);
this.writeInt32LE(0);
this.writeInt32LE(pumpId);
}
}
decode() {
super.decode();
this.pumpSetting = new Array(8);
this.pumpType = this.readUInt32LE();
this.isRunning = this.readUInt32LE() !== 0; // 0, 1, or 4294967295 (FF FF FF FF)
this.pumpWatts = this.readUInt32LE();
this.pumpRPMs = this.readUInt32LE();
this.pumpUnknown1 = this.readUInt32LE(); // Always 0
this.pumpGPMs = this.readUInt32LE();
this.pumpUnknown2 = this.readUInt32LE(); // Always 255
for (var i = 0; i < 8; i++) {
this.pumpSetting[i] = {};
this.pumpSetting[i].circuitId = this.readUInt32LE();
this.pumpSetting[i].pumpSetPoint = this.readUInt32LE();
this.pumpSetting[i].isRPMs = this.readUInt32LE() !== 0; // 1 for RPMs; 0 for GPMs
}
}
static getResponseId() {
return MSG_ID + 1;
}
};

View File

@ -0,0 +1,45 @@
'use strict';
const SLMessage = require('./SLMessage.js').SLMessage;
const MSG_ID = 12542;
exports.SLGetScheduleData = class SLGetScheduleData extends SLMessage {
constructor(buf, scheduleType, senderId) {
if (buf) {
var size = buf.readInt32LE(4) + 8;
super(buf, MSG_ID, size);
} else {
super(senderId, MSG_ID);
this.writeInt32LE(0);
this.writeInt32LE(scheduleType);
}
}
decode() {
super.decode();
this.eventCount = this.readUInt32LE();
this.events = new Array(this.eventCount);
for (var i = 0; i < this.events.length; i++) {
this.events[i] = {};
this.events[i].scheduleId = this.readUInt32LE();
this.events[i].circuitId = this.readUInt32LE();
this.events[i].startTime = this.decodeTime(this.readUInt32LE());
this.events[i].stopTime = this.decodeTime(this.readUInt32LE());
this.events[i].dayMask = this.readUInt32LE();
this.events[i].flags = this.readUInt32LE();
this.events[i].heatCmd = this.readUInt32LE();
this.events[i].heatSetPoint = this.readUInt32LE();
this.events[i].days = this.decodeDayMask(this.events[i].dayMask);
}
}
static getResponseId() {
return MSG_ID + 1;
}
};

View File

@ -0,0 +1,37 @@
'use strict';
const SLMessage = require('./SLMessage.js').SLMessage;
const MSG_ID = 8110;
exports.SLGetSystemTime = class SLGetSystemTime extends SLMessage {
constructor(buf, senderId) {
if (buf) {
var size = buf.readInt32LE(4) + 8;
super(buf, MSG_ID, size);
} else {
super(senderId, MSG_ID);
}
}
decode() {
super.decode();
this.date = this.readSLDateTime();
this.year = this.date.getFullYear();
this.month = this.date.getMonth() + 1; // + 1 is for backward compatibility, SLTime represents months as 1-based
this.dayOfWeek = this.date.getDay(); // should probably be tweaked to adjust what days are 0-6 as SLTime and Javascript start on different days of the week
this.day = this.date.getDate();
this.hour = this.date.getHours();
this.minute = this.date.getMinutes();
this.second = this.date.getSeconds();
this.millisecond = this.date.getMilliseconds();
var adjustForDST = this.readInt32LE();
this.adjustForDST = adjustForDST === 1;
}
static getResponseId() {
return MSG_ID + 1;
}
};

View File

@ -5,11 +5,16 @@ const SLMessage = require('./SLMessage.js').SLMessage;
const MSG_ID = 12556;
exports.SLLightControl = class SLLightControl extends SLMessage {
constructor(controllerIndex, command) {
super(0, MSG_ID);
constructor(controllerIndex, command, senderId) {
if (typeof controllerIndex === 'object') {
var size = controllerIndex.readInt32LE(4) + 8;
super(controllerIndex, MSG_ID, size);
} else {
super(senderId, MSG_ID);
this.controllerIndex = controllerIndex;
this.command = command;
this.controllerIndex = controllerIndex;
this.command = command;
}
}
encode() {

View File

@ -2,6 +2,16 @@
const SmartBuffer = require('smart-buffer').SmartBuffer;
const DAY_VALUES = [
['Mon', 0x1 ],
['Tue', 0x2 ],
['Wed', 0x4 ],
['Thu', 0x8 ],
['Fri', 0x10 ],
['Sat', 0x20 ],
['Sun', 0x40 ],
];
exports.SLMessage = class SLMessage extends SmartBuffer {
constructor(senderId, messageId, size) {
var options;
@ -17,7 +27,7 @@ exports.SLMessage = class SLMessage extends SmartBuffer {
this.writeUInt16LE(messageId || 0);
this._wroteSize = false;
} else if (senderId) {
} else if (typeof senderId === 'object') {
this._wroteSize = true;
var buffer = senderId;
this.writeBuffer(buffer, 0);
@ -93,6 +103,78 @@ exports.SLMessage = class SLMessage extends SmartBuffer {
this.dataLength = this.readInt32LE();
}
isBitSet(value, bit) {
return ((value >> bit) & 0x1) === 1;
}
decodeTime(rawTime) { // Takes 'rawTime' in mins past midnight and returns military time as a string
var retVal;
retVal = Math.floor(rawTime / 60) * 100 + rawTime % 60;
retVal = String(retVal).padStart(4, '0');
return retVal;
}
encodeTime(stringTime) { // Takes 'stringTime' as military time and returns mins past midnight
return Number(stringTime.substr(0, 2) * 60) + Number(stringTime.substr(2, 2));
}
decodeDayMask(dayMask) {
var days = [];
for (var i = 0; i < 7; i++) {
if (this.isBitSet(dayMask, i)) {
days.push(DAY_VALUES[i][0]);
}
}
return days;
}
encodeDayMask(daysArray) {
var dayMask = 0;
for (var i = 0; i < daysArray.length; i++) {
dayMask += this.getDayValue(daysArray[i]);
}
return dayMask;
}
getDayValue(dayName) {
for (var i = 0; i < DAY_VALUES.length; i++) {
if (DAY_VALUES[i][0] === dayName) {
return DAY_VALUES[i][1];
}
}
return 0;
}
writeSLDateTime(date) {
this.writeInt16LE(date.getFullYear());
this.writeInt16LE(date.getMonth() + 1);
this.writeInt16LE(date.getDay() + 1);
this.writeInt16LE(date.getDate());
this.writeInt16LE(date.getHours());
this.writeInt16LE(date.getMinutes());
this.writeInt16LE(date.getSeconds());
this.writeInt16LE(date.getMilliseconds());
}
readSLDateTime() {
let date = new Date();
date.setFullYear(this.readInt16LE());
date.setMonth(this.readInt16LE() - 1);
this.readInt16LE();
date.setDate(this.readInt16LE());
date.setHours(this.readInt16LE());
date.setMinutes(this.readInt16LE());
date.setSeconds(this.readInt16LE());
date.setMilliseconds(this.readInt16LE());
return date;
}
static slackForAlignment(val) {
return (4 - val % 4) % 4;
}

View File

@ -3,25 +3,20 @@
const SLMessage = require('./SLMessage.js').SLMessage;
const MSG_ID = 12526;
const ASYNC_MSG_ID = 12500;
const SPA_CIRCUIT_ID = 500;
const POOL_CIRCUIT_ID = 505;
exports.SLPoolStatusMessage = class SLPoolStatusMessage extends SLMessage {
constructor(buf) {
var size;
constructor(buf, senderId) {
if (buf) {
size = buf.readInt32LE(4) + 8;
}
super(0, MSG_ID, size);
if (!buf) {
this.writeInt32LE(0);
var size = buf.readInt32LE(4) + 8;
super(buf, MSG_ID, size);
} else {
this._wroteSize = true;
this.writeBuffer(buf, 0);
super(senderId, MSG_ID);
this.decode();
this.writeInt32LE(0);
}
}
@ -112,4 +107,8 @@ exports.SLPoolStatusMessage = class SLPoolStatusMessage extends SLMessage {
static getResponseId() {
return MSG_ID + 1;
}
static getAsyncResponseId() {
return ASYNC_MSG_ID;
}
};

View File

@ -0,0 +1,29 @@
'use strict';
const SLMessage = require('./SLMessage.js').SLMessage;
const MSG_ID = 12524;
exports.SLRemoveClient = class SLRemoveClient extends SLMessage {
constructor(clientId, senderId) {
if (typeof clientId === 'object') {
var size = clientId.readInt32LE(4) + 8;
super(clientId, MSG_ID, size);
} else {
super(senderId, MSG_ID);
this.clientId = clientId;
}
}
encode() {
this.writeInt32LE(0);
this.writeInt32LE(this.clientId);
super.encode();
}
static getResponseId() {
return MSG_ID + 1;
}
};

View File

@ -5,20 +5,14 @@ const SLMessage = require('./SLMessage.js').SLMessage;
const MSG_ID = 12572;
exports.SLSaltCellConfigMessage = class SLSaltCellConfigMessage extends SLMessage {
constructor(buf) {
var size;
constructor(buf, senderId) {
if (buf) {
size = buf.readInt32LE(4) + 8;
}
super(0, MSG_ID, size);
if (!buf) {
this.writeInt32LE(0); // controller index
var size = buf.readInt32LE(4) + 8;
super(buf, MSG_ID, size);
} else {
this._wroteSize = true;
this.writeBuffer(buf, 0);
super(senderId, MSG_ID);
this.decode();
this.writeInt32LE(0); // controller index
}
}

View File

@ -0,0 +1,32 @@
'use strict';
const SLMessage = require('./SLMessage.js').SLMessage;
const MSG_ID = 12550;
exports.SLSetCircuitRuntimeById = class SLSetCircuitRuntimeById extends SLMessage {
constructor(circuitId, runTime, senderId) {
if (typeof circuitId === 'object') {
var size = circuitId.readInt32LE(4) + 8;
super(circuitId, MSG_ID, size);
} else {
super(senderId, MSG_ID);
this.circuitId = circuitId;
this.runTime = runTime;
}
}
encode() {
this.writeInt32LE(0);
this.writeInt32LE(this.circuitId);
this.writeInt32LE(this.runTime);
super.encode();
}
static getResponseId() {
return MSG_ID + 1;
}
};

View File

@ -5,12 +5,17 @@ const SLMessage = require('./SLMessage.js').SLMessage;
const MSG_ID = 12530;
exports.SLSetCircuitStateMessage = class SLSetCircuitStateMessage extends SLMessage {
constructor(controllerId, circuitId, circuitState) {
super(0, MSG_ID);
constructor(controllerId, circuitId, circuitState, senderId) {
if (typeof controllerId === 'object') {
var size = controllerId.readInt32LE(4) + 8;
super(controllerId, MSG_ID, size);
} else {
super(senderId, MSG_ID);
this.controllerId = controllerId;
this.circuitId = circuitId;
this.circuitState = circuitState;
this.controllerId = controllerId;
this.circuitId = circuitId;
this.circuitState = circuitState;
}
}
encode() {

View File

@ -5,14 +5,17 @@ const SLMessage = require('./SLMessage.js').SLMessage;
const MSG_ID = 12538;
exports.SLSetHeatMode = class SLSetHeatMode extends SLMessage {
constructor(controllerIndex, bodyType, heatMode) {
super(0, MSG_ID);
constructor(controllerIndex, bodyType, heatMode, senderId) {
if (typeof controllerIndex === 'object') {
var size = controllerIndex.readInt32LE(4) + 8;
super(controllerIndex, MSG_ID, size);
} else {
super(senderId, MSG_ID);
this.controllerIndex = controllerIndex;
this.bodyType = bodyType;
this.heatMode = heatMode;
// heatmodes:
// 0: "Off", 1: "Solar", 2 : "Solar Preferred", 3 : "Heat Pump", 4: "Don't Change"
this.controllerIndex = controllerIndex;
this.bodyType = bodyType;
this.heatMode = heatMode;
}
}
encode() {

View File

@ -5,12 +5,17 @@ const SLMessage = require('./SLMessage.js').SLMessage;
const MSG_ID = 12528;
exports.SLSetHeatSetPoint = class SLSetHeatSetPoint extends SLMessage {
constructor(controllerIndex, bodyType, temperature) {
super(0, MSG_ID);
constructor(controllerIndex, bodyType, temperature, senderId) {
if (typeof controllerIndex === 'object') {
var size = controllerIndex.readInt32LE(4) + 8;
super(controllerIndex, MSG_ID, size);
} else {
super(senderId, MSG_ID);
this.controllerIndex = controllerIndex;
this.bodyType = bodyType;
this.temperature = temperature;
this.controllerIndex = controllerIndex;
this.bodyType = bodyType;
this.temperature = temperature;
}
}
encode() {

41
messages/SLSetPumpFlow.js Normal file
View File

@ -0,0 +1,41 @@
'use strict';
const SLMessage = require('./SLMessage.js').SLMessage;
const MSG_ID = 12586;
exports.SLSetPumpFlow = class SLSetPumpFlow extends SLMessage {
constructor(pumpId, circuitId, setPoint, isRPMs, senderId) {
if (typeof pumpId === 'object') {
var size = pumpId.readInt32LE(4) + 8;
super(pumpId, MSG_ID, size);
} else {
super(senderId, MSG_ID);
this.pumpId = pumpId;
this.circuitId = circuitId;
this.setPoint = setPoint;
if (isRPMs === true) {
this.isRPMs = 1;
} else {
this.isRPMs = 0;
}
}
}
encode() {
this.writeInt32LE(0); // Always 0 in my case
this.writeInt32LE(this.pumpId); // presumably pumpId, always 0 in my case
this.writeInt32LE(this.circuitId); // This is indexed to the array of circuits returned in GetPumpStatus
this.writeInt32LE(this.setPoint);
this.writeInt32LE(this.isRPMs); // 0 for GPM, 1 for RPMs
super.encode();
}
static getResponseId() {
return MSG_ID + 1;
}
};

View File

@ -5,12 +5,17 @@ const SLMessage = require('./SLMessage.js').SLMessage;
const MSG_ID = 12576;
exports.SLSetSaltCellConfigMessage = class SLSetSaltCellConfigMessage extends SLMessage {
constructor(controllerIndex, poolOutput, spaOutput) {
super(0, MSG_ID);
constructor(controllerIndex, poolOutput, spaOutput, senderId) {
if (typeof controllerIndex === 'object') {
var size = controllerIndex.readInt32LE(4) + 8;
super(controllerIndex, MSG_ID, size);
} else {
super(senderId, MSG_ID);
this.controllerIndex = controllerIndex;
this.poolOutput = poolOutput;
this.spaOutput = spaOutput;
this.controllerIndex = controllerIndex;
this.poolOutput = poolOutput;
this.spaOutput = spaOutput;
}
}
encode() {

View File

@ -0,0 +1,31 @@
'use strict';
const SLMessage = require('./SLMessage.js').SLMessage;
const MSG_ID = 12548;
exports.SLSetScheduleEventById = class SLSetScheduleEventById extends SLMessage {
constructor(buf, scheduleId, circuitId, startTime, stopTime, dayMask, flags, heatCmd, heatSetPoint, senderId) {
if (buf) {
var size = buf.readInt32LE(4) + 8;
super(buf, MSG_ID, size);
} else {
super(senderId, MSG_ID);
this.writeInt32LE(0);
this.writeInt32LE(scheduleId);
this.writeInt32LE(circuitId);
this.writeInt32LE(startTime);
this.writeInt32LE(stopTime);
this.writeInt32LE(dayMask);
this.writeInt32LE(flags);
this.writeInt32LE(heatCmd);
this.writeInt32LE(heatSetPoint);
}
}
static getResponseId() {
return MSG_ID + 1;
}
};

View File

@ -0,0 +1,28 @@
'use strict';
const SLMessage = require('./SLMessage.js').SLMessage;
const MSG_ID = 8112;
exports.SLSetSystemTime = class SLSetSystemTime extends SLMessage {
constructor(buf, date, shouldAdjustForDST, senderId) {
if (buf) {
var size = buf.readInt32LE(4) + 8;
super(buf, MSG_ID, size);
} else {
super(senderId, MSG_ID);
this.date = date;
this.shouldAdjustForDST = shouldAdjustForDST;
}
}
encode() {
this.writeSLDateTime(this.date);
this.writeInt32LE(this.shouldAdjustForDST ? 1 : 0);
}
static getResponseId() {
return MSG_ID + 1;
}
};

View File

@ -5,18 +5,12 @@ const SLMessage = require('./SLMessage.js').SLMessage;
const MSG_ID = 8120;
exports.SLVersionMessage = class SLVersionMessage extends SLMessage {
constructor(buf) {
var size;
constructor(buf, senderId) {
if (buf) {
size = buf.readInt32LE(4) + 8;
}
super(0, MSG_ID, size);
if (buf) {
this._wroteSize = true;
this.writeBuffer(buf, 0);
this.decode();
var size = buf.readInt32LE(4) + 8;
super(buf, MSG_ID, size);
} else {
super(senderId, MSG_ID);
}
}

View File

@ -15,3 +15,16 @@ exports.SLLightControlMessage = require('./SLLightControl.js').SLLightControl;
exports.SLSetSaltCellConfigMessage = require('./SLSetSaltCellConfigMessage.js').SLSetSaltCellConfigMessage;
exports.SLEquipmentConfigurationMessage =
require('./SLEquipmentConfigurationMessage.js').SLEquipmentConfigurationMessage;
exports.SLGetScheduleData = require('./SLGetScheduleData.js').SLGetScheduleData;
exports.SLAddNewScheduleEvent = require('./SLAddNewScheduleEvent.js').SLAddNewScheduleEvent;
exports.SLDeleteScheduleEventById = require('./SLDeleteScheduleEventById.js').SLDeleteScheduleEventById;
exports.SLSetScheduleEventById = require('./SLSetScheduleEventById.js').SLSetScheduleEventById;
exports.SLSetCircuitRuntimeById = require('./SLSetCircuitRuntimeById.js').SLSetCircuitRuntimeById;
exports.SLGetPumpStatus = require('./SLGetPumpStatus.js').SLGetPumpStatus;
exports.SLSetPumpFlow = require('./SLSetPumpFlow.js').SLSetPumpFlow;
exports.SLCancelDelay = require('./SLCancelDelay.js').SLCancelDelay;
exports.SLAddClient = require('./SLAddClient.js').SLAddClient;
exports.SLRemoveClient = require('./SLRemoveClient.js').SLRemoveClient;
exports.SLGetSystemTime = require('./SLGetSystemTime.js').SLGetSystemTime;
exports.SLSetSystemTime = require('./SLSetSystemTime.js').SLSetSystemTime;
exports.SLGetHistoryData = require('./SLGetHistoryData.js').SLGetHistoryData;

4466
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,26 +1,28 @@
{
"name": "node-screenlogic",
"description": "Tool for connecting to Pentair ScreenLogic systems on the local network",
"version": "1.4.0",
"main": "index.js",
"license": "MIT",
"repository": "https://github.com/parnic/node-screenlogic.git",
"keywords": [
"pentair",
"pool",
"screenlogic",
"swimmingpool"
],
"dependencies": {
"smart-buffer": "~4.1.0"
},
"devDependencies": {
"eslint": "^6.8.0",
"eslint-config-strongloop": "^2.1.0",
"mocha": "^7.1.1"
},
"scripts": {
"test": "mocha test/*.spec.js",
"pretest": "eslint --ignore-path .gitignore ."
}
"name": "node-screenlogic",
"description": "Tool for connecting to Pentair ScreenLogic systems on the local network",
"version": "1.8.0",
"main": "index.js",
"license": "MIT",
"repository": "https://github.com/parnic/node-screenlogic.git",
"keywords": [
"pentair",
"pool",
"screenlogic",
"swimmingpool"
],
"dependencies": {
"debug": "^4.3.2",
"smart-buffer": "^4.2.0"
},
"devDependencies": {
"eslint": "^8.0.0",
"eslint-config-strongloop": "^2.1.0",
"mocha": "^9.1.2"
},
"scripts": {
"test": "mocha test/*.spec.js",
"pretest": "eslint --ignore-path .gitignore .",
"test-slmessage": "mocha test/slmessage.spec.js"
}
}

View File

@ -3,8 +3,8 @@
const ScreenLogic = require('../index');
// you'll need a ScreenLogic-enabled device on your network for this to succeed
describe('Finder', () => {
it('finds a server', done => {
describe('Finder', function() {
it('finds a server', function(done) {
let finder = new ScreenLogic.FindUnits();
finder.on('serverFound', server => {
finder.close();

View File

@ -9,7 +9,7 @@ function slMessageLen(str) {
return 4 + str.length + SLMessage.slackForAlignment(str.length);
}
describe('SLMessage utilities', () => {
describe('SLMessage utilities', function() {
// message header = senderId, messageId, bodyLen.
// senderId and messageId are int16's, so 2b each. bodyLen is an int32, so 4b. total 8b.
let msgHeaderLen = 8;
@ -172,4 +172,62 @@ describe('SLMessage utilities', () => {
assert.strictEqual(decodedMsg.dataLength, decodedMsg.readOffset - 8);
}
});
it('encodes Date as SLTime', function() {
let msg = new SLMessage();
let date = new Date(2021, 8, 6, 22, 8, 5);
msg.writeSLDateTime(date);
let decodedMsg = new SLMessage(msg.toBuffer());
assert.equal(decodedMsg.readUInt16LE(), 2021);
// javascript Date() month is 0-based, ScreenLogic month matches the calendar
assert.equal(decodedMsg.readUInt16LE(), 9);
// ScreenLogic day-of-week starts with Sunday as 1
assert.equal(decodedMsg.readUInt16LE(), 2);
assert.equal(decodedMsg.readUInt16LE(), 6);
assert.equal(decodedMsg.readUInt16LE(), 22);
assert.equal(decodedMsg.readUInt16LE(), 8);
assert.equal(decodedMsg.readUInt16LE(), 5);
assert.equal(decodedMsg.readUInt16LE(), 0);
});
it('decodes SLTime as Date', function() {
let msg = new SLMessage();
let date = new Date(2021, 8, 6, 22, 8, 5);
msg.writeSLDateTime(date);
let decodedMsg = new SLMessage(msg.toBuffer());
let decodedDate = decodedMsg.readSLDateTime();
assert.equal(date.getFullYear(), decodedDate.getFullYear());
assert.equal(date.getMonth(), decodedDate.getMonth());
assert.equal(date.getDate(), decodedDate.getDate());
assert.equal(date.getHours(), decodedDate.getHours());
assert.equal(date.getMinutes(), decodedDate.getMinutes());
assert.equal(date.getSeconds(), decodedDate.getSeconds());
assert.equal(date.getMilliseconds(), decodedDate.getMilliseconds());
});
it('writes the appropriate day of week', function() {
let handler = function(inDate) {
let msg = new SLMessage();
msg.writeSLDateTime(inDate);
let decodedMsg = new SLMessage(msg.toBuffer());
decodedMsg.readUInt16LE();
decodedMsg.readUInt16LE();
return decodedMsg.readUInt16LE();
}
let dow = handler(new Date(2022, 3, 17, 10, 3, 0));
assert.equal(dow, 1);
dow = handler(new Date(2022, 3, 18, 10, 3, 0));
assert.equal(dow, 2);
dow = handler(new Date(2022, 3, 19, 10, 3, 0));
assert.equal(dow, 3);
dow = handler(new Date(2022, 3, 20, 10, 3, 0));
assert.equal(dow, 4);
dow = handler(new Date(2022, 3, 21, 10, 3, 0));
assert.equal(dow, 5);
dow = handler(new Date(2022, 3, 22, 10, 3, 0));
assert.equal(dow, 6);
dow = handler(new Date(2022, 3, 23, 10, 3, 0));
assert.equal(dow, 7);
});
});

View File

@ -1,11 +1,12 @@
'use strict';
const ScreenLogic = require('../index');
var assert = require('assert');
// you'll need a ScreenLogic-enabled device on your network for this to succeed
describe('Unit', () => {
describe('Unit', function() {
let unit;
before(done => {
before(function(done) {
let finder = new ScreenLogic.FindUnits();
finder.on('serverFound', server => {
finder.close();
@ -21,50 +22,57 @@ describe('Unit', () => {
finder.search();
});
after(() => {
after(function() {
unit.close();
});
// let circuit;
it('gets pool status', done => {
it('gets pool status', function(done) {
unit.on('poolStatus', status => {
/* circuit = */status.circuitArray[0];
assert.equal(status.senderId, 0);
done();
});
unit.getPoolStatus();
});
it('gets controller config', done => {
it('gets controller config', function(done) {
unit.on('controllerConfig', config => {
assert.equal(config.senderId, 42);
done();
});
unit.getControllerConfig();
unit.getControllerConfig(42);
});
it('gets chemical data', done => {
unit.on('chemicalData', () => {
it('gets chemical data', function(done) {
unit.on('chemicalData', chemData => {
assert.equal(chemData.senderId, 123);
done();
});
unit.getChemicalData();
unit.getChemicalData(123);
});
it('gets salt cell config', done => {
unit.on('saltCellConfig', () => {
it('gets salt cell config', function(done) {
unit.on('saltCellConfig', saltConfig => {
assert.equal(saltConfig.senderId, 0);
done();
});
unit.getSaltCellConfig();
});
it('gets version', done => {
unit.on('version', () => {
it('gets version', function(done) {
unit.on('version', version => {
assert.equal(version.senderId, 41239);
done();
});
unit.getVersion();
unit.getVersion(41239);
});
/* uncomment this and the `circuit` stuff above to test setting state
it('sets circuit state', done => {
it('sets circuit state', function(done) {
unit.on('circuitStateChanged', () => {
done();
});