Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 | 1x 1x 1x 1x 1x | /* Copyright(C) 2021-2024, donavanbecker (https://github.com/donavanbecker). All rights reserved.
*
* blindtilt.ts: @switchbot/homebridge-switchbot.
*/
import type { CharacteristicValue, PlatformAccessory, Service } from 'homebridge'
import type { blindTiltServiceData, blindTiltStatus, blindTiltWebhookContext, bodyChange, device, SwitchBotBLE, SwitchbotDevice, WoBlindTilt } from 'node-switchbot'
import type { SwitchBotPlatform } from '../platform.js'
import type { blindTiltConfig, devicesConfig } from '../settings.js'
/*
* For Testing Locally:
* import { SwitchBotBLEModel, SwitchBotBLEModelName } from '/Users/Shared/GitHub/OpenWonderLabs/node-switchbot/dist/index.js';
*/
import { SwitchBotBLEModel, SwitchBotBLEModelName } from 'node-switchbot'
import { debounceTime, interval, skipWhile, Subject, take, tap } from 'rxjs'
import { BlindTiltMappingMode, formatDeviceIdAsMac } from '../utils.js'
import { deviceBase } from './device.js'
export class BlindTilt extends deviceBase {
// Services
private WindowCovering: {
Name: CharacteristicValue
Service: Service
PositionState: CharacteristicValue
TargetPosition: CharacteristicValue
CurrentPosition: CharacteristicValue
TargetHorizontalTiltAngle: CharacteristicValue
CurrentHorizontalTiltAngle: CharacteristicValue
}
private Battery: {
Name: CharacteristicValue
Service: Service
BatteryLevel: CharacteristicValue
StatusLowBattery: CharacteristicValue
ChargingState?: CharacteristicValue
}
private LightSensor?: {
Name: CharacteristicValue
Service: Service
CurrentAmbientLightLevel?: CharacteristicValue
}
private OpenModeSwitch?: {
Name: CharacteristicValue
Service: Service
On: CharacteristicValue
}
private CloseModeSwitch?: {
Name: CharacteristicValue
Service: Service
On: CharacteristicValue
}
// OpenAPI
deviceStatus!: blindTiltStatus
mappingMode: BlindTiltMappingMode = BlindTiltMappingMode.OnlyUp
// Webhook
webhookContext!: blindTiltWebhookContext
// BLE
serviceData!: blindTiltServiceData
// Target
setNewTarget!: boolean
setNewTargetTimer!: NodeJS.Timeout
// Updates
blindTiltMoving: boolean
blindTiltUpdateInProgress: boolean
doBlindTiltUpdate: Subject<void>
constructor(
readonly platform: SwitchBotPlatform,
accessory: PlatformAccessory,
device: device & devicesConfig,
) {
super(platform, accessory, device)
// Set category
accessory.category = this.hap.Categories.WINDOW_COVERING
// default placeholders
this.mappingMode = ((device as blindTiltConfig).mapping as BlindTiltMappingMode) ?? BlindTiltMappingMode.OnlyUp
this.debugLog(`Mapping mode: ${this.mappingMode}`)
// this is subject we use to track when we need to POST changes to the SwitchBot API
this.doBlindTiltUpdate = new Subject()
this.blindTiltMoving = false
this.blindTiltUpdateInProgress = false
this.setNewTarget = false
// Initialize WindowCovering Service
accessory.context.WindowCovering = accessory.context.WindowCovering ?? {}
this.WindowCovering = {
Name: accessory.displayName,
Service: accessory.getService(this.hap.Service.WindowCovering) ?? accessory.addService(this.hap.Service.WindowCovering) as Service,
PositionState: accessory.context.PositionState ?? this.hap.Characteristic.PositionState.STOPPED,
TargetPosition: accessory.context.TargetPosition ?? 100,
CurrentPosition: accessory.context.CurrentPosition ?? 100,
TargetHorizontalTiltAngle: accessory.context.TargetHorizontalTiltAngle ?? 90,
CurrentHorizontalTiltAngle: accessory.context.CurrentHorizontalTiltAngle ?? 90,
}
accessory.context.WindowCovering = this.WindowCovering as object
// Initialize WindowCovering Characteristics
this.WindowCovering.Service.setCharacteristic(this.hap.Characteristic.Name, this.WindowCovering.Name).getCharacteristic(this.hap.Characteristic.TargetPosition).setProps({
minStep: (device as blindTiltConfig).set_minStep ?? 1,
minValue: 0,
maxValue: 100,
validValueRanges: [0, 100],
}).onGet(() => {
return this.WindowCovering.TargetPosition
}).onSet(this.TargetPositionSet.bind(this))
// Initialize WindowCovering CurrentPosition Characteristic
this.WindowCovering.Service.getCharacteristic(this.hap.Characteristic.CurrentPosition).setProps({
minStep: (device as blindTiltConfig).set_minStep ?? 1,
minValue: 0,
maxValue: 100,
validValueRanges: [0, 100],
}).onGet(() => {
return this.WindowCovering.CurrentPosition ?? 0
})
// Initialize WindowCovering TargetHorizontalTiltAngle Characteristic
this.WindowCovering.Service.getCharacteristic(this.hap.Characteristic.TargetHorizontalTiltAngle).setProps({
minStep: 180,
minValue: -90,
maxValue: 90,
validValues: [-90, 90],
}).onGet(() => {
return this.WindowCovering.TargetHorizontalTiltAngle
}).onSet(this.TargetHorizontalTiltAngleSet.bind(this))
// Initialize WindowCovering CurrentHorizontalTiltAngle Characteristic
this.WindowCovering.Service.getCharacteristic(this.hap.Characteristic.CurrentHorizontalTiltAngle).setProps({
minStep: 180,
minValue: -90,
maxValue: 90,
validValues: [-90, 90],
}).onGet(() => {
return this.WindowCovering.CurrentHorizontalTiltAngle ?? 0
})
// Initialize Battery Service
accessory.context.Battery = accessory.context.Battery ?? {}
this.Battery = {
Name: `${accessory.displayName} Battery`,
Service: accessory.getService(this.hap.Service.Battery) ?? accessory.addService(this.hap.Service.Battery) as Service,
BatteryLevel: accessory.context.BatteryLevel ?? 100,
StatusLowBattery: this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL,
ChargingState: accessory.context.ChargingState ?? this.hap.Characteristic.ChargingState.NOT_CHARGING,
}
accessory.context.Battery = this.Battery as object
// Initialize Battery Name Characteristic
this.Battery.Service.setCharacteristic(this.hap.Characteristic.Name, this.Battery.Name).setCharacteristic(this.hap.Characteristic.ChargingState, this.hap.Characteristic.ChargingState.NOT_CHARGEABLE)
// Initialize LightSensor Service
if ((device as blindTiltConfig).hide_lightsensor) {
if (this.LightSensor?.Service) {
this.debugLog('Removing Light Sensor Service')
this.LightSensor.Service = accessory.getService(this.hap.Service.LightSensor) as Service
accessory.removeService(this.LightSensor.Service)
accessory.context.LightSensor = {}
} else {
this.debugLog('Light Sensor Service is already removed')
}
} else {
accessory.context.LightSensor = accessory.context.LightSensor ?? {}
this.LightSensor = {
Name: `${accessory.displayName} Light Sensor`,
Service: accessory.getService(this.hap.Service.LightSensor) ?? accessory.addService(this.hap.Service.LightSensor) as Service,
CurrentAmbientLightLevel: accessory.context.CurrentAmbientLightLevel ?? 0.0001,
}
accessory.context.LightSensor = this.LightSensor as object
// Initialize LightSensor Characteristics
this.LightSensor.Service.setCharacteristic(this.hap.Characteristic.Name, this.LightSensor.Name).setCharacteristic(this.hap.Characteristic.StatusActive, true).getCharacteristic(this.hap.Characteristic.CurrentAmbientLightLevel).onGet(() => {
return this.LightSensor?.CurrentAmbientLightLevel ?? 0.0001
})
}
// Initialize Open Mode Switch Service
if (!(device as blindTiltConfig).silentModeSwitch) {
if (this.OpenModeSwitch?.Service) {
this.debugLog('Removing Open Mode Switch Service')
this.OpenModeSwitch.Service = this.accessory.getService(this.hap.Service.Switch) as Service
accessory.removeService(this.OpenModeSwitch.Service)
accessory.context.OpenModeSwitch = {}
}
} else {
accessory.context.OpenModeSwitch = accessory.context.OpenModeSwitch ?? {}
this.OpenModeSwitch = {
Name: `${accessory.displayName} Silent Open Mode`,
Service: accessory.getService(this.hap.Service.Switch) ?? accessory.addService(this.hap.Service.Switch) as Service,
On: accessory.context.OpenModeSwitch.On ?? false,
}
accessory.context.OpenModeSwitch = this.OpenModeSwitch as object
// Initialize Open Mode Switch Service
this.OpenModeSwitch.Service.setCharacteristic(this.hap.Characteristic.Name, this.OpenModeSwitch.Name).getCharacteristic(this.hap.Characteristic.On).onGet(() => {
return this.OpenModeSwitch?.On ?? false
})
this.OpenModeSwitch.Service.getCharacteristic(this.hap.Characteristic.On).onSet(this.OpenModeSwitchSet.bind(this))
}
// Initialize Close Mode Switch Service
if (!(device as blindTiltConfig).silentModeSwitch) {
if (this.CloseModeSwitch?.Service) {
this.debugLog('Removing Close Mode Switch Service')
this.CloseModeSwitch.Service = this.accessory.getService(this.hap.Service.Switch) as Service
accessory.removeService(this.CloseModeSwitch.Service)
accessory.context.CloseModeSwitch = {}
}
} else {
accessory.context.CloseModeSwitch = accessory.context.CloseModeSwitch ?? {}
this.CloseModeSwitch = {
Name: `${accessory.displayName} Silent Close Mode`,
Service: accessory.getService(this.hap.Service.Switch) ?? accessory.addService(this.hap.Service.Switch) as Service,
On: accessory.context.CloseModeSwitch.On ?? false,
}
accessory.context.CloseModeSwitch = this.CloseModeSwitch as object
// Initialize Close Mode Switch Service
this.CloseModeSwitch.Service.setCharacteristic(this.hap.Characteristic.Name, this.CloseModeSwitch.Name).getCharacteristic(this.hap.Characteristic.On).onGet(() => {
return this.CloseModeSwitch?.On ?? false
})
this.CloseModeSwitch.Service.getCharacteristic(this.hap.Characteristic.On).onSet(this.CloseModeSwitchSet.bind(this))
}
// Retrieve initial values and updateHomekit
try {
this.debugLog('Retrieve initial values and update Homekit')
this.refreshStatus()
} catch (e: any) {
this.errorLog(`failed to retrieve initial values and update Homekit, Error: ${e.message ?? e}`)
}
// regisiter webhook event handler if enabled
try {
this.debugLog('Registering Webhook Event Handler')
this.registerWebhook()
} catch (e: any) {
this.errorLog(`failed to registerWebhook, Error: ${e.message ?? e}`)
}
// regisiter platform BLE event handler if enabled
try {
this.debugLog('Registering Platform BLE Event Handler')
this.registerPlatformBLE()
} catch (e: any) {
this.errorLog(`failed to registerPlatformBLE, Error: ${e.message ?? e}`)
}
// Start an update interval
interval(this.deviceRefreshRate * 1000)
.pipe(skipWhile(() => this.blindTiltUpdateInProgress))
.subscribe(async () => {
await this.refreshStatus()
})
// update slide progress
interval(this.deviceUpdateRate * 1000)
.pipe(skipWhile(() => !this.blindTiltMoving))
.subscribe(async () => {
if (this.WindowCovering.PositionState === this.hap.Characteristic.PositionState.STOPPED) {
return
}
this.debugLog(`Refresh Status When Moving, PositionState: ${this.WindowCovering.PositionState}`)
await this.refreshStatus()
})
// Watch for BlindTilt change events
// We put in a debounce of 100ms so we don't make duplicate calls
this.doBlindTiltUpdate
.pipe(
tap(() => {
this.blindTiltUpdateInProgress = true
}),
debounceTime(this.devicePushRate * 1000),
)
.subscribe(async () => {
try {
await this.pushChanges()
} catch (e: any) {
await this.apiError(e)
this.errorLog(`failed pushChanges with ${device.connectionType} Connection, Error Message: ${JSON.stringify(e.message)}`)
}
this.blindTiltUpdateInProgress = false
})
}
/**
* Parse the device status from the SwitchBotBLE API
*/
async BLEparseStatus(): Promise<void> {
this.debugLog('BLEparseStatus')
this.debugLog(`(direction, slidePosition, battery, version) = BLE:(${this.serviceData.tilt}, ${this.serviceData.tilt}, ${this.serviceData.battery}, ${this.accessory.context.version}), current:(${this.WindowCovering.CurrentHorizontalTiltAngle}, ${this.WindowCovering.CurrentPosition}, ${this.Battery.BatteryLevel}, ${this.accessory.context.version})`)
// CurrentPosition
this.WindowCovering.CurrentPosition = 100 - Number(this.serviceData.tilt)
await this.setMinMax()
this.debugLog(`CurrentPosition ${this.WindowCovering.CurrentPosition}`)
if (this.setNewTarget) {
this.infoLog('Checking Status ...')
}
if (this.setNewTarget && this.serviceData.inMotion) {
this.blindTiltMoving = true
await this.setMinMax()
if (Number(this.WindowCovering.TargetPosition) > this.WindowCovering.CurrentPosition) {
this.debugLog(`Closing, CurrentPosition: ${this.WindowCovering.CurrentPosition}`)
this.WindowCovering.PositionState = this.hap.Characteristic.PositionState.INCREASING
this.WindowCovering.Service.getCharacteristic(this.hap.Characteristic.PositionState).updateValue(this.WindowCovering.PositionState)
this.debugLog(`Increasing, PositionState: ${this.WindowCovering.PositionState}`)
} else if (Number(this.WindowCovering.TargetPosition) < this.WindowCovering.CurrentPosition) {
this.debugLog(`Opening, CurrentPosition: ${this.WindowCovering.CurrentPosition}`)
this.WindowCovering.PositionState = this.hap.Characteristic.PositionState.DECREASING
this.WindowCovering.Service.getCharacteristic(this.hap.Characteristic.PositionState).updateValue(this.WindowCovering.PositionState)
this.debugLog(`Decreasing, PositionState: ${this.WindowCovering.PositionState}`)
} else {
this.debugLog(`Standby, CurrentPosition: ${this.WindowCovering.CurrentPosition}`)
this.WindowCovering.PositionState = this.hap.Characteristic.PositionState.STOPPED
this.WindowCovering.Service.getCharacteristic(this.hap.Characteristic.PositionState).updateValue(this.WindowCovering.PositionState)
this.debugLog('Stopped, PositionState', this.WindowCovering.PositionState)
}
} else {
this.blindTiltMoving = false
this.debugLog(`Standby, CurrentPosition: ${this.WindowCovering.CurrentPosition}`)
this.WindowCovering.TargetPosition = this.WindowCovering.CurrentPosition
this.WindowCovering.PositionState = this.hap.Characteristic.PositionState.STOPPED
this.debugLog(`Stopped, PositionState: ${this.WindowCovering.PositionState}`)
}
this.debugLog(`CurrentPosition: ${this.WindowCovering.CurrentPosition}, TargetPosition: ${this.WindowCovering.TargetPosition}, PositionState: ${this.WindowCovering.PositionState}`)
// CurrentAmbientLightLevel
if (!(this.device as blindTiltConfig).hide_lightsensor && this.LightSensor?.Service) {
const set_minLux = (this.device as blindTiltConfig).set_minLux ?? 1
const set_maxLux = (this.device as blindTiltConfig).set_maxLux ?? 6001
const spaceBetweenLevels = 9
this.getLightLevel(this.serviceData.lightLevel, set_minLux, set_maxLux, spaceBetweenLevels)
this.debugLog(`LightLevel: ${this.serviceData.lightLevel}, CurrentAmbientLightLevel: ${this.LightSensor!.CurrentAmbientLightLevel}`)
}
// Battery Info
if ('battery' in this.serviceData) {
// BatteryLevel
this.Battery.BatteryLevel = this.serviceData.battery
this.debugLog(`BatteryLevel: ${this.Battery.BatteryLevel}`)
// StatusLowBattery
this.Battery.StatusLowBattery = this.Battery.BatteryLevel < 10
? this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW
: this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL
this.debugLog(`StatusLowBattery: ${this.Battery.StatusLowBattery}`)
}
};
/**
* Parse the device status from the SwitchBot OpenAPI
*/
async openAPIparseStatus(): Promise<void> {
this.debugLog('openAPIparseStatus')
this.debugLog(`(direction, slidePosition, battery, version) = OpenAPI:(${this.deviceStatus.direction}, ${this.deviceStatus.slidePosition}, ${this.deviceStatus.battery}, ${this.deviceStatus.version}), current:(${this.WindowCovering.CurrentHorizontalTiltAngle}, ${this.WindowCovering.CurrentPosition}, ${this.Battery.BatteryLevel}, ${this.accessory.context.version})`)
// CurrentPosition
await this.getCurrentPosttionDirection(this.deviceStatus.direction, this.deviceStatus.slidePosition)
if (!(this.device as blindTiltConfig).hide_lightsensor && this.LightSensor?.Service) {
const set_minLux = (this.device as blindTiltConfig).set_minLux ?? 1
const set_maxLux = (this.device as blindTiltConfig).set_maxLux ?? 6001
const lightLevel = this.deviceStatus.lightLevel === 'bright' ? set_maxLux : set_minLux
this.LightSensor.CurrentAmbientLightLevel = this.getLightLevel(lightLevel, set_minLux, set_maxLux, 2)
this.debugLog(`LightLevel: ${this.deviceStatus.lightLevel}, CurrentAmbientLightLevel: ${this.LightSensor.CurrentAmbientLightLevel}`)
}
// BatteryLevel
this.Battery.BatteryLevel = this.deviceStatus.battery
this.debugLog(`BatteryLevel: ${this.Battery.BatteryLevel}`)
// StatusLowBattery
this.Battery.StatusLowBattery = this.Battery.BatteryLevel < 10
? this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW
: this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL
this.debugLog(`StatusLowBattery: ${this.Battery.StatusLowBattery}`)
// Firmware Version
const version = this.deviceStatus.version.toString()
this.debugLog(`Firmware Version: ${version.replace(/^V|-.*$/g, '')}`)
let deviceVersion: string
if (version?.includes('.') === false) {
const replace = version?.replace(/^V|-.*$/g, '')
const match = replace?.match(/./g)
const blindTiltVersion = match?.join('.') ?? '0.0.0'
deviceVersion = blindTiltVersion
} else {
deviceVersion = version.replace(/^V|-.*$/g, '') ?? '0.0.0'
}
this.accessory
.getService(this.hap.Service.AccessoryInformation)!
.setCharacteristic(this.hap.Characteristic.HardwareRevision, deviceVersion)
.setCharacteristic(this.hap.Characteristic.FirmwareRevision, deviceVersion)
.getCharacteristic(this.hap.Characteristic.FirmwareRevision)
.updateValue(deviceVersion)
this.accessory.context.version = deviceVersion
this.debugLog(`version: ${this.accessory.context.version}`)
}
async parseStatusWebhook(): Promise<void> {
this.debugLog('parseStatusWebhook')
this.debugLog(`(slidePosition, battery, version) = Webhook:(${this.webhookContext.direction}, ${this.webhookContext.slidePosition}, ${this.webhookContext.battery}, ${this.webhookContext.version}, current:(${this.WindowCovering.CurrentHorizontalTiltAngle}, ${this.WindowCovering.CurrentPosition}, ${this.Battery.BatteryLevel}, ${this.accessory.context.version})`)
// CurrentPosition and CurrentHorizontalTiltAngle
await this.getCurrentPosttionDirection(this.webhookContext.direction, this.webhookContext.slidePosition)
// BatteryLevel
this.Battery.BatteryLevel = this.webhookContext.battery
this.debugLog(`BatteryLevel: ${this.Battery.BatteryLevel}`)
// StatusLowBattery
this.Battery.StatusLowBattery = this.Battery.BatteryLevel < 10
? this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW
: this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL
this.debugLog(`StatusLowBattery: ${this.Battery.StatusLowBattery}`)
// Firmware Version
const deviceVersion = this.webhookContext.version.replace(/^V|-.*$/g, '') ?? '0.0.0'
this.accessory
.getService(this.hap.Service.AccessoryInformation)!
.setCharacteristic(this.hap.Characteristic.HardwareRevision, deviceVersion)
.setCharacteristic(this.hap.Characteristic.FirmwareRevision, deviceVersion)
.getCharacteristic(this.hap.Characteristic.FirmwareRevision)
.updateValue(deviceVersion)
this.accessory.context.version = deviceVersion
this.debugSuccessLog(`version: ${this.accessory.context.version}`)
}
/**
* Asks the SwitchBot API for the latest device information
*/
async refreshStatus(): Promise<void> {
if (!this.device.enableCloudService && this.OpenAPI) {
this.errorLog(`refreshStatus enableCloudService: ${this.device.enableCloudService}`)
} else if (this.BLE) {
await this.BLERefreshStatus()
} else if (this.OpenAPI && this.platform.config.credentials?.token) {
await this.openAPIRefreshStatus()
} else {
await this.offlineOff()
this.debugWarnLog(`Connection Type: ${this.device.connectionType}, refreshStatus will not happen.`)
}
}
async BLERefreshStatus(): Promise<void> {
this.debugLog('BLERefreshStatus')
const switchBotBLE = await this.switchbotBLE()
if (switchBotBLE === undefined) {
await this.BLERefreshConnection(switchBotBLE)
} else {
// Start to monitor advertisement packets
(async () => {
// Start to monitor advertisement packets
const serviceData = await this.monitorAdvertisementPackets(switchBotBLE) as blindTiltServiceData
// Update HomeKit
if (serviceData.model === SwitchBotBLEModel.BlindTilt && serviceData.modelName === SwitchBotBLEModelName.BlindTilt) {
this.serviceData = serviceData
if (serviceData !== undefined || serviceData !== null) {
await this.BLEparseStatus()
await this.updateHomeKitCharacteristics()
} else {
this.errorLog(`serviceData is either undefined or null, serviceData: ${JSON.stringify(serviceData)}`)
await this.BLERefreshConnection(switchBotBLE)
}
} else {
this.errorLog(`failed to get serviceData, serviceData: ${JSON.stringify(serviceData)}`)
await this.BLERefreshConnection(switchBotBLE)
}
})()
}
}
async registerPlatformBLE(): Promise<void> {
this.debugLog('registerPlatformBLE')
if (this.config.options?.BLE && !this.device.disablePlatformBLE) {
this.debugLog('is listening to Platform BLE.')
try {
const formattedDeviceId = formatDeviceIdAsMac(this.device.deviceId)
this.device.bleMac = formattedDeviceId
this.debugLog(`bleMac: ${this.device.bleMac}`)
this.platform.bleEventHandler[this.device.bleMac] = async (context: blindTiltServiceData) => {
try {
this.serviceData = context
if (context !== undefined || context !== null) {
this.debugLog(`received BLE: ${JSON.stringify(context)}`)
await this.BLEparseStatus()
await this.updateHomeKitCharacteristics()
} else {
this.errorLog(`context is either undefined or null, context: ${JSON.stringify(context)}`)
await this.BLERefreshConnection(context)
}
} catch (e: any) {
this.errorLog(`failed to handle BLE. Received: ${JSON.stringify(context)} Error: ${e.message ?? e}`)
}
}
} catch (error) {
this.errorLog(`failed to format device ID as MAC, Error: ${error}`)
}
} else {
this.debugLog('is not listening to Platform BLE')
}
}
async openAPIRefreshStatus(): Promise<void> {
this.debugLog('openAPIRefreshStatus')
try {
const response = await this.deviceRefreshStatus()
const deviceStatus: any = response.body
this.debugLog(`statusCode: ${deviceStatus.statusCode}, deviceStatus: ${JSON.stringify(deviceStatus)}`)
if (await this.successfulStatusCodes(deviceStatus)) {
this.debugSuccessLog(`statusCode: ${deviceStatus.statusCode}, deviceStatus: ${JSON.stringify(deviceStatus)}`)
this.deviceStatus = deviceStatus.body
await this.openAPIparseStatus()
await this.updateHomeKitCharacteristics()
} else {
this.debugWarnLog(`statusCode: ${deviceStatus.statusCode}, deviceStatus: ${JSON.stringify(deviceStatus)}`)
}
} catch (e: any) {
await this.apiError(e)
this.errorLog(`failed openAPIRefreshStatus with ${this.device.connectionType} Connection, Error Message: ${JSON.stringify(e.message)}`)
}
}
async registerWebhook(): Promise<void> {
if (this.device.webhook) {
this.debugLog('is listening webhook.')
this.platform.webhookEventHandler[this.device.deviceId] = async (context: blindTiltWebhookContext) => {
try {
this.webhookContext = context
if (context !== undefined || context !== null) {
this.debugLog(`received Webhook: ${JSON.stringify(context)}`)
await this.parseStatusWebhook()
await this.updateHomeKitCharacteristics()
} else {
this.errorLog(`context is either undefined or null, context: ${JSON.stringify(context)}`)
}
} catch (e: any) {
this.errorLog(`failed to handle webhook. Received: ${JSON.stringify(context)} Error: ${e.message ?? e}`)
}
}
} else {
this.debugLog('is not listening webhook.')
}
}
async pushChanges(): Promise<void> {
if (!this.device.enableCloudService && this.OpenAPI) {
this.errorLog(`pushChanges enableCloudService: ${this.device.enableCloudService}`)
} else if (this.BLE) {
await this.BLEpushChanges()
} else if (this.OpenAPI && this.platform.config.credentials?.token) {
await this.openAPIpushChanges()
} else {
await this.offlineOff()
this.debugWarnLog(`Connection Type: ${this.device.connectionType}, pushChanges will not happen.`)
}
// Refresh the status from the API
interval(15000)
.pipe(skipWhile(() => this.blindTiltUpdateInProgress))
.pipe(take(1))
.subscribe(async () => {
await this.refreshStatus()
})
}
async BLEpushChanges(): Promise<void> {
this.debugLog('BLEpushChanges')
if (this.WindowCovering.TargetPosition !== this.WindowCovering.CurrentPosition) {
this.debugLog(`BLEpushChanges On: ${this.WindowCovering.TargetPosition} OnCached: ${this.WindowCovering.CurrentPosition}`)
const switchBotBLE = await this.platform.connectBLE(this.accessory, this.device)
try {
const formattedDeviceId = formatDeviceIdAsMac(this.device.deviceId)
this.device.bleMac = formattedDeviceId
this.debugLog(`bleMac: ${this.device.bleMac}`)
const { setPositionMode, Mode }: { setPositionMode: number, Mode: string } = await this.setPerformance()
this.debugLog(`Mode: ${Mode}, setPositionMode: ${setPositionMode}`)
if (switchBotBLE !== false) {
switchBotBLE
.discover({ model: this.device.bleModel, quick: true, id: this.device.bleMac })
.then(async (device_list: SwitchbotDevice[]) => {
const deviceList = device_list as WoBlindTilt[]
return await this.retryBLE({
max: this.maxRetryBLE(),
fn: async () => {
return await deviceList[0].runToPos(100 - Number(this.WindowCovering.TargetPosition), setPositionMode)
},
})
})
.then(async () => {
this.successLog(`TargetPostion: ${this.WindowCovering.TargetPosition} sent over SwitchBot BLE, sent successfully`)
await this.updateHomeKitCharacteristics()
})
.catch(async (e: any) => {
await this.apiError(e)
this.errorLog(`failed BLEpushChanges with ${this.device.connectionType} Connection, Error Message: ${JSON.stringify(e.message)}`)
await this.BLEPushConnection()
})
} else {
this.errorLog(`wasn't able to establish BLE Connection, node-switchbot: ${JSON.stringify(switchBotBLE)}`)
await this.BLEPushConnection()
}
} catch (error) {
this.errorLog(`failed to format device ID as MAC, Error: ${error}`)
}
} else {
this.debugLog(`No changes (BLEpushChanges), TargetPosition: ${this.WindowCovering.TargetPosition}, CurrentPosition: ${this.WindowCovering.CurrentPosition}`)
}
}
async openAPIpushChanges(): Promise<void> {
this.debugLog('openAPIpushChanges')
const hasDifferentAndRelevantHorizontalTiltAngle
= this.mappingMode === BlindTiltMappingMode.UseTiltForDirection
&& this.WindowCovering.TargetHorizontalTiltAngle !== this.WindowCovering.CurrentHorizontalTiltAngle
if (this.WindowCovering.TargetPosition !== this.WindowCovering.CurrentPosition
|| hasDifferentAndRelevantHorizontalTiltAngle || this.device.disableCaching) {
const [direction, position] = this.mapHomekitValuesToDeviceValues(Number(this.WindowCovering.TargetPosition), Number(this.WindowCovering.TargetHorizontalTiltAngle))
const { Mode, setPositionMode }: { setPositionMode: number, Mode: string } = await this.setPerformance()
this.debugLog(`Pushing ${this.WindowCovering.TargetPosition} (device = ${direction};${position})`)
this.debugLog(`Mode: ${Mode}, setPositionMode: ${setPositionMode}`)
let bodyChange: bodyChange
if (position === 100) {
bodyChange = {
command: 'fullyOpen',
parameter: 'default',
commandType: 'command',
}
} else if (position === 0) {
bodyChange = {
command: direction === 'up' ? 'closeUp' : 'closeDown',
parameter: 'default',
commandType: 'command',
}
} else {
bodyChange = {
command: 'setPosition',
parameter: `${direction};${position}`,
commandType: 'command',
}
}
this.debugLog(`SwitchBot OpenAPI bodyChange: ${JSON.stringify(bodyChange)}`)
try {
const response = await this.pushChangeRequest(bodyChange)
const deviceStatus: any = response.body
this.debugLog(`statusCode: ${deviceStatus.statusCode}, deviceStatus: ${JSON.stringify(deviceStatus)}`)
if (await this.successfulStatusCodes(deviceStatus)) {
this.debugSuccessLog(`statusCode: ${deviceStatus.statusCode}, deviceStatus: ${JSON.stringify(deviceStatus)}`)
await this.updateHomeKitCharacteristics()
} else {
await this.statusCode(deviceStatus.statusCode)
}
} catch (e: any) {
await this.apiError(e)
this.errorLog(`failed openAPIpushChanges with ${this.device.connectionType} Connection, Error Message: ${JSON.stringify(e.message)}`)
}
} else {
this.debugLog(`No changes (openAPIpushChanges), TargetPosition: ${this.WindowCovering.TargetPosition}, CurrentPosition: ${this.WindowCovering.CurrentPosition}`)
this.debugLog(`No changes (openAPIpushChanges), TargetHorizontalTiltAngle: ${this.WindowCovering.TargetHorizontalTiltAngle}, CurrentHorizontalTiltAngle: ${this.WindowCovering.CurrentHorizontalTiltAngle}`)
}
}
/**
* Handle requests to set the value of the "Target Horizontal Tilt" characteristic
*/
async TargetHorizontalTiltAngleSet(value: CharacteristicValue): Promise<void> {
if (this.WindowCovering.TargetHorizontalTiltAngle !== this.accessory.context.TargetHorizontalTiltAngle) {
this.debugLog(`Set TargetHorizontalTiltAngle: ${value}`)
} else {
this.debugLog(`No changes, TargetHorizontalTiltAngle: ${value}`)
}
// value = value < 0 ? -90 : 90;
this.WindowCovering.TargetHorizontalTiltAngle = value
await this.mqtt('TargetHorizontalTiltAngle', this.WindowCovering.TargetHorizontalTiltAngle)
await this.startUpdatingBlindTiltIfNeeded()
}
/**
* Handle requests to set the value of the "Target Position" characteristic
*/
async TargetPositionSet(value: CharacteristicValue): Promise<void> {
if (this.WindowCovering.TargetPosition !== this.accessory.context.TargetPosition) {
this.debugLog(`Set TargetPosition: ${value}`)
} else {
this.debugLog(`No changes, TargetPosition: ${value}`)
}
this.WindowCovering.TargetPosition = value
await this.mqtt('TargetPosition', this.WindowCovering.TargetPosition)
await this.startUpdatingBlindTiltIfNeeded()
}
async startUpdatingBlindTiltIfNeeded(): Promise<void> {
await this.setMinMax()
this.debugLog('setMinMax')
if (this.WindowCovering.TargetPosition > this.WindowCovering.CurrentPosition
|| this.WindowCovering.TargetHorizontalTiltAngle !== this.WindowCovering.CurrentHorizontalTiltAngle) {
this.WindowCovering.PositionState = this.hap.Characteristic.PositionState.INCREASING
this.setNewTarget = true
this.debugLog(`value: ${this.WindowCovering.CurrentPosition}, CurrentPosition: ${this.WindowCovering.CurrentPosition}`)
} else if (this.WindowCovering.TargetPosition < this.WindowCovering.CurrentPosition) {
this.WindowCovering.PositionState = this.hap.Characteristic.PositionState.DECREASING
this.setNewTarget = true
this.debugLog(`value: ${this.WindowCovering.CurrentPosition}, CurrentPosition: ${this.WindowCovering.CurrentPosition}`)
} else {
this.WindowCovering.PositionState = this.hap.Characteristic.PositionState.STOPPED
this.setNewTarget = false
this.debugLog(`value: ${this.WindowCovering.CurrentPosition}, CurrentPosition: ${this.WindowCovering.CurrentPosition}`)
}
this.WindowCovering.Service.setCharacteristic(this.hap.Characteristic.PositionState, this.WindowCovering.PositionState)
this.WindowCovering.Service.getCharacteristic(this.hap.Characteristic.PositionState).updateValue(this.WindowCovering.PositionState)
/**
* If Blind Tilt movement time is short, the moving flag from backend is always false.
* The minimum time depends on the network control latency.
*/
clearTimeout(this.setNewTargetTimer)
this.debugLog(`deviceUpdateRate: ${this.deviceUpdateRate}`)
if (this.setNewTarget) {
this.setNewTargetTimer = setTimeout(async () => {
this.debugLog(`setNewTarget ${this.setNewTarget} timeout`)
this.setNewTarget = false
}, this.deviceUpdateRate * 1000)
}
this.doBlindTiltUpdate.next()
}
/**
* Handle requests to set the value of the "Target Position" characteristic
*/
async OpenModeSwitchSet(value: CharacteristicValue): Promise<void> {
if (this.OpenModeSwitch && (this.device as blindTiltConfig).silentModeSwitch) {
this.debugLog(`Silent Open Mode: ${value}`)
this.OpenModeSwitch.On = value
this.accessory.context.OpenModeSwitch.On = value
this.doBlindTiltUpdate.next()
}
}
/**
* Handle requests to set the value of the "Target Position" characteristic
*/
async CloseModeSwitchSet(value: CharacteristicValue): Promise<void> {
if (this.CloseModeSwitch && (this.device as blindTiltConfig).silentModeSwitch) {
this.debugLog(`Silent Close Mode: ${value}`)
this.CloseModeSwitch.On = value
this.accessory.context.CloseModeSwitch.On = value
this.doBlindTiltUpdate.next()
}
}
async updateHomeKitCharacteristics(): Promise<void> {
await this.setMinMax()
// CurrentHorizontalTiltAngle
if (this.mappingMode === BlindTiltMappingMode.UseTiltForDirection) {
await this.updateCharacteristic(this.WindowCovering.Service, this.hap.Characteristic.CurrentHorizontalTiltAngle, this.WindowCovering.CurrentHorizontalTiltAngle, 'CurrentHorizontalTiltAngle')
}
// CurrentPosition
await this.updateCharacteristic(this.WindowCovering.Service, this.hap.Characteristic.CurrentPosition, this.WindowCovering.CurrentPosition, 'CurrentPosition')
// PositionState
await this.updateCharacteristic(this.WindowCovering.Service, this.hap.Characteristic.PositionState, this.WindowCovering.PositionState, 'PositionState')
// TargetPosition
await this.updateCharacteristic(this.WindowCovering.Service, this.hap.Characteristic.TargetPosition, this.WindowCovering.TargetPosition, 'TargetPosition')
// CurrentAmbientLightLevel
if (!(this.device as blindTiltConfig).hide_lightsensor && this.LightSensor?.Service) {
const history = { time: Math.round(new Date().valueOf() / 1000), lux: this.LightSensor.CurrentAmbientLightLevel }
await this.updateCharacteristic(this.LightSensor?.Service, this.hap.Characteristic.CurrentAmbientLightLevel, this.LightSensor?.CurrentAmbientLightLevel, 'CurrentAmbientLightLevel', history)
}
// BatteryLevel
await this.updateCharacteristic(this.Battery.Service, this.hap.Characteristic.BatteryLevel, this.Battery.BatteryLevel, 'BatteryLevel')
// StatusLowBattery
await this.updateCharacteristic(this.Battery.Service, this.hap.Characteristic.StatusLowBattery, this.Battery.StatusLowBattery, 'StatusLowBattery')
// ChargingState
await this.updateCharacteristic(this.Battery.Service, this.hap.Characteristic.ChargingState, this.Battery.ChargingState, 'ChargingState')
}
async BLEPushConnection() {
if (this.platform.config.credentials?.token && this.device.connectionType === 'BLE/OpenAPI') {
this.warnLog('Using OpenAPI Connection to Push Changes')
await this.openAPIpushChanges()
}
}
async BLERefreshConnection(switchbot: SwitchBotBLE): Promise<void> {
this.errorLog(`wasn't able to establish BLE Connection, node-switchbot: ${switchbot}`)
if (this.platform.config.credentials?.token && this.device.connectionType === 'BLE/OpenAPI') {
this.warnLog('Using OpenAPI Connection to Refresh Status')
await this.openAPIRefreshStatus()
}
}
async setPerformance() {
let setPositionMode: number
let Mode: string
if (Number(this.WindowCovering.TargetPosition) > 50) {
if ((this.device as blindTiltConfig).setOpenMode === '1' || this.OpenModeSwitch?.On) {
setPositionMode = 1
Mode = 'Silent Mode'
} else if ((this.device as blindTiltConfig).setOpenMode === '0' || !this.OpenModeSwitch?.On) {
setPositionMode = 0
Mode = 'Performance Mode'
} else {
setPositionMode = 0
Mode = 'Default Mode'
}
} else {
if ((this.device as blindTiltConfig).setCloseMode === '1' || this.CloseModeSwitch?.On) {
setPositionMode = 1
Mode = 'Silent Mode'
} else if ((this.device as blindTiltConfig).setOpenMode === '0' || !this.CloseModeSwitch?.On) {
setPositionMode = 0
Mode = 'Performance Mode'
} else {
setPositionMode = 0
Mode = 'Default Mode'
}
}
return { setPositionMode, Mode }
}
async setMinMax(): Promise<void> {
if ((this.device as blindTiltConfig).set_min) {
if (Number(this.WindowCovering.CurrentPosition) <= (this.device as blindTiltConfig).set_min!) {
this.WindowCovering.CurrentPosition = 0
}
}
if ((this.device as blindTiltConfig).set_max) {
if (Number(this.WindowCovering.CurrentPosition) >= (this.device as blindTiltConfig).set_max!) {
this.WindowCovering.CurrentPosition = 100
}
}
if (this.device.history) {
const motion = this.accessory.getService(this.hap.Service.MotionSensor)
const state = Number(this.WindowCovering.CurrentPosition) > 0 ? 1 : 0
motion?.updateCharacteristic(this.hap.Characteristic.MotionDetected, state)
}
if (this.mappingMode === BlindTiltMappingMode.UseTiltForDirection) {
this.WindowCovering.CurrentHorizontalTiltAngle = Number(this.WindowCovering.CurrentHorizontalTiltAngle) < 0 ? -90 : 90
}
}
async offlineOff(): Promise<void> {
if (this.device.offline) {
this.WindowCovering.Service.updateCharacteristic(this.hap.Characteristic.CurrentPosition, 100)
this.WindowCovering.Service.updateCharacteristic(this.hap.Characteristic.PositionState, this.hap.Characteristic.PositionState.STOPPED)
this.WindowCovering.Service.updateCharacteristic(this.hap.Characteristic.TargetPosition, 100)
this.WindowCovering.Service.updateCharacteristic(this.hap.Characteristic.CurrentHorizontalTiltAngle, 90)
this.WindowCovering.Service.updateCharacteristic(this.hap.Characteristic.TargetHorizontalTiltAngle, 90)
}
}
async apiError(e: any): Promise<void> {
this.WindowCovering.Service.updateCharacteristic(this.hap.Characteristic.CurrentPosition, e)
this.WindowCovering.Service.updateCharacteristic(this.hap.Characteristic.PositionState, e)
this.WindowCovering.Service.updateCharacteristic(this.hap.Characteristic.TargetPosition, e)
this.WindowCovering.Service.updateCharacteristic(this.hap.Characteristic.CurrentHorizontalTiltAngle, e)
this.WindowCovering.Service.updateCharacteristic(this.hap.Characteristic.TargetHorizontalTiltAngle, e)
this.Battery.Service.updateCharacteristic(this.hap.Characteristic.BatteryLevel, e)
this.Battery.Service.updateCharacteristic(this.hap.Characteristic.StatusLowBattery, e)
this.Battery.Service.updateCharacteristic(this.hap.Characteristic.ChargingState, e)
if (!(this.device as blindTiltConfig).hide_lightsensor && this.LightSensor?.Service) {
this.LightSensor.Service.updateCharacteristic(this.hap.Characteristic.CurrentAmbientLightLevel, e)
this.LightSensor.Service.updateCharacteristic(this.hap.Characteristic.StatusActive, e)
}
}
async getCurrentPosttionDirection(
direction: blindTiltStatus['direction'] | blindTiltWebhookContext['direction'],
slidePosition: blindTiltStatus['slidePosition'] | blindTiltWebhookContext['slidePosition'],
) {
const [homekitPosition, homekitTiltAngle] = this.mapDeviceValuesToHomekitValues(Number(slidePosition), String(direction))
this.debugLog(`Slide Position: ${slidePosition}`)
this.debugLog(`Homekit Position: ${homekitPosition}`)
this.WindowCovering.CurrentPosition = homekitPosition
await this.setMinMax()
this.debugLog(`CurrentPosition: ${this.WindowCovering.CurrentPosition}`)
if (homekitTiltAngle) {
this.WindowCovering.CurrentHorizontalTiltAngle = homekitTiltAngle!
this.debugLog(`CurrentHorizontalTiltAngle: ${this.WindowCovering.CurrentHorizontalTiltAngle}`)
}
if (this.setNewTarget) {
this.blindTiltMoving = true
this.infoLog('Checking Status ...')
await this.setMinMax()
if (this.WindowCovering.TargetPosition > this.WindowCovering.CurrentPosition
|| (homekitTiltAngle && this.WindowCovering.TargetHorizontalTiltAngle !== this.WindowCovering.CurrentHorizontalTiltAngle)) {
this.debugLog(`Closing, CurrentPosition: ${this.WindowCovering.CurrentPosition}`)
this.WindowCovering.PositionState = this.hap.Characteristic.PositionState.INCREASING
this.WindowCovering.Service.getCharacteristic(this.hap.Characteristic.PositionState).updateValue(this.WindowCovering.PositionState)
this.debugLog(`Increasing, PositionState: ${this.WindowCovering.PositionState}`)
} else if (this.WindowCovering.TargetPosition < this.WindowCovering.CurrentPosition) {
this.debugLog(`Opening, CurrentPosition: ${this.WindowCovering.CurrentPosition}`)
this.WindowCovering.PositionState = this.hap.Characteristic.PositionState.DECREASING
this.WindowCovering.Service.getCharacteristic(this.hap.Characteristic.PositionState).updateValue(this.WindowCovering.PositionState)
this.debugLog(`Decreasing, PositionState: ${this.WindowCovering.PositionState}`)
} else {
this.debugLog(`Standby because reached position, CurrentPosition: ${this.WindowCovering.CurrentPosition}`)
this.WindowCovering.PositionState = this.hap.Characteristic.PositionState.STOPPED
this.WindowCovering.Service.getCharacteristic(this.hap.Characteristic.PositionState).updateValue(this.WindowCovering.PositionState)
this.debugLog(`Stopped, PositionState: ${this.WindowCovering.PositionState}`)
}
} else {
this.blindTiltMoving = false
this.debugLog(`Standby because device not moving, CurrentPosition: ${this.WindowCovering.CurrentPosition}`)
this.WindowCovering.TargetPosition = this.WindowCovering.CurrentPosition
if (homekitTiltAngle) {
this.WindowCovering.TargetHorizontalTiltAngle = this.WindowCovering.CurrentHorizontalTiltAngle
}
this.WindowCovering.PositionState = this.hap.Characteristic.PositionState.STOPPED
this.debugLog(`Stopped, PositionState: ${this.WindowCovering.PositionState}`)
}
this.debugLog(`CurrentPosition: ${this.WindowCovering.CurrentPosition}, TargetPosition: ${this.WindowCovering.TargetPosition}, PositionState: ${this.WindowCovering.PositionState}`)
}
/**
* Maps device values to homekit values
*
* @param devicePosition the position as reported by the devide
* @param deviceDirection the direction as reported by the device
* @returns [homekit position, homekit tiltAngle]
*/
mapDeviceValuesToHomekitValues(devicePosition: number, deviceDirection: string): [CharacteristicValue, CharacteristicValue?] {
// device position 0 => closed down
// device position 50 => open
// device position 100 => closed up
// homekit position 0 => closed
// homekit position 100 => open
const direction = deviceDirection === 'up' ? 'up' : 'down'
this.debugLog(`Mapping device values to homekit values, devicePostion: ${devicePosition}, deviceDirection: ${direction}`)
switch (this.mappingMode) {
case BlindTiltMappingMode.OnlyUp:
// we only close upwards, so we see anything that is tilted downwards(<50) as open
if (devicePosition < 50) {
return [100, undefined] // fully open in homekit
} else {
// we range from 50->100, with 100 being closed, so map to homekit by scaling to 0..100 and then reversing
return [100 - (devicePosition - 50) * 2, undefined]
}
case BlindTiltMappingMode.OnlyDown:
// we only close downwards, so we see anything that is tilted upwards(>50) as upwards
if (devicePosition > 50) {
return [100, undefined] // fully open in homekit
} else {
// we range from 0..50 so scale to homekit and then reverse
return [devicePosition * 2, undefined]
}
case BlindTiltMappingMode.DownAndUp:
// we close both ways with closed downwards being 0 in homekit and closed upwards in homekit being 100. Open is 50 in homekit
return [devicePosition, undefined]
case BlindTiltMappingMode.UpAndDown:
// we close both ways with closed downwards being 1000 in homekit and closed upwards in homekit being 0. Open is 50 in homekit.,
// so we reverse the value
return [100 - devicePosition, undefined]
case BlindTiltMappingMode.UseTiltForDirection:
// we use tilt for direction, so being closed downwards is 0 in homekit with -90 tilt, while being closed upwards is 0 with 90 tilt.
if (devicePosition <= 50) {
// downwards tilted, so we range from 0..50, with 0 being closed and 50 being open, so scale.
return [devicePosition * 2, -90]
} else {
// upwards tilted, so we range from 50..100, with 50 being open and 100 being closed, so scale and rever
return [100 - (devicePosition - 50) * 2, 90]
}
}
}
/**
* Maps homekit values to device values
*
* @param homekitPosition the position as reported by homekit
* @param homekitTiltAngle the tilt angle as reported by homekit
* @returns [device position, device direction]
*/
mapHomekitValuesToDeviceValues(homekitPosition: number, homekitTiltAngle: number): [string, number] {
// homekit position 0 => closed
// homekit position 100 => open
// device position [up, 0] = closed upwards
// device position [down, 0] = closed downwards
// device position [up, 100] = open
// device position [down, 100] = open
switch (this.mappingMode) {
case BlindTiltMappingMode.OnlyUp:
// invert
return ['up', homekitPosition]
case BlindTiltMappingMode.OnlyDown:
// invert
return ['down', homekitPosition]
case BlindTiltMappingMode.DownAndUp:
// homekit 0 = downwards closed,
// homekit 50 = open,
// homekit 100 = upwards closed
if (homekitPosition <= 50) {
// homekit 0..50 -> device 100..0 so scale and invert
return ['down', 100 - homekitPosition * 2]
} else {
// homekit 50..100 -> device 0..100, so rebase, scale and invert
return ['up', (homekitPosition - 50) * 2]
}
case BlindTiltMappingMode.UpAndDown:
// homekit 0 = upwards closed,
// homekit 50 = open,
// homekit 100 = upwards closed
if (homekitPosition <= 50) {
// homekit 0..50 -> device 0..100 so scale and invert
return ['up', homekitPosition * 2]
} else {
// homekit 50..100 -> device 100...0 so scale
return ['down', 100 - homekitPosition * 2]
}
case BlindTiltMappingMode.UseTiltForDirection:
// tilt -90, homekit 0 = closed downwards
// tilt -90, homekit 100 = open
// tilt 90, homekit 0 = closed upwards
// tilt 90, homekit 100 = open
if (homekitTiltAngle! <= 0) {
// downwards
// homekit 0..100 -> device 0..100, so invert
return ['down', homekitPosition]
} else {
// upwards
// homekit 0..100 -> device 0..100, so invert
return ['up', homekitPosition]
}
}
}
}
|