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 | 1x | /* Copyright(C) 2021-2024, donavanbecker (https://github.com/donavanbecker). All rights reserved.
*
* irdevice.ts: @switchbot/homebridge-switchbot.
*/
import type { API, CharacteristicValue, HAP, Logging, PlatformAccessory, Service } from 'homebridge'
import type { bodyChange, irdevice } from 'node-switchbot'
import type { SwitchBotPlatform } from '../platform.js'
import type { irAirConfig, irDevicesConfig, irFanConfig, irLightConfig, irOtherConfig, SwitchBotPlatformConfig } from '../settings.js'
export abstract class irdeviceBase {
public readonly api: API
public readonly log: Logging
public readonly config!: SwitchBotPlatformConfig
protected readonly hap: HAP
// Config
protected deviceLogging!: string
protected deviceRefreshRate!: number
protected deviceUpdateRate!: number
protected devicePushRate!: number
protected deviceMaxRetries!: number
protected deviceDelayBetweenRetries!: number
protected deviceDisablePushOn!: boolean
protected deviceDisablePushOff!: boolean
protected deviceDisablePushDetail?: boolean
constructor(
protected readonly platform: SwitchBotPlatform,
protected accessory: PlatformAccessory,
protected device: irdevice & irDevicesConfig,
) {
this.api = this.platform.api
this.log = this.platform.log
this.config = this.platform.config
this.hap = this.api.hap
this.getDeviceLogSettings(accessory, device)
this.getDeviceRateSettings(device)
this.getDeviceConfigSettings(device)
this.getDeviceContext(accessory, device)
// Set accessory information
accessory
.getService(this.hap.Service.AccessoryInformation)!
.setCharacteristic(this.hap.Characteristic.Manufacturer, 'SwitchBot')
.setCharacteristic(this.hap.Characteristic.AppMatchingIdentifier, 'id1087374760')
.setCharacteristic(this.hap.Characteristic.Name, accessory.displayName)
.setCharacteristic(this.hap.Characteristic.ConfiguredName, accessory.displayName)
.setCharacteristic(this.hap.Characteristic.Model, accessory.context.model ?? 'Unknown')
.setCharacteristic(this.hap.Characteristic.ProductData, device.deviceId)
.setCharacteristic(this.hap.Characteristic.SerialNumber, device.deviceId)
}
async getDeviceLogSettings(accessory: PlatformAccessory, device: irdevice & irDevicesConfig): Promise<void> {
this.deviceLogging = this.platform.debugMode ? 'debugMode' : device.logging ?? this.platform.platformLogging ?? 'standard'
const logging = this.platform.debugMode ? 'Debug Mode' : device.logging ? 'Device Config' : this.platform.platformLogging ? 'Platform Config' : 'Default'
accessory.context.deviceLogging = this.deviceLogging
this.debugLog(`Using ${logging} Logging: ${this.deviceLogging}`)
}
async getDeviceRateSettings(device: irdevice & irDevicesConfig): Promise<void> {
// refreshRate
this.deviceRefreshRate = device.refreshRate ?? this.platform.platformRefreshRate ?? 300
const refreshRate = device.refreshRate ? 'Device Config' : this.platform.platformRefreshRate ? 'Platform Config' : 'Default'
this.accessory.context.refreshRate = this.deviceRefreshRate
// updateRate
this.deviceUpdateRate = device.updateRate ?? this.platform.platformUpdateRate ?? 5
const updateRate = device.updateRate ? 'Device Config' : this.platform.platformUpdateRate ? 'Platform Config' : 'Default'
this.accessory.context.updateRate = this.deviceUpdateRate
// pushRate
this.devicePushRate = device.pushRate ?? this.platform.platformPushRate ?? 0.1
const pushRate = device.pushRate ? 'Device Config' : this.platform.platformPushRate ? 'Platform Config' : 'Default'
this.accessory.context.pushRate = this.devicePushRate
this.debugLog(`Using ${refreshRate} refreshRate: ${this.deviceRefreshRate}, ${updateRate} updateRate: ${this.deviceUpdateRate}, ${pushRate} pushRate: ${this.devicePushRate}`)
// maxRetries
this.deviceMaxRetries = device.maxRetries ?? this.platform.platformMaxRetries ?? 2
const maxRetries = device.maxRetries ? 'Device' : this.platform.platformMaxRetries ? 'Platform' : 'Default'
this.debugLog(`Using ${maxRetries} Max Retries: ${this.deviceMaxRetries}`)
// delayBetweenRetries
this.deviceDelayBetweenRetries = device.delayBetweenRetries ? (device.delayBetweenRetries * 1000) : this.platform.platformDelayBetweenRetries ?? 3000
const delayBetweenRetries = device.delayBetweenRetries ? 'Device' : this.platform.platformDelayBetweenRetries ? 'Platform' : 'Default'
this.debugLog(`Using ${delayBetweenRetries} Delay Between Retries: ${this.deviceDelayBetweenRetries}`)
// disablePushOn
this.deviceDisablePushOn = device.disablePushOn ?? false
const disablePushOn = device.disablePushOn ? 'Device Config' : 'Default'
// disablePushOff
this.deviceDisablePushOff = device.disablePushOff ?? false
const disablePushOff = device.disablePushOff ? 'Device Config' : 'Default'
// disablePushDetail
this.deviceDisablePushDetail = device.disablePushDetail ?? false
const disablePushDetail = device.disablePushDetail ? 'Device Config' : 'Default'
this.debugLog(`Using ${disablePushOn} Disable Push On: ${this.deviceDisablePushOn}, ${disablePushOff} Disable Push Off: ${this.deviceDisablePushOff}, ${disablePushDetail} Disable Push Detail: ${this.deviceDisablePushDetail}`)
}
async getDeviceConfigSettings(device: irdevice & irDevicesConfig): Promise<void> {
const deviceConfig = Object.assign(
{},
device.logging !== 'standard' && { logging: device.logging },
device.connectionType !== '' && { connectionType: device.connectionType },
device.external === true && { external: device.external },
device.customize === true && { customize: device.customize },
device.commandType !== '' && { commandType: device.commandType },
device.customOn !== '' && { customOn: device.customOn },
device.customOff !== '' && { customOff: device.customOff },
device.disablePushOn === true && { disablePushOn: device.disablePushOn },
device.disablePushOff === true && { disablePushOff: device.disablePushOff },
device.disablePushDetail === true && { disablePushDetail: device.disablePushDetail },
)
let deviceSpecificConfig = {}
switch (device.configRemoteType) {
case 'Fan':
case 'DIY Fan':
deviceSpecificConfig = device as irFanConfig
break
case 'Light':
case 'DIY Light':
deviceSpecificConfig = device as irLightConfig
break
case 'Air Conditioner':
case 'DIY Air Conditioner':
deviceSpecificConfig = device as irAirConfig
break
case 'Others':
deviceSpecificConfig = device as irOtherConfig
break
default:
break
}
const config = Object.assign(
{},
deviceConfig,
deviceSpecificConfig,
)
if (Object.keys(config).length !== 0) {
this.debugSuccessLog(`Config: ${JSON.stringify(config)}`)
}
}
async getDeviceContext(accessory: PlatformAccessory, device: irdevice & irDevicesConfig): Promise<void> {
accessory.context.name = device.deviceName
accessory.context.model = device.remoteType
accessory.context.deviceId = device.deviceId
accessory.context.remoteType = device.remoteType
const deviceFirmwareVersion = device.firmware ?? accessory.context.version ?? this.platform.version ?? '0.0.0'
const version = deviceFirmwareVersion.toString()
this.debugLog(`version: ${version?.replace(/^V|-.*$/g, '')}`)
let deviceVersion: string
if (version?.includes('.') === false) {
const replace = version?.replace(/^V|-.*$/g, '')
const match = replace?.match(/./g)
const validVersion = match?.join('.')
deviceVersion = validVersion ?? '0.0.0'
} else {
deviceVersion = version.replace(/^V|-.*$/g, '') ?? '0.0.0'
}
accessory
.getService(this.hap.Service.AccessoryInformation)!
.setCharacteristic(this.hap.Characteristic.HardwareRevision, deviceVersion)
.setCharacteristic(this.hap.Characteristic.SoftwareRevision, deviceVersion)
.setCharacteristic(this.hap.Characteristic.FirmwareRevision, deviceVersion)
.getCharacteristic(this.hap.Characteristic.FirmwareRevision)
.updateValue(deviceVersion)
accessory.context.version = deviceVersion
this.debugSuccessLog(`version: ${accessory.context.version}`)
}
async pushChangeRequest(bodyChange: bodyChange): Promise<{ body: any, statusCode: number }> {
const { response, statusCode } = await this.platform.retryCommand(this.device, bodyChange, this.deviceMaxRetries, this.deviceDelayBetweenRetries)
return { body: response, statusCode }
}
async successfulStatusCodes(deviceStatus: any) {
return (deviceStatus.statusCode === 200 || deviceStatus.statusCode === 100)
}
/**
* Update the characteristic value and log the change.
*
* @param Service Service
* @param Characteristic Characteristic
* @param CharacteristicValue CharacteristicValue | undefined
* @param CharacteristicName string
* @return: void
*
*/
async updateCharacteristic(Service: Service, Characteristic: any, CharacteristicValue: CharacteristicValue | undefined, CharacteristicName: string): Promise<void> {
if (CharacteristicValue === undefined) {
this.debugLog(`${CharacteristicName}: ${CharacteristicValue}`)
} else {
Service.updateCharacteristic(Characteristic, CharacteristicValue)
this.debugLog(`updateCharacteristic ${CharacteristicName}: ${CharacteristicValue}`)
this.debugWarnLog(`${CharacteristicName} context before: ${this.accessory.context[CharacteristicName]}`)
this.accessory.context[CharacteristicName] = CharacteristicValue
this.debugWarnLog(`${CharacteristicName} context after: ${this.accessory.context[CharacteristicName]}`)
}
}
async pushStatusCodes(deviceStatus: any) {
this.debugWarnLog(`deviceStatus: ${JSON.stringify(deviceStatus)}`)
this.debugWarnLog(`deviceStatus statusCode: ${deviceStatus.statusCode}`)
}
async successfulPushChange(deviceStatus: any, bodyChange: any) {
this.debugSuccessLog(`deviceStatus StatusCode: ${deviceStatus.statusCode}`)
this.successLog(`request to SwitchBot API, body: ${JSON.stringify(bodyChange)} sent successfully`)
}
async pushChangeError(e: Error) {
this.errorLog(`failed pushChanges with ${this.device.connectionType} Connection, Error Message: ${JSON.stringify(e.message)}`)
}
async commandType(): Promise<string> {
let commandType: string
if (this.device.commandType && this.device.customize) {
commandType = this.device.commandType
} else if (this.device.customize) {
commandType = 'customize'
} else {
commandType = 'command'
}
return commandType
}
async commandOn(): Promise<string> {
let command: string
if (this.device.customize && this.device.customOn) {
command = this.device.customOn
} else {
command = 'turnOn'
}
return command
}
async commandOff(): Promise<string> {
let command: string
if (this.device.customize && this.device.customOff) {
command = this.device.customOff
} else {
command = 'turnOff'
}
return command
}
async statusCode(statusCode: number): Promise<void> {
const statusMessages = {
151: 'Command not supported by this deviceType',
152: 'Device not found',
160: 'Command is not supported',
161: 'Device is offline',
171: `Hub Device is offline. Hub: ${this.device.hubDeviceId}`,
190: 'Device internal error due to device states not synchronized with server, or command format is invalid',
100: 'Command successfully sent',
200: 'Request successful',
400: 'Bad Request, an invalid payload request',
401: 'Unauthorized, Authorization for the API is required, but the request has not been authenticated',
403: 'Forbidden, The request has been authenticated but does not have appropriate permissions, or a requested resource is not found',
404: 'Not Found, Specifies the requested path does not exist',
406: 'Not Acceptable, a MIME type has been requested via the Accept header for a value not supported by the server',
415: 'Unsupported Media Type, a contentType header has been defined that is not supported by the server',
422: 'Unprocessable Entity: The server cannot process the request, often due to exceeded API limits.',
429: 'Too Many Requests, exceeded the number of requests allowed for a given time window',
500: 'Internal Server Error, An unexpected error occurred. These errors should be rare',
}
if (statusCode === 171 && (this.device.hubDeviceId === this.device.deviceId || this.device.hubDeviceId === '000000000000')) {
this.debugErrorLog(`statusCode 171 changed to 161: hubDeviceId ${this.device.hubDeviceId} matches deviceId ${this.device.deviceId}, device is its own hub.`)
statusCode = 161
}
const logMessage = statusMessages[statusCode] || `Unknown statusCode: ${statusCode}, Submit Bugs Here: https://tinyurl.com/SwitchBotBug`
const logMethod = [100, 200].includes(statusCode) ? 'debugLog' : statusMessages[statusCode] ? 'errorLog' : 'infoLog'
this[logMethod](`${logMessage}, statusCode: ${statusCode}`)
}
/**
* Logging for Device
*/
async infoLog(...log: any[]): Promise<void> {
if (await this.enablingDeviceLogging()) {
this.log.info(`${this.device.remoteType}: ${this.accessory.displayName}`, String(...log))
}
}
async successLog(...log: any[]): Promise<void> {
if (await this.enablingDeviceLogging()) {
this.log.success(`${this.device.remoteType}: ${this.accessory.displayName}`, String(...log))
}
}
async debugSuccessLog(...log: any[]): Promise<void> {
if (await this.enablingDeviceLogging()) {
if (await this.loggingIsDebug()) {
this.log.success(`[DEBUG] ${this.device.remoteType}: ${this.accessory.displayName}`, String(...log))
}
}
}
async warnLog(...log: any[]): Promise<void> {
if (await this.enablingDeviceLogging()) {
this.log.warn(`${this.device.remoteType}: ${this.accessory.displayName}`, String(...log))
}
}
async debugWarnLog(...log: any[]): Promise<void> {
if (await this.enablingDeviceLogging()) {
if (await this.loggingIsDebug()) {
this.log.warn(`[DEBUG] ${this.device.remoteType}: ${this.accessory.displayName}`, String(...log))
}
}
}
async errorLog(...log: any[]): Promise<void> {
if (await this.enablingDeviceLogging()) {
this.log.error(`${this.device.remoteType}: ${this.accessory.displayName}`, String(...log))
}
}
async debugErrorLog(...log: any[]): Promise<void> {
if (await this.enablingDeviceLogging()) {
if (await this.loggingIsDebug()) {
this.log.error(`[DEBUG] ${this.device.remoteType}: ${this.accessory.displayName}`, String(...log))
}
}
}
async debugLog(...log: any[]): Promise<void> {
if (await this.enablingDeviceLogging()) {
if (this.deviceLogging === 'debug') {
this.log.info(`[DEBUG] ${this.device.remoteType}: ${this.accessory.displayName}`, String(...log))
} else if (this.deviceLogging === 'debugMode') {
this.log.debug(`${this.device.remoteType}: ${this.accessory.displayName}`, String(...log))
}
}
}
async loggingIsDebug(): Promise<boolean> {
return this.deviceLogging === 'debugMode' || this.deviceLogging === 'debug'
}
async enablingDeviceLogging(): Promise<boolean> {
return this.deviceLogging === 'debugMode' || this.deviceLogging === 'debug' || this.deviceLogging === 'standard'
}
}
|