[
  {
    "path": ".gitignore",
    "content": "/dummycloud/node_modules/\n"
  },
  {
    "path": "Readme.md",
    "content": "# Deye Microinverter - Cloud-free\n\n![Deye microinverter in the sun](img/banner.jpg)\n\nSolar power generation work best if there are no clouds anywhere to be seen :)\n<br/><br/>\n\nThis repository aims to document how to use Deye microinverters entirely local only and cloud free.\nIt consolidates the knowledge that at the time of writing was spread over hundreds of different posts, issues and comments.\n\nFurthermore, it also features a cloud replacement implementation so you won't have to install any apps or create any accounts.\nYou also won't have to share any e-mail address or phone number.\n\n## Devices\n\nSo far, the following devices are known to work like this:\n\n- Deye SUN600G3-EU-230\n- Deye SUN-M80G3-EU-Q0\n- Deye SUN-M80G4-EU-Q0\n\nit should also be the same for other inverters of the same series including rebrands such as Bosswerk.<br/>\nIf you have verified that it works with another device, feel free to extend this list.\n\n## TL;DR\n\nHere are the main things you will want to know about these microinverters:\n\n- They have Wi-Fi\n- They can be connected to Wi-Fi networks via their webinterface\n- They can operate without an internet connection\n- They can operate without an account\n- They can be monitored and controlled via their local ModbusTCP interface\n- You can also completely replace the cloud with a local implementation: [dummycloud](./dummycloud)\n\n**2024-08-20 Update**\n\nDeye has started rolling out firmware updates for the logger that block both ModbusTCP access and prevent the mock cloud\nfrom working due to the introduction of TLS. Fortunately, for now it seems that newly bought inverters still come with older\nlogger firmwares that work offline.\nAlso equally fortunately, it seems that downgrading the firmware is possible as well.\n\nHowever, both of these things may change in the future.\n\n## Preamble\n\nCompared to traditional PV setups where a single large inverter is connected to strings of many PV Panels, in a microinverter Setup, you have one small inverter for every 1-4 PV Panels.\n\nThere are up- and downsides to both of these topologies but that is for now out of scope for this document.\nWhat you need to know is that microinverters are cheaper and scaled-down versions of their larger brothers.\n\nBecause they only cost 150-200€ they make getting into solar power generation accessible for many more people than ever before.\nPaired with two PV Panels you're looking at an investment of at most 1000€ to get free energy from the sun.\n\nAdditionally, because you only need few panels for the setup to make sense financially, often a balcony or garden can be enough for a small solar setup.\nThis is especially interesting for people living in rental properties.\n\n### Word of warning\n\nAfter reading through way too many concerning posts and comments, here's what has to be said:\n\n**Please** please please don't cut any corners when it comes to safety-critical stuff such as cabling and also mounting panels.\nYou don't want your home to burn down or anyone to be killed by a falling 1.5m² 25kg PV Panel.\n\nElectricity is dangerous. So are heavy things with a huge attack surface for wind.<br/>\nWhen in doubt, contact a local electrician. They know what they're doing and will help you.\n\n## Setup\n\nNow with that out of the way, we can talk about what to do.\n\nThe first important thing to note is that these inverters will shut down if they don't sense at least 20V on at least one PV input.\nThis means that you have to do all this during the day connected while connected to a PV panel.\n\nAlternatively, some people reported that they got the inverter to wake up by connecting a 30V lab power supply to one of the PV inputs.\n\n### Joining Wi-Fi\n\nBy default, your microinverter should provide a Wi-Fi Access point with an SSID named similarly to `AP_4151234567`.\nUsing a laptop, connect to that using the password printed on the AP or for older inverters the default password `12345678`.\n\nIn a browser, navigate to the IP of the inverter in that network which should by default be `http://10.10.100.254/`.\nLog in to the webinterface with the default credentials `admin:admin` and use that to configure Wi-Fi.\n\n![wifi configuration](img/wifi_config.png)\n\nThe AP-mode can be a bit unstable so prepare for the webinterface stopping to work occasionally.\nOnce the inverter is connected to you Wi-Fi, this should not be an issue anymore.\n\n\n### Ensuring a patched logger firmware\n\nAfter joining the inverter to you Wi-Fi network, connect to the webinterface again but this time using the IP in your network.\n\nNow, expand the `Device Information` on the `Status` page and ensure that your logger firmware version is at least `MW3_16U_5406_1.53` or newer.\n\n![firmware version](img/firmware_version.png)\n\nOlder firmwares don't allow reconfiguration of the Wi-Fi AP, which is a serious vulnerability, as it allows an attacker to easily gain access to your real Wi-Fi credentials.\n\nIf your firmware is older, you can find firmware update files in this repo: [https://github.com/dasrecht/deye-firmware](https://github.com/dasrecht/deye-firmware).\nYou can flash them using the `Upgrade Firmware` page of the webinterface.\n\n\n### Securing the AP\n\nWith the logger firmware upgraded, you should now use the webinterface to change SSID and Password for the AP of the inverter.\n\n![ap config](img/ap_config.png)\n\nPick something not immediately obvious and relatively secure as - as mentioned before - it is all that prevents an attacker from connecting to that AP and reading out your main Wi-Fi credentials.\n\nI have been told that you can also use the wizard to disable the AP entirely, however personally, I like having a fallback way into the inverter, especially since I did not see a \"Factory Reset\" button on the device.\n\n\n### Configuring your network\n\nNow that the AP is secured, use the configuration interface of your router to block internet access of the inverter.\nYou will also likely want to configure it, so that it will always get the same IP assigned via DHCP.\n\nThese things should be dropdowns and checkboxes in most consumer routers.\nIf you run some advanced setup, you will know what to do.\n\nYou can also try to DNS-block `access1.solarmanpv.com` and `access2.solarmanpv.com`, however it seems that the logger firmware might also use hardcoded IPs?\nEither way, just blocking internet access entirely should be much easier in most setups anyway and comes with no known downsides.\n\n## Usage\n\nAfter connecting the inverter to your Wi-Fi network, securing it and blocking its internet access, all you need to do now is monitor and control it.\n\nFor this there are different options.\n\n### Local polling\nMost of the options rely on polling the local modbusTCP interface that uses the inverter logger serial number for authentication.\n\nTo get this serial, simply look at the sticker on the device:\n\n![logger_serial_number](img/logger_sn.png)\n\nIf you feel like doing something arcane and/or want to build something for that yourself, you can find the Modbus spec for these inverters in the complementary assets repo:\n[https://github.com/Hypfer/deye-microinverter-cloud-free-assets](https://github.com/Hypfer/deye-microinverter-cloud-free-assets).\n\nNote that with internet access blocked, the inverter never receives any time information.\nThis breaks the `Yield today` counter as it will never properly reset unless you manually set the time on each boot using modbus register `22`, `23` and `24`.\n\n\n#### With Home Assistant\n\nWith Home Assistant, the easiest way to get your inverter connected is by using [HACS](https://hacs.xyz/) to install the [Solarman](https://github.com/StephanJoubert/home_assistant_solarman) `custom_component`.\nPlease refer to the project documentation on how to install and configure those.\n\nHome Assistant offers powerful tooling to store, visualize and process data right out of the box.\n\nFor example, here's how a solar dashboard could look like using mock data and only stock home assistant cards.\nThe real world will obviously look slightly different but the idea should be the same:\n\n![example home assistant dashboard](img/dashboard_example_mock.png)\n\n\n#### With other smarthome software\n\nIf you're using OpenHAB, FHEM, ioBroker or something else, as long as it can speak MQTT, you can use for example [https://github.com/kbialek/deye-inverter-mqtt](https://github.com/kbialek/deye-inverter-mqtt) to connect your inverter to your smarthome.\n\nA `docker-compose.yml` entry for that tool could look like this:\n\n```yaml\n  deyetomqtt:\n    image: ghcr.io/kbialek/deye-inverter-mqtt\n    container_name: \"deyetomqtt\"\n    environment:\n      - LOG_LEVEL=DEBUG\n      - DEYE_DATA_READ_INTERVAL=60\n      - DEYE_METRIC_GROUPS=micro\n      - DEYE_LOGGER_SERIAL_NUMBER=4151234567\n      - DEYE_LOGGER_IP_ADDRESS=192.168.178.123\n      - DEYE_LOGGER_PORT=8899\n      - MQTT_HOST=192.168.178.2\n      - MQTT_TOPIC_PREFIX=deye\n      - MQTT_PORT=1883\n    restart: always\n```\n\nKeep in mind that this might change in the future so make sure to always check the docs of the project itself.\n\n### Using the dummycloud\n\nIf you don't want polling and/or are unhappy with having the inverter in a perpetual state of reconnection to the cloud,\nyou can instead deploy the cloud replacement that can be found in the [dummycloud](./dummycloud) folder in this repository.\n\nThis will make the inverter happy, provide it with the correct time for daily counters to work and push all the data to your MQTT broker.\nIt will also autoconfigure entities for home assistant.\n\n![dummycloud_demo.png](./img/dummycloud_demo.png)\n\nIt is however a bit more complicated than the polling approaches, as it requires you to understand how networks work\nand how to deploy a service somewhere. Nothing too arcane of course but if you don't know anything about linux, you might want to pass on this.\n\nFor further information, check out the [dummycloud](./dummycloud) folder.\n\n## Misc\n\n### Hidden configuration page\n\nThese inverters also have a hidden configuration page that is reachable via `/config_hide.html`.\n\nThere, it is possible to configure\n\n- Cloud Server A and B\n- Serial Port parameters (which serial port?)\n- The port of the modbusTCP server of the inverter\n- Enable/Disable the AP\n- Switch the branding(?)\n\n<details>\n<summary>Click here to show a screenshot of the page</summary>\n\n![config hide screenshot](img/config_hide.png)\n\n</details>\n\n### AT Commands\n\nApart from the modbus over tcp interface, these inverters also provide another interface on port 48899 where you can talk to it over AT commands like a modem.\nFor that, for now you can use this tool: [https://github.com/s10l/deye-logger-at-cmd](https://github.com/s10l/deye-logger-at-cmd).\n\nSome firmware versions seem to respond to the `AT+H` command with a full list of commands.\nMine doesn't, however a [user fortunately posted a full response](https://www.photovoltaikforum.com/thread/180129-deye-sun600-und-sun2000-erfahrungen/?postID=2846951#post2846951) which is the source for this table:\n\n<details>\n<summary>Click here to show the AT command table</summary>\n\n| Command                                   | Vendor Description                                      |\n|-------------------------------------------|---------------------------------------------------------|\n| AT+TIME                                   | Set/Get Device Time                                     |\n| AT+ADDRESS                                | Set/Get Device Address                                  |\n| AT+KEY                                    | Set/Get Device Password                                 |\n| AT+MTYPE                                  | Set/Get Device Mtype                                    |\n| AT+CNMOSAVE                               | Set/Get TCPB Link Mode                                  |\n| AT+DEVICENUM                              | Set/Get Device Link Num                                 |\n| AT+DEVSELCTL                              | Set/Get Web Device List Info                            |\n| AT+NDBGS                                  | Set/Get Debug Status                                    |\n| AT+FFCLER                                 | Clear File in Flash                                     |\n| AT+LANGSEL                                | Select Language                                         |\n| AT+ADTIME                                 | Set/Get Device Time                                     |\n| AT+YZFTIME                                | Set/Get Device factory Time                             |\n| AT+TZEARSE                                | Clear yz File in Flash                                  |\n| AT+YZACK                                  | Clear yz File in Flash                                  |\n| AT+YZTIME                                 | Clear yz File in Flash                                  |\n| AT+YZWKTIME                               | Clear yz File in Flash                                  |\n| AT+YZERRCLR                               | Clear yz File in Flash                                  |\n| AT+YZDBNUM                                | Clear yz File in Flash                                  |\n| AT+YZDB                                   | Clear yz File in Flash                                  |\n| AT+YZVER                                  | Clear yz File in Flash                                  |\n| AT+YZLOG                                  | Clear yz File in Flash                                  |\n| AT+YZAPP                                  | Clear yz File in Flash                                  |\n| AT+YZAPSTAT                               | Clear yz File in Flash                                  |\n| AT+YZsize                                 | Clear yz File in Flash                                  |\n| AT+YZsize                                 | Clear yz File in Flash                                  |\n| AT+YZsize                                 | Clear yz File in Flash                                  |\n| AT+YZsize                                 | Clear yz File in Flash                                  |\n| AT+YZsize                                 | Clear yz File in Flash                                  |\n| AT+YZsize                                 | Clear yz File in Flash                                  |\n| AT+YZsize                                 | Clear yz File in Flash                                  |\n| AT+YZWAKEYCTL                             | Clear yz File in Flash                                  |\n| AT+YZsize                                 | Clear yz File in Flash                                  |\n| AT+YZFLSHTEST=<password>,<devlist_status> |                                                         |\n| AT+YZFLSHTEST=<password>,<devlist_status> |                                                         |\n| AT+YZVER                                  | Clear yz File in Flash                                  |\n| AT+YZVER                                  | Clear yz File in Flash                                  |\n| AT+YZVER                                  | Clear yz File in Flash                                  |\n| AT+YZVER                                  | Clear yz File in Flash                                  |\n| AT+YZVER                                  | Clear yz File in Flash                                  |\n| AT+YZEXPFUN                               | Clear yz File in Flash                                  |\n| AT+YZEXPFUN                               | Clear yz File in Flash                                  |\n| AT+YZEXPFUN                               | Clear yz File in Flash                                  |\n| AT+YZEXPFUN                               | Clear yz File in Flash                                  |\n| AT+YZEXPFUN                               | Clear yz File in Flash                                  |\n| AT+YZEXPFUN                               | Clear yz File in Flash                                  |\n| AT+TMODE                                  | Set/Get the UART work mode.                             |\n| AT+ENTM                                   | Goto Through MOde.                                      |\n| AT+UART                                   | Set/Get the UART0/UART1 Parameters.                     |\n| AT+WSMAC                                  | Set/Get Module MAC Address.                             |\n| AT+WAMAC                                  | Get Module MAC Address in AP mode.                      |\n| AT+NDBGL                                  | set/get debug level                                     |\n| AT+RELD                                   | Reload the default setting and reboot.                  |\n| AT+RLDEN                                  | Put on/off the Reload Pin.                              |\n| AT+MID                                    | Get The Module ID.                                      |\n| AT+WRMID                                  | Write Module ID.                                        |\n| AT+ASWD                                   | Set/Query WiFi configuration code.                      |\n| AT+VER                                    | Get application version.                                |\n| AT+BVER                                   | Get bootloader version.                                 |\n| AT+HWVER                                  | Get hardware version.                                   |\n| AT+FCLR                                   | Clear Fsetting.                                         |\n| AT+CFGRD                                  | Get current system config.                              |\n| AT+CFGTF                                  | Save Current Config to Default Config.                  |\n| AT+SMEM                                   | show system memory stat                                 |\n| AT+OTA                                    | OTA                                                     |\n| AT+UPURL                                  | Set/Get the path of remote upgrade.                     |\n| AT+CMDPW                                  | Set/Get cmd password in throuphput mode.                |\n| AT+UID                                    | Set/Get UID.                                            |\n| AT+E                                      | Echo ON/Off, to turn on/off command line echo function. |\n| AT+Z                                      | Reset the Module.                                       |\n| AT+SRST                                   | Soft Reset the Module.                                  |\n| AT+H                                      | show help                                               |\n| AT+NETP                                   | Set/Get the Net Protocol Parameters.                    |\n| AT+TCPLK                                  | Get The state of TCP link.                              |\n| AT+TCPTO                                  | Set/Get TCP time out.                                   |\n| AT+TCPDIS                                 | Connect/Dis-connect the TCP Client link                 |\n| AT+MAXSK                                  | Set/Get MAX num of TCP socket (1~5)                     |\n| AT+RCV                                    | Recv data from socket_a                                 |\n| AT+SEND                                   | Send data to socket_a                                   |\n| AT+SOCKB                                  | Set/Get Parameters of socket_b.                         |\n| AT+TCPLKB                                 | Get The state of TCP_B link.                            |\n| AT+TCPTOB                                 | Set/Get TCP_B time out.                                 |\n| AT+TCPDISB                                | Connect/Dis-connect the TCP_B Client link.              |\n| AT+RCVB                                   | Recv data from socket_b                                 |\n| AT+SNDB                                   | Send data to socket_b                                   |\n| AT+WMODE                                  | Set/Get the WIFI Operation Mode (AP or STA).            |\n| AT+WSSSID                                 | Set/Get the AP's SSID of WIFI STA Mode.                 |\n| AT+WSKEY                                  | Set/Get the Security Parameters of WIFI STA Mode.       |\n| AT+WSLK                                   | Get Link Status of the Module (Only for STA Mode).      |\n| AT+WSLQ                                   | Get Link Quality of the Module (Only for STA Mode).     |\n| AT+WAP                                    | Set/Get the AP parameters.                              |\n| AT+WAKEY                                  | Set/Get the Security Parameters of WIFI AP Mode.        |\n| AT+WALK                                   | Show sta information of AP connection.                  |\n| AT+WALKIND                                | enable/disable LED indication of AP connection.         |\n| AT+WAPMXSTA                               | Set/Get the Max Number Of Sta Connected to Ap.          |\n| AT+WSCAN                                  | Get The AP site Survey (only for STA Mode).             |\n| AT+SMTLK                                  | Start Smart Configuration.                              |\n| AT+SMTLKST=mode,protocol                  | Setup smartlnk mode and protocol.                       |\n| AT+SMARTAPCONFIG                          | Enable/disable smart AP config function.                |\n| AT+SMARTAPSTART                           | Start smart AP config function.                         |\n| AT+WPS                                    | Start WPS.                                              |\n| AT+DISPS                                  | Disable power saving mode of WIFI                       |\n| AT+WIFI=UP/DOWN                           | Power down or up  the wifi chip.                        |\n| AT+MDCH                                   | Put on/off automatic switching WIFI mode.               |\n| AT+WSLKO                                  | Enable/Disable connect router with the best signal.     |\n| AT+DTIM                                   | Set/Get station listen interval(1~3).                   |\n| AT+UDPLCPT                                | Set/Get local UDP port.                                 |\n| AT+PING                                   | General PING command.                                   |\n| AT+WANN                                   | Set/Get The WAN setting if in STA mode.                 |\n| AT+LANN                                   | Set/Get The LAN setting if in ADHOC mode.               |\n| AT+WADHCP                                 | enable/disable AP dhcp server and set ip address pool   |\n| AT+WEBU                                   | Set/Get the Login Parameters of WEB page.               |\n| AT+WEBVER                                 | Get WEB version.                                        |\n| AT+PLANG=EN/CN                            | Set/Get the language of WEB page.                       |\n| AT+WSDNS                                  | Set/Get the DNS Server address.                         |\n| AT+NTPEN                                  | Enable/Disable NTP Server.                              |\n| AT+NTPRF                                  | Set/Query NTP.                                          |\n| AT+NTPTM                                  | Set/Query Ntp Time.                                     |\n| AT+NTPSER                                 | Set/Query Ntp Server.                                   |\n| AT+TXPWR                                  | Set/Get wifi rf tx power.                               |\n| AT+RFTESTMODE                             | RF test mode ON/OFF.                                    |\n\n</details>\n\n\n## Donate\n\nIf this software and documentation effort brought value to you, there's the option to leave a small donation using the \"Sponsor\" button on top of the repo or by [clicking right here](https://github.com/sponsors/Hypfer).\n\nThanks!\n"
  },
  {
    "path": "assets/deye_sun600.ksy",
    "content": "meta:\n  id: deye_sun600\n\nseq:\n  - id: header\n    type: header\n  - id: payload\n    size: header.payload_length\n    type:\n      switch-on: header.msg_type\n      cases:\n        \"msg_type::handshake\": handshake_msg_payload\n        \"msg_type::data\": data_msg_payload\n        \"msg_type::wifi\": wifi_msg_payload\n        \"msg_type::command\": command_msg_payload\n  - id: footer\n    type: footer\n\ntypes:\n  header:\n    seq:\n      - id: magic\n        contents: [0xa5]\n      - id: payload_length\n        type: u2le\n      - id: unknown1\n        type: u1\n      - id: msg_type\n        type: u1\n        enum: msg_type\n      - id: msg_id_response\n        type: u1\n      - id: msg_id_request\n        type: u1\n      - id: logger_sn\n        type: u4le\n  footer:\n    seq:\n      - id: checksum\n        type: u1\n      - id: magic\n        contents: [0x15]\n  \n  command_msg_payload:\n    seq:\n      - size: 15\n      - id: command\n        type: str\n        encoding: ASCII\n        size-eos: true\n  \n  handshake_msg_payload:\n    seq:\n      - size: 13\n      - size: 6\n      - id: fw_ver\n        type: str\n        size: 40\n        encoding: ASCII\n      - size: 6\n      - id: ip\n        type: str\n        size: 16\n        encoding: ASCII\n      - size: 8\n      - id: version\n        type: str\n        size: 18\n        encoding: ASCII\n      - size: 65\n      - id: ssid\n        type: str\n        size: 30\n        encoding: ASCII\n      - id: unknown\n        size-eos: true\n\n  data_msg_payload:\n    seq:\n      - id: payload_magic # Might be destination? 01 for logger, 02 for inverter, 129 for logger historic\n        size: 1 # has to be carried over to the response\n      - id: schema\n        enum: data_msg_payload_schema\n        type: u1\n      - id: data\n        size-eos: true\n        type:\n          switch-on: schema\n          cases:\n            \"data_msg_payload_schema::microinverter\": data_msg_payload_microinverter\n            \"data_msg_payload_schema::hybridinverter\": data_msg_payload_hybridinverter\n  \n  data_msg_payload_hybridinverter:\n    seq:\n      - size: 1\n      - id: unknown\n        type: u4le\n      - id: power_on_time\n        type: u4le\n      - id: unknown2\n        type: u4le\n      - size: 10\n      - id: inverter_serial\n        type: str\n        size: 10\n        encoding: ASCII\n      - size: 6\n      - id: some_string\n        type: str\n        size: 28\n        encoding: ASCII\n      - size: 26\n      - id: energy_battery_charge_today\n        type: s2be\n      - id: energy_battery_discharge_today\n        type: s2be\n      - id: energy_battery_charge_total\n        type: s4be\n      - id: energy_battery_discharge_total\n        type: s4be\n      - id: energy_grid_import_today\n        type: s2be\n      - id: energy_grid_export_today\n        type: s2be\n      - id: energy_grid_import_total\n        type: s4be\n      - id: energy_grid_export_total\n        type: s4be\n      - id: energy_house_today\n        type: s2be\n      - id: energy_house_total\n        type: s4be\n\n      - size: 4\n\n      - id: energy_pv_today\n        type: s2be\n      - id: energy_pv1_today # TODO\n        type: s2be\n      - id: energy_pv2_today # TODO\n        type: s2be\n      - id: energy_pv_total\n        type: s4be\n\n      - size: 34\n\n      - id: battery_temp\n        type: s2be\n      - id: battery_voltage\n        type: s2be\n      - id: battery_soc_pct\n        type: s2be\n      - size: 2\n      - id: battery_power\n        type: s2be\n      - id: battery_current\n        type: s2be\n      - id: battery_unknown \n        type: s2be\n\n      - id: grid_l1_n_voltage\n        type: s2be\n      - id: grid_l2_n_voltage\n        type: s2be\n      - id: grid_l3_n_voltage\n        type: s2be\n\n      - size: 8\n\n      - id: grid_l1_power\n        type: s2be\n      - id: grid_l2_power\n        type: s2be\n      - id: grid_l3_power\n        type: s2be\n\n\n  data_msg_payload_microinverter:\n    seq:\n      - size: 5\n      - id: unknown_counter_1\n        type: u2be\n      - size: 8\n      - id: unknown_counter_2\n        type: u2le\n      - size: 2\n      - id: inverter_id\n        size: 10\n      - id: unknown2\n        type: u2le\n      - id: kwh_today\n        type: u4le\n      - id: kwh_total\n        type: u4le\n      - size: 4\n      - id: grid_v\n        type: u2le\n      - size: 4\n      - id: grid_i\n        type: u2le\n      - size: 4\n      - id: grid_freq_hz\n        type: u2le\n      - id: grid_active_power_w\n        type: u4le\n      - id: inverter_radiator_temp_celsius\n        type: s2le\n      - size: 20\n      - id: pv_1_v\n        type: u2le\n      - id: pv_1_i\n        type: u2le\n      - id: pv_2_v\n        type: u2le\n      - id: pv_2_i\n        type: u2le\n      - id: pv_3_v\n        type: u2le\n      - id: pv_3_i\n        type: u2le\n      - id: pv_4_v\n        type: u2le\n      - id: pv_4_i\n        type: u2le\n      - id: protocol_ver\n        type: str\n        size: 8\n        encoding: ASCII\n      - id: dc_master_fw_version\n        type: str\n        size: 8\n        encoding: ASCII\n      - id: ac_fw_version\n        type: str\n        size: 8\n        encoding: ASCII\n      - size: 4\n      - id: inverter_rated_power_w\n        type: u2be\n      - id: mppt_count\n        type: u1\n      - id: phase_count\n        type: u1\n      - size: 3\n      - id: pv_1_kwh_today\n        type: u2le\n      - id: pv_2_kwh_today\n        type: u2le\n      - id: pv_3_kwh_today\n        type: u2le\n      - id: pv_4_kwh_today\n        type: u2le\n      - size: 1\n      - id: pv_1_kwh_total\n        type: u2be\n      - size: 2\n      - id: pv_2_kwh_total\n        type: u2be\n      - size: 2\n      - id: pv_3_kwh_total\n        type: u2be\n      - size: 2\n      - id: pv_4_kwh_total\n        type: u2be\n      - id: pv_ids\n        size: 64\n      - id: grid_freq_hz_overfreq_load_reduction_starting_point\n        type: u2be\n      - id: grid_overfreq_load_reduction_percent\n        type: u2be\n      - size: 8\n      - id: grid_v_limit_upper\n        type: u2be\n      - id: grid_v_limit_lower\n        type: u2be\n      - id: grid_freq_hz_limit_upper\n        type: u2be\n      - id: grid_freq_hz_limit_lower\n        type: u2be\n      - id: startup_self_check_time\n        type: u2be\n      - id: current_time\n        size: 6\n  \n  \n  wifi_msg_payload:\n    seq:\n      - id: schema\n        enum: wifi_msg_payload_schema\n        type: u1\n      - id: maybe_uptime\n        type: u2le\n      - id: some_count\n        type: u2le\n\n      - id: maybe_connection_time_seconds\n        type: u2le\n      - id: unknown2\n        type: u2le\n      - id: unknown3\n        type: u2le\n      - id: unknown5\n        type: u2le\n      - id: unknown7\n        type: u1\n      - id: unknonw8\n        type: u1\n      - id: data\n        size-eos: true\n        type:\n          switch-on: schema\n          cases:\n            \"wifi_msg_payload_schema::foo\": wifi_msg_payload_baz #intentional\n            \"wifi_msg_payload_schema::bar\": wifi_msg_payload_bar\n            \"wifi_msg_payload_schema::baz\": wifi_msg_payload_baz\n  \n  wifi_msg_payload_bar:\n    seq:\n      - id: inverter_sn\n        size: 10\n        type: str\n        encoding: ASCII\n      - id: data\n        size-eos: true\n  wifi_msg_payload_baz:\n    seq:\n      - id: ssid\n        type: str\n        size: 30\n        encoding: ASCII\n      - id: signal_quality_pct\n        type: u1\n      - id: some_constant\n        contents: [0x01]\n\n\nenums:\n  msg_type:\n    0x11: \"handshake_response\"\n    0x12: \"data_response\"\n    0x17: \"heartbeat_response\"\n    0x41: \"handshake\"\n    0x42: \"data\"\n    0x43: \"wifi\"\n    0x45: \"command\"\n    0x47: \"heartbeat\"\n  \n  data_msg_payload_schema:\n    0x08: \"microinverter\"\n    0x11: \"hybridinverter\"\n    0x13: \"relaymodule\"\n  \n  wifi_msg_payload_schema:\n    0x01: \"foo\"\n    0x04: \"bar\"\n    0x81: \"baz\"\n"
  },
  {
    "path": "dummycloud/.automated.eslintrc.json",
    "content": "{\n  \"rules\": {\n    \"brace-style\": [\n      \"error\",\n      \"1tbs\"\n    ],\n    \"no-trailing-spaces\": [\n      \"error\",\n      {\n        \"ignoreComments\": true\n      }\n    ],\n    \"keyword-spacing\": \"error\",\n    \"eol-last\": [\n      \"error\",\n      \"always\"\n    ],\n    \"no-multi-spaces\": [\n      \"error\",\n      {\n        \"ignoreEOLComments\": true\n      }\n    ],\n    \"semi\": [\n      \"error\",\n      \"always\"\n    ],\n    \"quotes\": [\n      \"error\",\n      \"double\"\n    ],\n    \"indent\": [\n      \"error\",\n      4,\n      {\n        \"SwitchCase\": 1\n      }\n    ],\n    \"no-empty\": \"error\"\n  }\n}"
  },
  {
    "path": "dummycloud/.eslintrc.json",
    "content": "{\n  \"env\": {\n    \"browser\": true,\n    \"commonjs\": true,\n    \"es6\": true,\n    \"node\": true,\n    \"mocha\": true\n  },\n  \"plugins\": [\"jsdoc\", \"sort-keys-fix\", \"sort-requires\", \"regexp\"],\n  \"extends\": [\"eslint:recommended\", \"plugin:regexp/recommended\"],\n  \"ignorePatterns\": [\"dist/*.js\"],\n  \"globals\": {\n    \"Atomics\": \"readonly\",\n    \"SharedArrayBuffer\": \"readonly\"\n  },\n  \"parserOptions\": {\n    \"ecmaVersion\": 2020,\n    \"sourceType\": \"module\"\n  },\n  \"settings\": {\n    \"jsdoc\": {\n      \"mode\": \"closure\",\n      \"tagNamePreference\": {\n        \"returns\": \"returns\",\n        \"augments\": \"extends\"\n      }\n    }\n  },\n  \"rules\": {\n    \"no-labels\": \"error\",\n    \"max-classes-per-file\": \"error\",\n    \"eqeqeq\": \"error\",\n    \"curly\": \"error\",\n    \"default-case-last\": \"error\",\n    \"block-scoped-var\": \"error\",\n    \"no-new\": \"error\",\n    \"no-multi-str\": \"error\",\n    \"no-new-wrappers\": \"error\",\n    \"no-sequences\": \"error\",\n    \"no-self-compare\": \"error\",\n    \"no-multi-assign\": \"error\",\n    \"no-whitespace-before-property\": \"error\",\n    \"no-magic-numbers\": [\"off\", { \"ignoreArrayIndexes\": true }],\n    \"no-unused-vars\": [\"warn\", { \"args\": \"none\" }],\n    \"jsdoc/check-alignment\": \"error\",\n    \"jsdoc/check-param-names\": \"error\",\n    \"jsdoc/check-tag-names\": \"error\",\n    \"jsdoc/check-types\": \"error\",\n    \"jsdoc/implements-on-classes\": \"error\",\n    \"jsdoc/no-undefined-types\": \"error\",\n    \"jsdoc/require-param\": \"error\",\n    \"jsdoc/require-param-name\": \"error\",\n    \"jsdoc/require-param-type\": \"error\",\n    \"jsdoc/require-returns-check\": \"error\",\n    \"jsdoc/require-returns-type\": \"error\",\n    \"sort-requires/sort-requires\": \"warn\",\n    \"operator-linebreak\": [\"error\", \"after\"],\n    \"no-unneeded-ternary\": [\"error\", { \"defaultAssignment\": false }],\n    \"arrow-body-style\": [\"error\", \"always\"],\n    \"regexp/no-unused-capturing-group\": \"off\",\n\n\n\n    \"no-empty\": \"off\",\n    \"brace-style\": \"off\",\n    \"no-trailing-spaces\": \"off\",\n    \"keyword-spacing\": \"off\",\n    \"eol-last\": \"off\",\n    \"no-multi-spaces\": \"off\",\n    \"semi\": \"off\",\n    \"quotes\": \"off\",\n    \"indent\": \"off\",\n    \"no-extra-boolean-cast\": \"off\"\n\n\n  }\n}\n"
  },
  {
    "path": "dummycloud/Dockerfile",
    "content": "FROM node:lts-alpine\n\nWORKDIR /app\nENV LOGLEVEL=\"info\"\nENV MQTT_BROKER_URL=\"mqtt://127.0.0.1\"\n\nCOPY package.json /app\nCOPY package-lock.json /app\n\nRUN npm ci\nCOPY . /app\n\nCMD [\"npm\", \"start\"]"
  },
  {
    "path": "dummycloud/LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright 2023 Sören Beye\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "dummycloud/Readme.md",
    "content": "# Deye-dummycloud\n\nThis is a small Node.js service that mocks the deye solarman cloud and publishes all the data to an MQTT broker.\nIt also takes care of Home Assistant autodiscovery leading to things just working.\n\n![dummycloud_demo.png](../img/dummycloud_demo.png)\n\n## Usage\n\nThe dummycloud is configured using environment variables to be container-friendly to use.\n\n- `LOGLEVEL` (defaults to `info`)\n- `MQTT_BROKER_URL` (no default. Should look like `mqtt://foo.bar`)\n- `MQTT_USERNAME` (no default, optional.)\n- `MQTT_PASSWORD` (no default, optional.)\n- `MQTT_CHECK_CERT` set to `false` for using `mqtts` with self signed certificate (defaults to `true`)\n\n## Inverter Setup\n\nUsing the `/config_hide.html` of the inverter webinterface, simply point `Server A Setting` and `Optional Server Setting` to the host this is running on.\nI'd still keep the firewall rules preventing the inverter from phoning home in place for good measure.\n\n## Deployment\n\nThe dummycloud can be started using `npm run start`. Next to this readme, there's also a dockerfile provided.\n\nA `docker-compose.yml` entry could for example look like this:\n\n```yml\n  deye-dummycloud:\n    build:\n      context: ./deye-microinverter-cloud-free/dummycloud/\n      dockerfile: Dockerfile\n    container_name: \"deye-dummycloud\"\n    restart: always\n    environment:\n      - \"LOGLEVEL=info\"\n      - \"MQTT_BROKER_URL=mqtt://foobar.example\"\n      # User those variables if the MQTT broker requires username and password\n      # - \"MQTT_USERNAME=example-user\"\n      # - \"MQTT_PASSWORD=example-password\"\n    ports:\n      - \"10000:10000\"\n```\n"
  },
  {
    "path": "dummycloud/app.js",
    "content": "const DummyCloud = require(\"./src/DummyCloud\");\nconst Logger = require(\"./src/Logger\");\nconst MqttClient = require(\"./src/MqttClient\");\n\nif (process.env.LOGLEVEL) {\n    Logger.setLogLevel(process.env.LOGLEVEL);\n}\n\nconst dummyCloud = new DummyCloud();\nconst mqttClient = new MqttClient(dummyCloud);\n\ndummyCloud.initialize();\nmqttClient.initialize();\n"
  },
  {
    "path": "dummycloud/package.json",
    "content": "{\n  \"name\": \"deye-dummycloud\",\n  \"version\": \"1.1.0\",\n  \"description\": \"\",\n  \"main\": \"app.js\",\n  \"scripts\": {\n    \"start\": \"node app.js\",\n\n    \"lint\": \"eslint -c .automated.eslintrc.json .\",\n    \"lint_fix\": \"eslint -c .automated.eslintrc.json . --fix\"\n  },\n  \"author\": \"\",\n  \"license\": \"Apache-2.0\",\n  \"dependencies\": {\n    \"mqtt\": \"^4.3.7\"\n  },\n  \"devDependencies\": {\n    \"eslint\": \"8.16.0\",\n    \"eslint-plugin-jsdoc\": \"48.9.3\",\n    \"eslint-plugin-regexp\": \"1.7.0\",\n    \"eslint-plugin-sort-keys-fix\": \"1.1.2\",\n    \"eslint-plugin-sort-requires\": \"git+https://npm@github.com/Hypfer/eslint-plugin-sort-requires.git#2.1.1\"\n  }\n}\n"
  },
  {
    "path": "dummycloud/src/DummyCloud.js",
    "content": "const EventEmitter = require(\"events\").EventEmitter;\nconst Logger = require(\"./Logger\");\nconst net = require(\"net\");\nconst Protocol = require(\"./Protocol\");\n\nclass DummyCloud {\n    constructor() {\n        this.eventEmitter = new EventEmitter();\n        this.server = new net.Server();\n    }\n\n    initialize() {\n        this.server.listen(\n            {\n                port: DummyCloud.PORT,\n                host: \"0.0.0.0\"\n            }, \n            function() {\n                Logger.info(`Starting deye-dummycloud on port ${DummyCloud.PORT}`);\n        });\n\n        this.server.on(\"connection\", (socket) => {\n            this.handleConnection(socket);\n        });\n    }\n\n    /**\n     * @private\n     * @param {net.Socket} socket\n     */\n    handleConnection(socket) {\n        const remoteAddress = socket.remoteAddress; // As this is a getter, it may become unavailable\n        Logger.info(`New connection from ${remoteAddress}`);\n\n        socket.on(\"data\", (data) => {\n            Logger.trace(new Date().toISOString(), `Data received from client ${remoteAddress}: ${data.toString()}`);\n            Logger.trace(new Date().toISOString(), `Data ${remoteAddress}:`, data.toString(\"hex\"));\n\n            try {\n                const packet = Protocol.parsePacket(data);\n                let response;\n\n                switch (packet.header.type) {\n                    case Protocol.MESSAGE_REQUEST_TYPES.HEARTBEAT: {\n                        response = Protocol.buildTimeResponse(packet);\n                        break;\n                    }\n                    case Protocol.MESSAGE_REQUEST_TYPES.WIFI: {\n                        /*\n                            There isn't much of interest in this packet\n                            It can contain the SSID or the Logger SN\n                            + Some counters increasing every second\n                            \n                            On connect, it also can contain the signal strength\n                            But that's about it\n                            \n                            The signal strength over time would've been interesting, but it only gets sent on connect\n                            With that, it's close to useless\n                         */\n                        response = Protocol.buildTimeResponse(packet);\n                        break;\n                    }\n                    case Protocol.MESSAGE_REQUEST_TYPES.HANDSHAKE: {\n                        const data = Protocol.parseLoggerPacketPayload(packet);\n\n                        Logger.debug(`Handshake packet data from ${remoteAddress}`, data);\n                        this.emitHandshake({\n                            header: packet.header,\n                            payload: data\n                        });\n\n                        response = Protocol.buildTimeResponse(packet);\n                        break;\n                    }\n                    case Protocol.MESSAGE_REQUEST_TYPES.DATA: {\n                        const data = Protocol.parseDataPacketPayload(packet);\n\n                        if (data) {\n                            Logger.debug(`DATA packet data from ${remoteAddress}`, data);\n                            this.emitData({\n                                header: packet.header,\n                                payload: data,\n                                meta: {\n                                    remoteAddress: remoteAddress\n                                }\n                            });\n                        } else {\n                            Logger.debug(\"Discarded data packet\");\n                        }\n\n                        response = Protocol.buildTimeResponse(packet);\n                        break;\n                    }\n\n                    default: {\n                        response = Protocol.buildTimeResponse(packet);\n                    }\n                }\n\n                if (response) {\n                    Logger.trace(\"Response\", response.toString(\"hex\"));\n\n                    socket.write(response);\n                }\n            } catch (e) {\n                Logger.error(`Error while parsing packet from ${remoteAddress}`, e);\n            }\n        });\n\n        socket.on(\"end\", function() {\n            Logger.info(`Ending connection with ${remoteAddress}`);\n        });\n\n        socket.on(\"close\", function() {\n            Logger.info(`Closing connection with ${remoteAddress}`);\n        });\n\n        socket.on(\"error\", function(err) {\n            Logger.error(`Error on dummycloud socket for ${remoteAddress}`, err);\n        });\n    }\n\n    emitData(data) {\n        this.eventEmitter.emit(DummyCloud.PACKET_EVENTS.Data, data);\n    }\n\n    onData(listener) {\n        this.eventEmitter.on(DummyCloud.PACKET_EVENTS.Data, listener);\n    }\n\n    emitHandshake(data) {\n        this.eventEmitter.emit(DummyCloud.PACKET_EVENTS.Handshake, data);\n    }\n\n    onHandshake(listener) {\n        this.eventEmitter.on(DummyCloud.PACKET_EVENTS.Handshake, listener);\n    }\n}\n\nDummyCloud.PACKET_EVENTS = {\n    Data: \"Data\",\n    Handshake: \"Handshake\"\n};\n\n\nDummyCloud.PORT = 10000;\n\nmodule.exports = DummyCloud;\n"
  },
  {
    "path": "dummycloud/src/Logger.js",
    "content": "const util = require(\"util\");\n\nclass Logger {\n    constructor() {\n        this.logLevel = Logger.LogLevels[\"info\"];\n    }\n\n    /**\n     * @public\n     * @return {string}\n     */\n    getLogLevel() {\n        return Object.keys(Logger.LogLevels).find(key => {\n            return Logger.LogLevels[key] === this.logLevel;\n        });\n    }\n\n    /**\n     * @public\n     * @param {string} value\n     */\n    setLogLevel(value) {\n        if (Logger.LogLevels[value] === undefined) {\n            throw new Error(`Invalid log level '${value}', valid are '${Object.keys(Logger.LogLevels).join(\"','\")}'`);\n        } else {\n            this.logLevel = Logger.LogLevels[value];\n        }\n    }\n\n\n    /**\n     * @private\n     * @param {string} logLevel\n     * @return {string}\n     */\n    buildLogLinePrefix(logLevel) {\n        return `[${new Date().toISOString()}] [${logLevel}]`;\n    }\n\n    /**\n     * @param {string} level\n     * @param {...any} args\n     * @private\n     */\n    log(level, ...args) {\n        if (this.logLevel[\"level\"] <= Logger.LogLevels[level][\"level\"]) {\n            const logLinePrefix = this.buildLogLinePrefix(level.toUpperCase());\n            const logLine = [logLinePrefix, ...args].map(arg => {\n                if (typeof arg === \"string\") {\n                    return arg;\n                }\n\n                return util.inspect(\n                    arg,\n                    {\n                        depth: Infinity\n                    }\n                );\n            }).join(\" \");\n\n            Logger.LogLevels[level][\"callback\"](logLine);\n        }\n    }\n\n    /**\n     * @public\n     * @see console.trace\n     * @param  {...any} args\n     */\n    trace(...args) {\n        this.log(\"trace\", ...args);\n    }\n\n    /**\n     * @public\n     * @see console.debug\n     * @param  {...any} args\n     */\n    debug(...args) {\n        this.log(\"debug\", ...args);\n    }\n\n    /**\n     * @public\n     * @see console.info\n     * @param  {...any} args\n     */\n    info(...args) {\n        this.log(\"info\", ...args);\n    }\n\n    /**\n     * @public\n     * @see console.warn\n     * @param  {...any} args\n     */\n    warn(...args) {\n        this.log(\"warn\", ...args);\n    }\n\n    /**\n     * @public\n     * @see console.error\n     * @param  {...any} args\n     */\n    error( ...args) {\n        this.log(\"error\", ...args);\n    }\n}\n\nLogger.LogLevels = Object.freeze({\n    // eslint-disable-next-line no-console\n    \"trace\": {\"level\": -2, \"callback\": console.debug},\n    // eslint-disable-next-line no-console\n    \"debug\": {\"level\": -1, \"callback\": console.debug},\n    // eslint-disable-next-line no-console\n    \"info\": {\"level\": 0, \"callback\": console.info},\n    // eslint-disable-next-line no-console\n    \"warn\": {\"level\": 1, \"callback\": console.warn},\n    // eslint-disable-next-line no-console\n    \"error\": {\"level\": 2, \"callback\": console.error},\n});\n\nmodule.exports = new Logger();\n"
  },
  {
    "path": "dummycloud/src/MqttClient.js",
    "content": "const Logger = require(\"./Logger\");\nconst mqtt = require(\"mqtt\");\n\n\nclass MqttClient {\n    /**\n     *\n     * @param {import(\"./DummyCloud\")} dummyCloud\n     */\n    constructor(dummyCloud) {\n        this.dummyCloud = dummyCloud;\n\n        this.autoconfTimestamps = {};\n\n        this.dummyCloud.onHandshake((data) => {\n            this.handleHandshake(data);\n        });\n        this.dummyCloud.onData((data) => {\n            this.handleData(data);\n        });\n    }\n\n    initialize() {\n        const options = {\n            clientId: `deye_dummycloud_${Math.random().toString(16).slice(2, 9)}`,  // 23 characters allowed\n        };\n\n        if (process.env.MQTT_USERNAME) {\n            options.username = process.env.MQTT_USERNAME;\n\n            if (process.env.MQTT_PASSWORD) {\n                options.password = process.env.MQTT_PASSWORD;\n            }\n        } else if (process.env.MQTT_PASSWORD) {\n            // MQTT_PASSWORD is set but MQTT_USERNAME is not\n            Logger.error(\"MQTT_PASSWORD is set but MQTT_USERNAME is not. MQTT_USERNAME must be set if MQTT_PASSWORD is set.\");\n            process.exit(1);\n        }\n\n        if (process.env.MQTT_CHECK_CERT) {\n            options.rejectUnauthorized = (process.env.MQTT_CHECK_CERT !== \"false\");\n        }\n\n        this.client = mqtt.connect(process.env.MQTT_BROKER_URL, options);\n\n        this.client.on(\"connect\", () => {\n            Logger.info(\"Connected to MQTT broker\");\n        });\n\n        this.client.on(\"error\", (e) => {\n            if (e && e.message === \"Not supported\") {\n                Logger.info(\"Connected to non-standard-compliant MQTT Broker.\");\n            } else {\n                Logger.error(\"MQTT error:\", e.toString());\n            }\n        });\n\n        this.client.on(\"reconnect\", () => {\n            Logger.info(\"Attempting to reconnect to MQTT broker\");\n        });\n    }\n\n    handleHandshake(data) {\n        // Nothing to see here\n    }\n\n    handleData(data) {\n        this.ensureAutoconf(data.meta, data.header.loggerSerial.toString(), data.payload.inverter_meta.mppt_count);\n        const baseTopic = `${MqttClient.TOPIC_PREFIX}/${data.header.loggerSerial.toString()}`;\n\n        for (let i = 1; i <= data.payload.inverter_meta.mppt_count; i++) {\n            this.client.publish(`${baseTopic}/pv/${i}/v`, data.payload.pv[`${i}`].v.toString());\n            this.client.publish(`${baseTopic}/pv/${i}/i`, data.payload.pv[`${i}`].i.toString());\n            this.client.publish(`${baseTopic}/pv/${i}/w`, data.payload.pv[`${i}`].w.toString());\n            this.client.publish(\n                `${baseTopic}/pv/${i}/kWh_today`,\n                data.payload.pv[`${i}`].kWh_today.toString(),\n                {retain: true}\n            );\n\n            if (data.payload.pv[`${i}`].kWh_total > 0) {\n                this.client.publish(\n                    `${baseTopic}/pv/${i}/kWh_total`,\n                    data.payload.pv[`${i}`].kWh_total.toString(),\n                    {retain: true}\n                );\n            }\n        }\n\n        this.client.publish(`${baseTopic}/grid/active_power_w`, data.payload.grid.active_power_w.toString());\n\n        this.client.publish(\n            `${baseTopic}/grid/kWh_today`,\n            data.payload.grid.kWh_today.toString(),\n            {retain: true}\n        );\n        if (data.payload.grid.kWh_total > 0) {\n            this.client.publish(\n                `${baseTopic}/grid/kWh_total`,\n                data.payload.grid.kWh_total.toString(),\n                {retain: true}\n            );\n        }\n        this.client.publish(`${baseTopic}/grid/v`, data.payload.grid.v.toString());\n        this.client.publish(`${baseTopic}/grid/hz`, data.payload.grid.hz.toString());\n\n        this.client.publish(`${baseTopic}/inverter/radiator_temperature`, data.payload.inverter.radiator_temp_celsius.toString());\n\n\n        const totalDcPower = Object.values(data.payload.pv).reduce((sum, pv) => sum + pv.w, 0);\n        const acPower = Math.abs(data.payload.grid.active_power_w);\n        const efficiency = totalDcPower > 0 && totalDcPower > acPower ? ((acPower / totalDcPower) * 100).toFixed(2) : \"null\";\n\n        this.client.publish(`${baseTopic}/inverter/efficiency`, efficiency);\n    }\n\n    ensureAutoconf(meta, loggerSerial, mpptCount) {\n        // (Re-)publish every 4 hours\n        if (Date.now() - (this.autoconfTimestamps[loggerSerial] ?? 0) <= 4 * 60 * 60 * 1000) {\n            return;\n        }\n        const baseTopic = `${MqttClient.TOPIC_PREFIX}/${loggerSerial.toString()}`;\n        const device = {\n            \"manufacturer\":\"Deye\",\n            \"model\":\"Microinverter\",\n            \"name\":`Deye Microinverter ${loggerSerial}`,\n            \"configuration_url\": `http://${meta.remoteAddress}/index_cn.html`,\n            \"identifiers\":[\n                `deye_dummycloud_${loggerSerial}`\n            ]\n        };\n\n        for (let i = 1; i <= mpptCount; i++) {\n            this.client.publish(\n                `homeassistant/sensor/deye_dummycloud_${loggerSerial}/${loggerSerial}_pv${i}_v/config`,\n                JSON.stringify({\n                    \"state_topic\": `${baseTopic}/pv/${i}/v`,\n                    \"name\":`PV ${i} Voltage`,\n                    \"unit_of_measurement\": \"V\",\n                    \"device_class\": \"voltage\",\n                    \"state_class\": \"measurement\",\n                    \"object_id\": `deye_dummycloud_${loggerSerial}_pv_${i}_v`,\n                    \"unique_id\": `deye_dummycloud_${loggerSerial}_pv_${i}_v`,\n                    \"expire_after\": 360,\n                    \"enabled_by_default\": i < 3,\n                    \"device\": device\n                }),\n                {retain: true}\n            );\n            this.client.publish(\n                `homeassistant/sensor/deye_dummycloud_${loggerSerial}/${loggerSerial}_pv${i}_i/config`,\n                JSON.stringify({\n                    \"state_topic\": `${baseTopic}/pv/${i}/i`,\n                    \"name\":`PV ${i} Current`,\n                    \"unit_of_measurement\": \"A\",\n                    \"device_class\": \"current\",\n                    \"state_class\": \"measurement\",\n                    \"object_id\": `deye_dummycloud_${loggerSerial}_pv_${i}_i`,\n                    \"unique_id\": `deye_dummycloud_${loggerSerial}_pv_${i}_i`,\n                    \"expire_after\": 360,\n                    \"enabled_by_default\": i < 3,\n                    \"device\": device\n                }),\n                {retain: true}\n            );\n            this.client.publish(\n                `homeassistant/sensor/deye_dummycloud_${loggerSerial}/${loggerSerial}_pv${i}_w/config`,\n                JSON.stringify({\n                    \"state_topic\": `${baseTopic}/pv/${i}/w`,\n                    \"name\":`PV ${i} Power`,\n                    \"unit_of_measurement\": \"W\",\n                    \"device_class\": \"power\",\n                    \"state_class\": \"measurement\",\n                    \"object_id\": `deye_dummycloud_${loggerSerial}_pv_${i}_w`,\n                    \"unique_id\": `deye_dummycloud_${loggerSerial}_pv_${i}_w`,\n                    \"expire_after\": 360,\n                    \"enabled_by_default\": i < 3,\n                    \"device\": device\n                }),\n                {retain: true}\n            );\n\n            this.client.publish(\n                `homeassistant/sensor/deye_dummycloud_${loggerSerial}/${loggerSerial}_pv${i}_kWh_today/config`,\n                JSON.stringify({\n                    \"state_topic\": `${baseTopic}/pv/${i}/kWh_today`,\n                    \"name\":`PV ${i} Energy Today`,\n                    \"unit_of_measurement\": \"kWh\",\n                    \"device_class\": \"energy\",\n                    \"state_class\": \"total_increasing\",\n                    \"object_id\": `deye_dummycloud_${loggerSerial}_pv_${i}_kWh_today`,\n                    \"unique_id\": `deye_dummycloud_${loggerSerial}_pv_${i}_kWh_today`,\n                    \"enabled_by_default\": i < 3,\n                    \"device\": device\n                }),\n                {retain: true}\n            );\n            this.client.publish(\n                `homeassistant/sensor/deye_dummycloud_${loggerSerial}/${loggerSerial}_pv${i}_kWh_total/config`,\n                JSON.stringify({\n                    \"state_topic\": `${baseTopic}/pv/${i}/kWh_total`,\n                    \"name\":`PV ${i} Energy Total`,\n                    \"unit_of_measurement\": \"kWh\",\n                    \"device_class\": \"energy\",\n                    \"state_class\": \"total_increasing\",\n                    \"object_id\": `deye_dummycloud_${loggerSerial}_pv_${i}_kWh_total`,\n                    \"unique_id\": `deye_dummycloud_${loggerSerial}_pv_${i}_kWh_total`,\n                    \"enabled_by_default\": i < 3,\n                    \"device\": device\n                }),\n                {retain: true}\n            );\n        }\n\n\n        this.client.publish(\n            `homeassistant/sensor/deye_dummycloud_${loggerSerial}/${loggerSerial}_grid_active_power_w/config`,\n            JSON.stringify({\n                \"state_topic\": `${baseTopic}/grid/active_power_w`,\n                \"name\":\"Grid Power (Active)\",\n                \"unit_of_measurement\": \"W\",\n                \"device_class\": \"power\",\n                \"state_class\": \"measurement\",\n                \"object_id\": `deye_dummycloud_${loggerSerial}_grid_active_power_w`,\n                \"unique_id\": `deye_dummycloud_${loggerSerial}_grid_active_power_w`,\n                \"expire_after\": 360,\n                \"device\": device\n            }),\n            {retain: true}\n        );\n        this.client.publish(\n            `homeassistant/sensor/deye_dummycloud_${loggerSerial}/${loggerSerial}_grid_kWh_today/config`,\n            JSON.stringify({\n                \"state_topic\": `${baseTopic}/grid/kWh_today`,\n                \"name\":\"Grid Energy Today\",\n                \"unit_of_measurement\": \"kWh\",\n                \"device_class\": \"energy\",\n                \"state_class\": \"total_increasing\",\n                \"object_id\": `deye_dummycloud_${loggerSerial}_grid_energy_today`,\n                \"unique_id\": `deye_dummycloud_${loggerSerial}_grid_energy_today`,\n                \"device\": device\n            }),\n            {retain: true}\n        );\n        this.client.publish(\n            `homeassistant/sensor/deye_dummycloud_${loggerSerial}/${loggerSerial}_grid_kWh_total/config`,\n            JSON.stringify({\n                \"state_topic\": `${baseTopic}/grid/kWh_total`,\n                \"name\":\"Grid Energy Total\",\n                \"unit_of_measurement\": \"kWh\",\n                \"device_class\": \"energy\",\n                \"state_class\": \"total_increasing\",\n                \"object_id\": `deye_dummycloud_${loggerSerial}_grid_energy_total`,\n                \"unique_id\": `deye_dummycloud_${loggerSerial}_grid_energy_total`,\n                \"device\": device\n            }),\n            {retain: true}\n        );\n        this.client.publish(\n            `homeassistant/sensor/deye_dummycloud_${loggerSerial}/${loggerSerial}_grid_v/config`,\n            JSON.stringify({\n                \"state_topic\": `${baseTopic}/grid/v`,\n                \"name\":\"Grid Voltage\",\n                \"unit_of_measurement\": \"V\",\n                \"device_class\": \"voltage\",\n                \"state_class\": \"measurement\",\n                \"object_id\": `deye_dummycloud_${loggerSerial}_grid_v`,\n                \"unique_id\": `deye_dummycloud_${loggerSerial}_grid_v`,\n                \"expire_after\": 360,\n                \"device\": device\n            }),\n            {retain: true}\n        );\n        this.client.publish(\n            `homeassistant/sensor/deye_dummycloud_${loggerSerial}/${loggerSerial}_grid_hz/config`,\n            JSON.stringify({\n                \"state_topic\": `${baseTopic}/grid/hz`,\n                \"name\":\"Grid Frequency\",\n                \"unit_of_measurement\": \"Hz\",\n                \"device_class\": \"frequency\",\n                \"state_class\": \"measurement\",\n                \"object_id\": `deye_dummycloud_${loggerSerial}_grid_hz`,\n                \"unique_id\": `deye_dummycloud_${loggerSerial}_grid_hz`,\n                \"expire_after\": 360,\n                \"device\": device\n            }),\n            {retain: true}\n        );\n\n        this.client.publish(\n            `homeassistant/sensor/deye_dummycloud_${loggerSerial}/${loggerSerial}_inverter_radiator_temperature/config`,\n            JSON.stringify({\n                \"state_topic\": `${baseTopic}/inverter/radiator_temperature`,\n                \"name\":\"Radiator Temperature\",\n                \"unit_of_measurement\": \"°C\",\n                \"device_class\": \"temperature\",\n                \"state_class\": \"measurement\",\n                \"object_id\": `deye_dummycloud_${loggerSerial}_inverter_radiator_temperature`,\n                \"unique_id\": `deye_dummycloud_${loggerSerial}_inverter_radiator_temperature`,\n                \"expire_after\": 360,\n                \"device\": device\n            }),\n            {retain: true}\n        );\n\n        this.client.publish(\n            `homeassistant/sensor/deye_dummycloud_${loggerSerial}/${loggerSerial}_inverter_efficiency/config`,\n            JSON.stringify({\n                \"state_topic\": `${baseTopic}/inverter/efficiency`,\n                \"name\":\"Inverter Efficiency\",\n                \"unit_of_measurement\": \"%\",\n                \"entity_category\": \"diagnostic\",\n                \"icon\": \"mdi:cog-transfer\",\n                \"state_class\": \"measurement\",\n                \"object_id\": `deye_dummycloud_${loggerSerial}_inverter_efficiency`,\n                \"unique_id\": `deye_dummycloud_${loggerSerial}_inverter_efficiency`,\n                \"expire_after\": 360,\n                \"value_template\": \"{{ value_json }}\",\n                \"device\": device\n            }),\n            {retain: true}\n        );\n\n        this.autoconfTimestamps[loggerSerial] = Date.now();\n    }\n}\n\nMqttClient.TOPIC_PREFIX = \"deye-dummycloud\";\n\nmodule.exports = MqttClient;\n"
  },
  {
    "path": "dummycloud/src/Protocol.js",
    "content": "const Logger = require(\"./Logger\");\nconst {getKeyByValue, truncateToNullTerminator} = require(\"./util\");\n\nconst HEADER_LEN = 11;\nconst FOOTER_LEN = 2;\n\nclass Protocol {\n    static parseHeader(buf) {\n        const result = {\n            magic: buf[0], //should be 0xa5\n            payloadLength: buf.readUInt16LE(1),\n            unknown1: buf[3],\n            type: buf[4],\n            msgIDResponse: buf[5],\n            msgIDRequest: buf[6],\n            loggerSerial: buf.readUint32LE(7)\n        };\n\n        if (result.magic !== 0xa5) {\n            throw new Error(\"Invalid header magic: \" + result.magic);\n        }\n\n        if (result.payloadLength + HEADER_LEN + FOOTER_LEN !== buf.length) {\n            throw new Error(\"Payload length from header doesn't match packet length. Truncated?\");\n        }\n\n        return result;\n    }\n\n    static parseFooter(buf) {\n        const result = {\n            checksum: buf[buf.length - 2],\n            magic: buf[buf.length - 1] //should always be 0x15\n        };\n\n        if (result.magic !== 0x15) {\n            throw new Error(\"Invalid footer magic: \" + result.magic);\n        }\n\n        return result;\n    }\n\n    static checksum(msgBuf) {\n        const slice = msgBuf.subarray(1, msgBuf.length - 2); //exclude magic bytes and checksum\n        let sum = 0;\n\n        for (let i = 0; i < slice.length; i++) {\n            sum = (sum + slice[i]) & 255;\n        }\n\n        return sum & 255;\n    }\n\n\n    static parsePacket(buf) {\n        const header = Protocol.parseHeader(buf);\n\n        const typeStr = getKeyByValue(Protocol.MESSAGE_REQUEST_TYPES, header.type);\n        if (typeStr) {\n            Logger.debug(`Received packet of type \"${typeStr}\"`);\n        } else {\n            Logger.warn(`Received packet of unknown type \"0x${header.type.toString(16)}\"`);\n        }\n\n        return {\n            header: header,\n            payload: buf.subarray(HEADER_LEN, buf.length - FOOTER_LEN)\n        };\n    }\n\n    static parseDataPacketPayload(packet) {\n        switch (packet.payload[1]) {\n            case Protocol.DATA_PACKET_SCHEMAS.MICROINVERTER:\n                return Protocol.parseDataPacketMicroinverterPayload(packet);\n            default:\n                return null; //TODO: parse relay and string inverter packets\n        }\n\n\n    }\n\n    static parseDataPacketMicroinverterPayload(packet) {\n        if (!!(packet.payload[0] & 0b10000000)) {\n            // Seems to be one of these weird historic data packets from the SUN-M series. Ignoring for now\n            // TODO: understand what they mean and how they should be handled\n            return null;\n        }\n\n        //TODO: there's a lot more in this packet\n\n        return {\n            pv: {\n                \"1\": {\n                    v: packet.payload.readUInt16LE(85) / 10,\n                    i: packet.payload.readUInt16LE(87) / 10,\n\n                    w: parseFloat(((packet.payload.readUInt16LE(85) / 10) * (packet.payload.readUInt16LE(87) / 10)).toFixed(2)),\n\n                    kWh_today: packet.payload.readUInt16LE(136) / 10,\n                    kWh_total: packet.payload.readUInt16BE(145) / 10,\n                },\n                \"2\": {\n                    v: packet.payload.readUInt16LE(89) / 10,\n                    i: packet.payload.readUInt16LE(91) / 10,\n\n                    w: parseFloat(((packet.payload.readUInt16LE(89) / 10) * (packet.payload.readUInt16LE(91) / 10)).toFixed(2)),\n\n                    kWh_today: packet.payload.readUInt16LE(138) / 10,\n                    kWh_total: packet.payload.readUInt16BE(149) / 10,\n                },\n                \"3\": {\n                    v: packet.payload.readUInt16LE(93) / 10,\n                    i: packet.payload.readUInt16LE(95) / 10,\n\n                    w: parseFloat(((packet.payload.readUInt16LE(93) / 10) * (packet.payload.readUInt16LE(95) / 10)).toFixed(2)),\n\n                    kWh_today: packet.payload.readUInt16LE(140) / 10,\n                    kWh_total: packet.payload.readUInt16BE(153) / 10,\n                },\n                \"4\": {\n                    v: packet.payload.readUInt16LE(97) / 10,\n                    i: packet.payload.readUInt16LE(99) / 10,\n\n                    w: parseFloat(((packet.payload.readUInt16LE(97) / 10) * (packet.payload.readUInt16LE(99) / 10)).toFixed(2)),\n\n                    kWh_today: packet.payload.readUInt16LE(142) / 10,\n                    kWh_total: packet.payload.readUInt16BE(157) / 10,\n                },\n            },\n            grid: {\n                active_power_w: packet.payload.readUInt32LE(59),\n\n                kWh_today: packet.payload.readUInt32LE(33) / 100,\n                kWh_total: packet.payload.readUInt32LE(37) / 10,\n\n                v: packet.payload.readUInt16LE(45) / 10,\n                i: packet.payload.readUInt16LE(51) / 10,\n\n                hz: packet.payload.readUInt16LE(57) / 100,\n\n            },\n            inverter: {\n                radiator_temp_celsius: packet.payload.readInt16LE(63) / 100, //TODO: is this actually a signed int?\n            },\n            inverter_meta: {\n                rated_power_w: packet.payload.readUInt16BE(129) / 10,\n                mppt_count: packet.payload.readInt8(131),\n                phase_count: packet.payload.readInt8(132),\n\n                startup_self_check_time: packet.payload.readUInt16BE(243),\n                current_time: Protocol.parseTime(packet.payload.subarray(245, 251)),\n\n\n                grid_freq_hz_overfreq_load_reduction_starting_point: packet.payload.readUInt16BE(223) / 100,\n                grid_overfreq_load_reduction_percent: packet.payload.readUInt16BE(225),\n\n                grid_v_limit_upper: packet.payload.readUInt16BE(235) / 10,\n                grid_v_limit_lower: packet.payload.readUInt16BE(237) / 10,\n                grid_freq_hz_limit_upper: packet.payload.readUInt16BE(239) / 100,\n                grid_freq_hz_limit_lower: packet.payload.readUInt16BE(241) / 100,\n\n                protocol_ver: packet.payload.subarray(101, 109).toString(\"ascii\"),\n                dc_master_fw_ver: packet.payload.subarray(109, 117).toString(\"ascii\"),\n                ac_fw_ver: packet.payload.subarray(117, 125).toString(\"ascii\"),\n            },\n\n            //for some reason everything after byte ~120 is all BE compared to the above?\n\n        };\n    }\n\n    static parseLoggerPacketPayload(packet) {\n        //TODO: there's a lot more in this packet\n        return {\n            fw_ver: truncateToNullTerminator(packet.payload.subarray(19, 60).toString(\"ascii\")),\n            ip: truncateToNullTerminator(packet.payload.subarray(65, 82).toString(\"ascii\")),\n            ver: truncateToNullTerminator(packet.payload.subarray(89, 130).toString(\"ascii\")), //hw revision maybe?\n            ssid: truncateToNullTerminator(packet.payload.subarray(172, 210).toString(\"ascii\")),\n        };\n    }\n\n    static buildTimeResponse(packet) {\n        const response = Buffer.alloc(23);\n\n        // header\n        response[0] = 0xa5; //magic\n        response.writeUInt16LE(10, 1); //payload len\n        response[3] = packet.header.unknown1;\n        response[4] = packet.header.type - 0x30; // set type to response for that type\n        response[5] = packet.header.msgIDResponse + 1;\n        response[6] = packet.header.msgIDRequest;\n        response.writeUint32LE(packet.header.loggerSerial, 7);\n        // end header\n\n        response[11] = packet.payload[0];\n        response[12] = 0x01;\n\n        response.writeUint32LE(\n            Math.round(Date.now()/1000),\n            13\n        );\n        response.writeUint32LE(\n            0,\n            17\n        );\n\n\n        response[response.length - 2] = Protocol.checksum(response);\n        response[response.length - 1] = 0x15; //magic\n\n        return response;\n    }\n\n    static parseTime(buf) {\n        return new Date(\n            [\n                `${2000 + buf[0]}-${buf[1].toString().padStart(2, \"0\")}-${buf[2].toString().padStart(2, \"0\")}T`,\n                `${buf[3].toString().padStart(2, \"0\")}:${buf[4].toString().padStart(2, \"0\")}:${buf[5].toString().padStart(2, \"0\")}Z`\n            ].join(\"\")\n        );\n    }\n}\n\nProtocol.MESSAGE_REQUEST_TYPES = {\n    HANDSHAKE: 0x41,\n    DATA: 0x42,\n    WIFI: 0x43,\n    HEARTBEAT: 0x47,\n};\n\nProtocol.MESSAGE_RESPONSE_TYPES = {\n    HANDSHAKE: 0x11,\n    DATA: 0x12,\n    // wifi info reply is 0x13?\n    HEARTBEAT: 0x17,\n};\n\nProtocol.DATA_PACKET_SCHEMAS = {\n    MICROINVERTER: 0x08,\n    HYBRIDINVERTER: 0x11,\n    RELAYMODULE: 0x13\n};\n\nmodule.exports = Protocol;\n"
  },
  {
    "path": "dummycloud/src/util.js",
    "content": "\nfunction getKeyByValue(obj, value) {\n    for (const key in obj) {\n        // eslint-disable-next-line no-prototype-builtins\n        if (obj.hasOwnProperty(key) && obj[key] === value) {\n            return key;\n        }\n    }\n}\n\nfunction truncateToNullTerminator(str) {\n    const nullTerminatorIndex = str.indexOf(\"\\0\");\n    if (nullTerminatorIndex !== -1) {\n        return str.slice(0, nullTerminatorIndex);\n    } else {\n        return str;\n    }\n}\n\n\nmodule.exports = {\n    getKeyByValue: getKeyByValue,\n    truncateToNullTerminator: truncateToNullTerminator\n};\n"
  }
]