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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 25x 1x 13x 13x 1x 14x 26x 2x 2x 2x 12x 14x 1x 24x 12x 12x 12x 12x 3x 9x 9x 12x 14x 12x 12x 12x 10x 10x 12x 12x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 1x 2x 2x 2x 2x 2x 6x 6x 6x 2x 1x 5x 1x 3x 9x 9x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 2x 1x 1x 1x 4x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x | /** * smartFritz - Fritz goes smartHome * * AVM SmartHome nodeJS Control - for AVM Fritz!Box and Dect200 Devices * * @author Andreas Goetz <cpuidle@gmx.de> * * Forked from: https://github.com/nischelwitzer/smartfritz * nischi - first version: July 2014 * * based on: Node2Fritz by steffen.timm on 05.12.13 for Fritz!OS > 05.50 * and thk4711 (code https://github.com/pimatic/pimatic/issues/38) * * AVM Documentation is at https://avm.de/service/schnittstellen/ */ /* * Object-oriented API */ import axios from 'axios'; import crypto from 'crypto'; import parser from 'xml2json'; import * as qs from 'qs'; import { api2temp, AVMDevice, color2apihue, ColorName, colortemp2api, defaultUrl, FUNCTION_BUTTON, FUNCTION_COLORCONTROL, FUNCTION_LIGHT, FUNCTION_THERMOSTAT, IBase, IExt, IState, ITemp, level2api, OSInfo, ReqOption, satindex2apisat, state2api, temp2api, time2api, } from './utils'; export default class Fritz { protected sid: string | null; protected username: string; protected password: string; protected url = defaultUrl; protected deviceList: AVMDevice[] | null; /** * Default constructor * @param username * @param password * @param url if not set default is 'http://fritz.box' */ constructor(username: string, password: string, url?: string) { this.sid = null; this.username = username; this.password = password; this.deviceList = null; if (url) { this.url = url; } } /** * get SID */ async getSID(): Promise<string> { if (this.sid === null) { this.sid = await this.getSessionID(this.username, this.password); } Iif (this.sid === null) { throw new Error('Bad SID'); } return this.sid; } /** * Request helper * @param request * @param options * @private */ private static async httpRequest<T>( request: string, options?: ReqOption, ): Promise<T> { try { let res; if (options?.method === 'POST') { if (Ioptions.form) { const form = qs.stringify(options.form); res = await axios.post<any>(request, form, { headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, }); } else { throw new Error('no form data'); } } else { res = await axios.get<any>(request); } return res.data; } catch (e) { console.error(e); throw new Error('httpRequest Failed'); } } /** * Execute Fritz API command for device specified by AIN */ async executeCommand<T>( sid: boolean, command: string | null, ain: string | null, path?: string, ...param: string[] ) { const ePath = []; const eParam = []; ePath.push(this.url); if (path) { ePath.push(path); } else { ePath.push('/webservices/homeautoswitch.lua'); eParam.push('0=0'); } param.forEach((el) => { eParam.push(el); }); if (sid) eParam.push(`sid=${await this.getSID()}`); if (command) eParam.push(`switchcmd=${command}`); if (ain) eParam.push(`ain=${ain}`); if (eParam.length > 0) { ePath.push('?'); ePath.push(eParam.join('&')); } console.log(ePath.join('')); return Fritz.httpRequest<T>(ePath.join('')); } /** * get session id * @param username * @param password * @private */ private async getSessionID( username: string, password: string, ): Promise<string> { let body = await this.executeCommand<any>( false, null, null, '/login_sid.lua', ); const challenge = body.match('<Challenge>(.*?)</Challenge>')[1]; const challengeResponse = `${challenge}-${crypto .createHash('md5') .update(Buffer.from(`${challenge}-${password}`, 'utf16le')) .digest('hex')}`; const url = `/login_sid.lua?username=${username}&response=${challengeResponse}`; body = await this.executeCommand(false, null, null, url); const sessionID = body.match('<SID>(.*?)</SID>')[1]; return sessionID; } /** * check if session id is OK */ async checkSession(): Promise<boolean> { const body = await this.executeCommand<string>( true, null, null, '/login_sid.lua', ); const sessionID = body.match('<SID>(.*?)</SID>'); return !!sessionID && sessionID[1] !== '0000000000000000'; } /** * get OS version */ async getOSVersion() { const req: ReqOption = { method: 'POST', form: { sid: await this.getSID(), xhr: 1, page: 'overview', }, }; const json = await Fritz.httpRequest<OSInfo>(`${this.url}/data.lua`, req); const osVersion = json.data && json.data.fritzos && json.data.fritzos.nspver ? json.data.fritzos.nspver : null; return osVersion; } /** * get full FritzBox config */ async getDataSheet(): Promise<OSInfo> { const req: ReqOption = { method: 'POST', form: { sid: await this.getSID(), xhr: 1, page: 'overview', }, }; return Fritz.httpRequest<OSInfo>(`${this.url}/data.lua`, req); } /** * get template information (XML) */ async getTemplateListInfos(): Promise<string> { return this.executeCommand<string>(true, 'gettemplatelistinfos', null); } /** * get template information (json) */ getTemplateList: IBase<any[]> = async () => { const templateinfo = await this.getTemplateListInfos(); const templates = JSON.parse(parser.toJson(templateinfo)); // extract templates as array let out: any[] = []; out = out.concat((templates.templatelist || {}).template || []); out = out.map((template) => { return template; }); return out; }; /** * apply template * @param ain */ async applyTemplate(ain: string) { return this.executeCommand(true, 'applytemplate', ain); } /** * get basic device info (XML) * @param ain */ async getBasicDeviceStats(ain: string) { return this.executeCommand(true, 'getbasicdevicestats', ain); } /** * get detailed device information (XML) */ async getDeviceListInfos() { return this.executeCommand<string>(true, 'getdevicelistinfos', null); } /** * get device list */ async getDeviceList(): Promise<AVMDevice[]> { const devicelistinfo = await this.getDeviceListInfos(); const devicesCore = JSON.parse(parser.toJson(devicelistinfo)); // extract devices as array let devices: AVMDevice[] = []; devices = devices.concat((devicesCore.devicelist || {}).device || []); devices = devices.map((dev: any) => { const newElement = dev; newElement.identifier = newElement.identifier.replace(/\s/g, ''); return newElement; }); return devices; } /** * get device list by filter criteria * @param filter */ async getDeviceListFiltered(filter: any): Promise<AVMDevice[]> { if (!this.deviceList) { this.deviceList = await this.getDeviceList(); } return this.deviceList.filter((device: any) => { return Object.keys(filter).every(function (key) { /* jshint laxbreak:true */ return key === 'functionbitmask' ? device.functionbitmask & filter[key] : device[key] === filter[key]; }); }); } /** * get single device * @param ain */ async getDevice(ain: string): Promise<AVMDevice | null> { const devices = await this.getDeviceListFiltered({ identifier: ain, }); return devices.length ? devices[0] : null; } /** * get temperature- both switches and thermostats are supported, but not powerline modules * @param ain */ async getTemperature(ain: string): Promise<number> { const body = await this.executeCommand<string>(true, 'gettemperature', ain); return parseFloat(body) / 10; // °C } /** * get presence from deviceListInfo * @param ain */ async getPresence(ain: string): Promise<boolean> { return !!(await this.getDevice(ain))?.presence; } /* * Switches */ /** * get switch list */ async getSwitchList(): Promise<any[]> { let res = await this.executeCommand<string>(true, 'getswitchlist', null); res = res.replace('\n', ''); return res === '' ? [] : res.split(','); } /** * get switch state * @param ain */ getSwitchState: IExt<boolean> = async (ain) => { const body = await this.executeCommand<string>(true, 'getswitchstate', ain); return /^1/.test(body); // true if on }; /** * turn an outlet on. returns the state the outlet was set to * @param ain */ setSwitchOn: IExt<boolean> = async (ain) => { const body = await this.executeCommand<string>(true, 'setswitchon', ain); return /^1/.test(body); // true if on }; /** * turn an outlet off. returns the state the outlet was set to * @param ain */ setSwitchOff: IExt<boolean> = async (ain) => { const body = await this.executeCommand<string>(true, 'setswitchoff', ain); return /^1/.test(body); // false if off }; /** * toggle an outlet. returns the state the outlet was set to * @param ain */ setSwitchToggle: IExt<boolean> = async (ain) => { const body = await this.executeCommand<string>( true, 'setswitchtoggle', ain, ); return /^1/.test(body); // false if off }; /** * get the total enery consumption. returns the value in Wh * @param ain */ getSwitchEnergy: IExt<number> = async (ain) => { const body = await this.executeCommand<string>( true, 'getswitchenergy', ain, ); return parseFloat(body); // Wh }; /** * get the current enery consumption of an outlet. returns the value in mW * @param ain */ getSwitchPower: IExt<number | null> = async (ain) => { const body = await this.executeCommand<string>(true, 'getswitchpower', ain); const power = parseFloat(body); return Number.isNaN(power) ? null : power / 1000; // W }; /** * get the outet presence status * @param ain */ getSwitchPresence: IExt<boolean> = async (ain) => { const body = await this.executeCommand<string>( true, 'getswitchpresent', ain, ); return /^1/.test(body); // true if present }; /** * get switch name * @param ain */ getSwitchName: IExt<string> = async (ain) => { const body = await this.executeCommand<string>(true, 'getswitchname', ain); return body.trim(); }; /* * Thermostats */ /** * get the thermostat list */ getThermostatList: IBase<any> = async () => { const devices = await this.getDeviceListFiltered({ functionbitmask: FUNCTION_THERMOSTAT, }); return devices.map((device) => { return device.identifier; }); }; /** * set target temperature (Solltemperatur) * @param ain * @param temp */ async setTempTarget(ain: string, temp: number): Promise<number> { await this.executeCommand(true, `sethkrtsoll¶m=${temp2api(temp)}`, ain); return temp; } /** * get target temperature (Solltemperatur) * @param ain */ getTempTarget: IExt<ITemp> = async (ain) => { const body = await this.executeCommand<string>(true, 'gethkrtsoll', ain); return api2temp(body); }; /** * get night temperature (Absenktemperatur) * @param ain */ getTempNight: IExt<ITemp> = async (ain) => { const body = await this.executeCommand<string>(true, 'gethkrabsenk', ain); return api2temp(body); }; /** * get comfort temperature (Komforttemperatur) * @param ain */ getTempComfort: IExt<ITemp> = async (ain) => { const body = await this.executeCommand<string>(true, 'gethkrkomfort', ain); return api2temp(body); }; /** * ------------------------------------------------ */ /** * Not yet tested - deactivated for now */ // /** * activate boost with end time or deactivate boost * @param ain * @param endtime */ async setHkrBoost(ain: string, endtime: number) { await this.executeCommand( true, `sethkrboost&endtimestamp=${time2api(endtime)}`, ain, ); return endtime; } /** * activate window open with end time or deactivate boost * @param ain * @param endtime */ async setHkrWindowOpen(ain: string, endtime: number) { await this.executeCommand( true, `sethkrwindowopen&endtimestamp=${time2api(endtime)}`, ain, ); } /** * activate window open with end time or deactivate boost * @param deviceId * @param offset */ async setHkrOffset(deviceId: string, offset: number) { const path = '/net/home_auto_hkr_edit.lua'; const req: ReqOption = { method: 'POST', form: { sid: await this.getSID(), xhr: 1, lang: 'de', no_sidrenew: '', ule_device_name: '', useajax: 1, WindowOpenTimer: '', WindowOpenTrigger: '', tempsensor: '', Roomtemp: '', ExtTempsensorID: '', Offset: offset, back_to_page: 'sh_dev', view: '', graphState: 1, apply: '', device: deviceId, oldpage: '/net/home_auto_hkr_edit.lua', }, }; await Fritz.httpRequest(path, req); return offset; } /** * ------------------------------------------------ */ /* * AVM Buttons Fritz!DECT 400 and Fritz!DECT 440 * Querying a button isn't really useful because they don't have a state to query, * there is just a timestamp of the last short and long button press. * The only useful information is the battery status returned in the 'battery' and * 'batterylow' property. * The Fritz!DECT 440 should have an additional 'temperature' property */ /** * get a list of all button devices */ getButtonList: IBase<string[]> = async () => { const devices = await this.getDeviceListFiltered({ functionbitmask: FUNCTION_BUTTON, }); return devices.map((device) => { return device.identifier; }); }; /* * Light bulbs (HAN-FUN) */ /** * get a list of all bulbs */ getBulbList: IBase<string[]> = async () => { const devices = await this.getDeviceListFiltered({ functionbitmask: FUNCTION_LIGHT, }); return devices.map((device) => { return device.identifier; }); }; /** * get a list of bulbs which support colors */ getColorBulbList: IBase<string[]> = async () => { const devices = await this.getDeviceListFiltered({ functionbitmask: FUNCTION_LIGHT || FUNCTION_COLORCONTROL, }); return devices.map((device) => { return device.identifier; }); }; /** * switch the device on, of or toggle its current state * @param ain * @param state */ async setSimpleOnOff(ain: string, state: IState) { /** * ain = ain.replace('-1',''); */ await this.executeCommand( true, `setsimpleonoff&onoff=${state2api(state)}`, ain, ); return state; } /** * Dimm the device, allowed values are 0 - 255 * @param ain * @param level */ async setLevel(ain: string, level: number) { await this.executeCommand( true, `setlevel&level=${level2api(level, false)}`, ain, ); return level; } /** * Dimm the device, allowed values are 0 - 100 * @param ain * @param levelInPercent */ async setLevelPercentage(ain: string, levelInPercent: number) { return this.executeCommand( true, `setlevelpercentage&level=${level2api(levelInPercent, true)}`, ain, ).then(function (body) { /** * api does not return a value */ return levelInPercent; }); } /** * Set the color and saturation of a color bulb * Valid color values are: * red, orange, yellow, lime, green, turquoise, cyan, * lightblue, blue, purple, magenta and pink * Valid satindex values are: 0, 1 or 2 * @param ain * @param color * @param satindex * @param duration */ async setColor( ain: string, color: ColorName, satindex: number, duration: number, ) { await this.executeCommand( true, `setcolor&hue=${color2apihue(color)}&saturation=${satindex2apisat( color, satindex, )}&duration=${duration}`, ain, ); return color; } /** * Set the color temperature of a bulb. * @param ain * @param temperature Valid values are 2700, 3000, 3400,3800, 4200, 4700, 5300, 5900 and 6500. * @param duration */ async setColorTemperature( ain: string, temperature: number, duration: number, ) { const temp = colortemp2api(temperature); await this.executeCommand( true, `setcolortemperature&temperature=${temp}&duration=${duration}`, ain, ); return temp; } // get the color defaults // This is mostly useless because they are no defaults which can be changed but // fixed values. Only combinations returned by this api call are accepted by // setcolor and setcolortemperature. // module.exports.getColorDefaults = function(sid, ain, options) // { // return executeCommand(true, 'getcolordefaults', ain, options).then(function(body) { // return body; // }); // }; // ------------------------------------------------ // Not yet tested - deactivated for now // I don't know about any blind control unit with HANFUN support, but this API call makes // it plausible that AVM or a partner has somthing like that in the pipeline. // async setBlind(ain: string, blindState: string | number) { // „open“, „close“ or „stop“ await this.executeCommand(true, `setblind&target=${blindState}`, ain); return blindState; } /** * get battery charge * Attention: this function queries the whole device list to get the value for one device. * If multiple device will be queried for the battery status, a better approach would be to * get the device list once and then filter out the devices of interest. * @param ain */ getBatteryCharge: IExt<unknown | null> = async (ain) => { const device = await this.getDevice(ain); return device?.battery; }; /** * Get the window open flag of a thermostat * Attention: this function queries the whole device list to get the value for one device. * If multiple device will be queried for the window open status, a better approach would * be to get the device list once and then filter out the devices of interest. * @param ain */ getWindowOpen: IExt<boolean> = async (ain) => { const device = await this.getDevice(ain); return device?.hkr?.windowopenactiv === '1'; }; /* * WLAN */ // Parse guest WLAN form settings parseGuestWlanHTML(html: string) { throw new Error('Not Implemented'); /* $ = cheerio.load(html); const form = $('form'); const settings = {}; $('input', form).each(function (i, elem) { let val; const name = $(elem).attr('name'); if (!name) return; switch ($(elem).attr('type')) { case 'checkbox': val = $(elem).attr('checked') == 'checked'; break; default: val = $(elem).val(); } settings[name] = val; }); $('select option[selected=selected]', form).each(function (i, elem) { const val = $(elem).val(); const name = $(elem).parent().attr('name'); settings[name] = val; }); return settings; */ } // get guest WLAN settings - not part of Fritz API async getGuestWlan(): Promise<any> { const body = await this.executeCommand<string>( true, null, null, '/wlan/guest_access.lua?0=0', ); return this.parseGuestWlanHTML(body); } // set guest WLAN settings - not part of Fritz API async setGuestWlan(enable: boolean) { throw new Error('Not Implemented'); /* /!* jshint laxbreak:true *!/ const settings = enable || executeCommand( sid, undefined, undefined, options, '/wlan/guest_access.lua?0=0' ).then(function (body) { return extend(parseGuestWlanHTML(body), { activate_guest_access: enable, }); }); return settings.then(function (settings) { // convert boolean to checkbox for (const property in settings) { if (settings[property] === true) settings[property] = 'on'; else if (settings[property] === false) delete settings[property]; } const req = { method: 'POST', form: extend(settings, { sid, xhr: 1, no_sidrenew: '', apply: '', oldpage: '/wlan/guest_access.lua', }), }; return httpRequest('/data.lua', req, options).then(function (body) { return parseGuestWlanHTML(body); }); }); */ } /** * get phone devices */ async getPhoneList() { return this.executeCommand( true, null, null, '/fon_num/foncalls_list.lua?csv=', ); } } |