├── phev-ha.png ├── addon ├── config.json ├── Dockerfile ├── run.sh ├── CHANGELOG.md └── README.md ├── go.mod ├── main.go ├── cmd ├── decode.go ├── client.go ├── hex.go ├── file.go ├── watch.go ├── set.go ├── root.go ├── register.go ├── emulator.go ├── pcap.go └── mqtt.go ├── protocol ├── settings.go ├── message_test.go ├── raw_test.go ├── raw.go ├── message.go └── README.md ├── emulator ├── state_machine.go ├── connection.go └── car.go ├── lovelace.yaml ├── client └── client.go ├── README.md └── LICENSE /phev-ha.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/buxtronix/phev2mqtt/HEAD/phev-ha.png -------------------------------------------------------------------------------- /addon/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "PHEV", 3 | "version": "1.4", 4 | "slug": "phev", 5 | "description": "Mitsubishi PHEV", 6 | "arch": ["armhf", "armv7", "aarch64", "amd64", "i386"], 7 | "startup": "application", 8 | "boot": "auto", 9 | "options": { 10 | "mqtt_server": null, 11 | "mqtt_user": null, 12 | "mqtt_password": null, 13 | "debug": false 14 | }, 15 | "schema": { 16 | "mqtt_server": "str", 17 | "mqtt_user": "str", 18 | "mqtt_password": "str", 19 | "debug": "bool" 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /addon/Dockerfile: -------------------------------------------------------------------------------- 1 | ARG BUILD_FROM 2 | FROM $BUILD_FROM as builder 3 | 4 | RUN apk update && apk add --no-cache \ 5 | g++ \ 6 | gcc \ 7 | git \ 8 | libpcap-dev 9 | 10 | WORKDIR /tmp 11 | RUN git clone https://github.com/buxtronix/phev2mqtt.git 12 | COPY --from=golang:alpine /usr/local/go/ /usr/local/go/ 13 | RUN cd /tmp/phev2mqtt && \ 14 | /usr/local/go/bin/go build 15 | 16 | FROM $BUILD_FROM 17 | RUN apk update && apk add --no-cache \ 18 | libpcap-dev 19 | 20 | COPY --from=builder /tmp/phev2mqtt/phev2mqtt /opt/phev2mqtt 21 | 22 | COPY run.sh /opt 23 | RUN chmod a+x /opt/run.sh 24 | 25 | CMD [ "/opt/run.sh" ] 26 | -------------------------------------------------------------------------------- /addon/run.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/with-contenv bashio 2 | 3 | CONFIG_PATH=/data/options.json 4 | 5 | export mqtt_server="$(bashio::config 'mqtt_server')" 6 | export mqtt_user="$(bashio::config 'mqtt_user')" 7 | export mqtt_password="$(bashio::config 'mqtt_password')" 8 | export debug="$(bashio::config 'debug')" 9 | 10 | if [[ $debug == "true" ]] 11 | then 12 | echo Debug mode on - sleeping indefinitely 13 | sleep inf 14 | fi 15 | 16 | echo Starting phev2mqtt 17 | 18 | /opt/phev2mqtt \ 19 | client \ 20 | mqtt \ 21 | --mqtt_server "tcp://${mqtt_server}/" \ 22 | --mqtt_username "${mqtt_user}" \ 23 | --mqtt_password "${mqtt_password}" 24 | 25 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/buxtronix/phev2mqtt 2 | 3 | go 1.16 4 | 5 | require ( 6 | github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf // indirect 7 | github.com/d4l3k/messagediff v1.2.1 // indirect 8 | github.com/eclipse/paho.mqtt.golang v1.3.5 9 | github.com/google/btree v1.0.0 // indirect 10 | github.com/google/gopacket v1.1.19 11 | github.com/sirupsen/logrus v1.8.1 12 | github.com/spf13/cobra v1.2.1 13 | github.com/spf13/viper v1.8.1 14 | github.com/wercker/journalhook v0.0.0-20230927020745-64542ffa4117 // indirect 15 | golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6 // indirect 16 | golang.org/x/sync v0.0.0-20210220032951-036812b2e83c 17 | gopkg.in/d4l3k/messagediff.v1 v1.2.1 18 | ) 19 | -------------------------------------------------------------------------------- /addon/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Version 1.4 2 | * Changed "startup": "before" to "startup": "application" as "before" no longer supported and it should really start after Home Assistant 3 | 4 | # Version 1.3 5 | * Removed host networking as it wasn't required 6 | 7 | # Version 1.2 8 | * Removed fatal error if Outlander is not available 9 | 10 | # Version 1.1 11 | * Set inital values of mqtt_user and mqtt_password to null instead of dummy values to ensure that user enters them 12 | * Added debug variable to allow start of container and then manual connection to it to run commands 13 | * Added netcat test to check that Outlander is available 14 | * Moved phev2mqtt binary from /tmp/phev2mqtt to /opt 15 | 16 | # Version 1 17 | Initial build 18 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2021 Ben Buxton 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | package main 18 | 19 | import "github.com/buxtronix/phev2mqtt/cmd" 20 | 21 | func main() { 22 | cmd.Execute() 23 | } 24 | -------------------------------------------------------------------------------- /addon/README.md: -------------------------------------------------------------------------------- 1 | This requires that Home Assistant is already connected to the Outlander, you should be able to check this by ensuring that you can ping 192.168.8.46 2 | 3 | Once installed as a local addon, you must configure the mqtt target and username/password before start and stop phev2mqtt from the GUI 4 | For my docker install the host machine's address (which is also running the mqtt addon) is 172.30.32.1:1883 (I suspect this could be different depending on install) 5 | 6 | These files need to go in a directory (called phev for example) in the local addons. 7 | 8 | If you ssh into the main os, this will be in /usr/share/hassio/addons/local/phev 9 | If you ssh in using the terminal add on, this will be /addons/phev (or symblink /root/addons/phev) 10 | If you connect to the hassio_supervisort docker container, this will be /data/addons/local/phev 11 | 12 | More information about local addons at https://developers.home-assistant.io/docs/add-ons/tutorial/ 13 | 14 | If you set the debug flag on, it will just start the container and sleep indefinitely, you can then run the phev2mqtt manually, to run "phev2mqtt client watch" for example. 15 | 16 | NOTE - on 32bit Raspberry Pi there's an issue with the latest alpine docker images and old versions of libseccomp (including the ones in Raspbian repos), this will stop the Dockerfile building. In order to overcome this, you may need to manually install a newer version with 17 | 18 | wget http://ftp.us.debian.org/debian/pool/main/libs/libseccomp/libseccomp2_2.4.4-1~bpo10+1_armhf.deb 19 | dpkg -i libseccomp2_2.4.4-1~bpo10+1_armhf.deb 20 | -------------------------------------------------------------------------------- /cmd/decode.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2021 Ben Buxton 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | package cmd 18 | 19 | import ( 20 | "github.com/spf13/cobra" 21 | ) 22 | 23 | // decodeCmd represents the decode command 24 | var decodeCmd = &cobra.Command{ 25 | Use: "decode", 26 | Short: "Commands to decode Phev messages", 27 | Long: ` 28 | Commands for decoding messages to and from a Phev. 29 | Subcommands provide specific functionality, see below. 30 | `, 31 | Run: func(cmd *cobra.Command, args []string) { 32 | cmd.Help() 33 | }, 34 | } 35 | 36 | func init() { 37 | rootCmd.AddCommand(decodeCmd) 38 | 39 | // Here you will define your flags and configuration settings. 40 | 41 | // Cobra supports Persistent Flags which will work for this command 42 | // and all subcommands, e.g.: 43 | // decodeCmd.PersistentFlags().String("foo", "", "A help for foo") 44 | 45 | // Cobra supports local flags which will only run when this command 46 | // is called directly, e.g.: 47 | // decodeCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") 48 | } 49 | -------------------------------------------------------------------------------- /protocol/settings.go: -------------------------------------------------------------------------------- 1 | package protocol 2 | 3 | import ( 4 | "encoding/binary" 5 | "fmt" 6 | "strings" 7 | // log "github.com/sirupsen/logrus" 8 | ) 9 | 10 | // Vehicle settings are sent to the client in register 0x16. 11 | // The client sends updated settings to the vehicle via register 0x0f. 12 | type Settings struct { 13 | settings []uint64 14 | } 15 | 16 | // FromRegister extracts settings from the 0x16 register. They appear 17 | // to be little endian and need decoding, though this is not yet certain. 18 | func (s *Settings) FromRegister(reg []byte) error { 19 | switch { 20 | case len(reg) != 8: 21 | return fmt.Errorf("register wrong length got=%d want=8", len(reg)) 22 | case reg[0] != 0x2: 23 | return fmt.Errorf("register must start with 0x2, is 0x%x", reg[0]) 24 | case reg[7] != 0x0: 25 | return fmt.Errorf("register must end with 0x0, is 0x%x", reg[7]) 26 | } 27 | value := binary.LittleEndian.Uint64(reg) 28 | for _, v := range s.settings { 29 | if value == v { 30 | return nil 31 | } 32 | } 33 | s.settings = append(s.settings, value) 34 | return nil 35 | } 36 | 37 | func (s *Settings) Clear() { 38 | s.settings = []uint64{} 39 | } 40 | 41 | func (s *Settings) NewSender() *SettingsSender { 42 | return &SettingsSender{settings: s.settings} 43 | } 44 | 45 | func (s *Settings) Dump() string { 46 | ret := []string{} 47 | for _, v := range s.settings { 48 | ret = append(ret, fmt.Sprintf("%016x", v)) 49 | } 50 | return strings.Join(ret, "\n") 51 | } 52 | 53 | type SettingsSender struct { 54 | C chan *PhevMessage 55 | settings []uint64 56 | } 57 | 58 | func (s *SettingsSender) Start() { 59 | s.C = make(chan *PhevMessage) 60 | go func() { 61 | for i := 0; i < len(s.settings); i++ { 62 | buf := make([]byte, 8) 63 | binary.LittleEndian.PutUint64(buf, s.settings[i]) 64 | s.C <- NewMessage(CmdInResp, 0x16, false, buf) 65 | } 66 | close(s.C) 67 | }() 68 | } 69 | -------------------------------------------------------------------------------- /cmd/client.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2021 Ben Buxton 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | package cmd 18 | 19 | import ( 20 | "github.com/spf13/cobra" 21 | "github.com/spf13/viper" 22 | ) 23 | 24 | // clientCmd represents the client command 25 | var clientCmd = &cobra.Command{ 26 | Use: "client", 27 | Short: "Client to connect and interact with the vehicle", 28 | Long: ` 29 | Client functionality for connecting and interacting with 30 | the vehicle. Please see subcommands for available functions. 31 | Requires Wifi reachability to the vehicle.`, 32 | Run: func(cmd *cobra.Command, args []string) { 33 | cmd.Help() 34 | }, 35 | } 36 | 37 | func init() { 38 | rootCmd.AddCommand(clientCmd) 39 | 40 | // Here you will define your flags and configuration settings. 41 | 42 | // Cobra supports Persistent Flags which will work for this command 43 | // and all subcommands, e.g.: 44 | // clientCmd.PersistentFlags().String("foo", "", "A help for foo") 45 | clientCmd.PersistentFlags().String("address", "192.168.8.46:8080", "Address to connect to") 46 | 47 | viper.BindPFlag("address", clientCmd.PersistentFlags().Lookup("address")) 48 | // Cobra supports local flags which will only run when this command 49 | // is called directly, e.g.: 50 | // clientCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") 51 | } 52 | -------------------------------------------------------------------------------- /cmd/hex.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2021 Ben Buxton 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | package cmd 18 | 19 | import ( 20 | "encoding/hex" 21 | "github.com/buxtronix/phev2mqtt/protocol" 22 | log "github.com/sirupsen/logrus" 23 | "github.com/spf13/cobra" 24 | ) 25 | 26 | // hexCmd represents the hex command 27 | var hexCmd = &cobra.Command{ 28 | Use: "hex", 29 | Short: "Decode provided raw hex messages.", 30 | Long: `Decodes raw messages provided as arguments. Messages 31 | should be in hex format, e;g 'dc2b2f762f7f'.`, 32 | Args: cobra.MinimumNArgs(1), 33 | Run: func(cmd *cobra.Command, args []string) { 34 | securityKey = &protocol.SecurityKey{} 35 | for _, arg := range args { 36 | data, err := hex.DecodeString(arg) 37 | if err != nil { 38 | log.Errorf("Not a valid hex string [%s]: %v", arg, err) 39 | continue 40 | } 41 | for _, msg := range protocol.NewFromBytes(data, securityKey) { 42 | log.Debug(hex.EncodeToString(msg.Original)) 43 | log.Infof("%s", msg.ShortForm()) 44 | } 45 | } 46 | }, 47 | } 48 | 49 | func init() { 50 | decodeCmd.AddCommand(hexCmd) 51 | 52 | // Here you will define your flags and configuration settings. 53 | 54 | // Cobra supports Persistent Flags which will work for this command 55 | // and all subcommands, e.g.: 56 | // hexCmd.PersistentFlags().String("foo", "", "A help for foo") 57 | 58 | // Cobra supports local flags which will only run when this command 59 | // is called directly, e.g.: 60 | // hexCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") 61 | } 62 | -------------------------------------------------------------------------------- /cmd/file.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2021 Ben Buxton 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | package cmd 18 | 19 | import ( 20 | "encoding/hex" 21 | "os" 22 | "strings" 23 | 24 | "github.com/buxtronix/phev2mqtt/protocol" 25 | log "github.com/sirupsen/logrus" 26 | "github.com/spf13/cobra" 27 | ) 28 | 29 | var securityKey *protocol.SecurityKey 30 | 31 | // fileCmd represents the file command 32 | var fileCmd = &cobra.Command{ 33 | Use: "file", 34 | Short: "Decode Phev messages from a file", 35 | Long: ` 36 | Decode raw hex string messages from the provided filename. 37 | `, 38 | Args: cobra.ExactArgs(1), 39 | Run: func(cmd *cobra.Command, args []string) { 40 | f, err := os.Open(args[0]) 41 | if err != nil { 42 | panic(err) 43 | } 44 | defer f.Close() 45 | 46 | inData := make([]byte, 100000) 47 | n, err := f.Read(inData) 48 | if err != nil { 49 | panic(err) 50 | } 51 | dat := strings.Replace(string(inData[:n]), "\n", "", -1) 52 | binData, err := hex.DecodeString(dat) 53 | if err != nil { 54 | panic(err) 55 | } 56 | securityKey = &protocol.SecurityKey{} 57 | for _, msg := range protocol.NewFromBytes(binData, securityKey) { 58 | log.Debug(hex.EncodeToString(msg.Original)) 59 | log.Infof("%s", msg.ShortForm()) 60 | } 61 | }, 62 | } 63 | 64 | func init() { 65 | decodeCmd.AddCommand(fileCmd) 66 | 67 | // Here you will define your flags and configuration settings. 68 | 69 | // Cobra supports Persistent Flags which will work for this command 70 | // and all subcommands, e.g.: 71 | // fileCmd.PersistentFlags().String("foo", "", "A help for foo") 72 | 73 | // Cobra supports local flags which will only run when this command 74 | // is called directly, e.g.: 75 | // fileCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") 76 | } 77 | -------------------------------------------------------------------------------- /cmd/watch.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2021 Ben Buxton 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | package cmd 18 | 19 | import ( 20 | "encoding/hex" 21 | "time" 22 | 23 | "github.com/buxtronix/phev2mqtt/client" 24 | "github.com/buxtronix/phev2mqtt/protocol" 25 | log "github.com/sirupsen/logrus" 26 | "github.com/spf13/cobra" 27 | ) 28 | 29 | // watchCmd represents the watch command 30 | var watchCmd = &cobra.Command{ 31 | Use: "watch", 32 | Short: "Connect to Phev and watch incoming updates", 33 | Long: `Connects to the Phev and watches for incoming register 34 | updates, displaying them in real-time.`, 35 | Run: Run, 36 | } 37 | 38 | func Run(cmd *cobra.Command, args []string) { 39 | address, _ := cmd.Flags().GetString("address") 40 | cl, err := client.New(client.AddressOption(address)) 41 | if err != nil { 42 | panic(err) 43 | } 44 | 45 | if err := cl.Connect(); err != nil { 46 | panic(err) 47 | } 48 | 49 | if err := cl.Start(); err != nil { 50 | panic(err) 51 | } 52 | 53 | var registers = map[byte]string{} 54 | 55 | for { 56 | select { 57 | case m, ok := <-cl.Recv: 58 | if !ok { 59 | log.Infof("Connection closed.") 60 | return 61 | } 62 | switch m.Type { 63 | case protocol.CmdInResp: 64 | dataStr := hex.EncodeToString(m.Data) 65 | if data := registers[m.Register]; data != dataStr { 66 | log.Infof("%%PHEV_REG_UPDATE%% %02x: %s -> %s", m.Register, data, dataStr) 67 | registers[m.Register] = dataStr 68 | if _, ok := m.Reg.(*protocol.RegisterGeneric); !ok { 69 | log.Infof("%%PHEV_REG_UPDATE%% %02x: [%s]", m.Register, m.Reg.String()) 70 | } 71 | } 72 | cl.Send <- &protocol.PhevMessage{ 73 | Type: protocol.CmdOutSend, 74 | Register: m.Register, 75 | Ack: protocol.Ack, 76 | Xor: m.Xor, 77 | Data: []byte{0x0}, 78 | } 79 | } 80 | } 81 | } 82 | } 83 | 84 | func init() { 85 | clientCmd.AddCommand(watchCmd) 86 | 87 | // Here you will define your flags and configuration settings. 88 | 89 | // Cobra supports Persistent Flags which will work for this command 90 | // and all subcommands, e.g.: 91 | // watchCmd.PersistentFlags().String("foo", "", "A help for foo") 92 | 93 | // Cobra supports local flags which will only run when this command 94 | // is called directly, e.g.: 95 | // watchCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") 96 | watchCmd.Flags().DurationP("wait", "w", 60*time.Second, "How long to hold connection open for") 97 | } 98 | -------------------------------------------------------------------------------- /emulator/state_machine.go: -------------------------------------------------------------------------------- 1 | package emulator 2 | 3 | import ( 4 | "github.com/buxtronix/phev2mqtt/protocol" 5 | log "github.com/sirupsen/logrus" 6 | "time" 7 | ) 8 | 9 | func (s *Connection) manage() { 10 | l := s.AddListener() 11 | pingCount := 0 12 | defer func() { 13 | l.Stop() 14 | s.RemoveListener(l) 15 | }() 16 | for { 17 | select { 18 | case msg := <-l.C: 19 | switch msg.Type { 20 | case protocol.CmdOutPingReq: 21 | // Ping request from client. 22 | pingCount++ 23 | s.Send <- protocol.NewPingResponseMessage(msg.Register) 24 | if s.key.State == protocol.SecurityEmpty && pingCount == 10 { 25 | // Establish initial key after 10th ping. 26 | s.state = conSecInit 27 | s.rekey() 28 | } 29 | case protocol.CmdOutMy18StartResp: 30 | if msg.Original[2] == 0x0 { 31 | s.rekey() 32 | break 33 | } 34 | if s.key.State == protocol.SecurityKeyProposed { 35 | s.key.AcceptProposal() 36 | s.sendNextRegister() 37 | } 38 | /* 39 | if s.state == conSecInit { 40 | s.state = conRegisterStart 41 | s.registerIndex = 0 42 | s.sendNextRegister() 43 | } 44 | */ 45 | case protocol.CmdOutSend: 46 | if msg.Ack == protocol.Ack { 47 | s.sendNextRegister() 48 | } 49 | if msg.Ack == protocol.Request { 50 | s.handleSetRegister(msg) 51 | } 52 | } 53 | } 54 | } 55 | } 56 | 57 | func (s *Connection) getRegister(r byte) protocol.Register { 58 | for _, reg := range s.car.Registers { 59 | if reg.Register() == r { 60 | return reg 61 | } 62 | } 63 | return nil 64 | } 65 | 66 | func (s *Connection) handleSetRegister(msg *protocol.PhevMessage) { 67 | // Ack the message that came in. 68 | s.Send <- protocol.NewMessage(protocol.CmdInResp, msg.Register, true, []byte{0x0}) 69 | switch msg.Register { 70 | case 0x05: 71 | s.Send <- protocol.NewMessage(protocol.CmdInResp, protocol.TimeRegister, false, msg.Data) 72 | time.Sleep(20 * time.Millisecond) 73 | s.Send <- protocol.NewMessage(protocol.CmdInResp, protocol.BatteryLevelRegister, false, []byte{0x50, 0x00, 0x00, 0x00}) 74 | } 75 | 76 | } 77 | 78 | func (s *Connection) sendNextRegister() { 79 | if s.settingsSender != nil { 80 | if setting, ok := <-s.settingsSender.C; ok { 81 | s.Send <- setting 82 | } else { 83 | s.settingsSender = nil 84 | } 85 | return 86 | } 87 | if s.registerIndex < 0 { 88 | return 89 | } 90 | msg := s.car.Registers[s.registerIndex].Encode() 91 | msg.Type = protocol.CmdInResp 92 | msg.Ack = protocol.Request 93 | s.Send <- msg 94 | 95 | s.registerIndex++ 96 | if s.registerIndex >= len(s.car.Registers) { 97 | s.registerIndex = -1 98 | log.Debug("Finished sending registers, sending settings") 99 | s.settingsSender = s.car.Settings.NewSender() 100 | s.settingsSender.Start() 101 | } 102 | } 103 | 104 | // Generate and send new key request. 105 | func (s *Connection) rekey() { 106 | if s.state == conRegisterStart { 107 | s.Send <- protocol.NewMessage(protocol.CmdInMy18StartReq, 0x1, true, []byte{0x0}) 108 | } 109 | data := s.key.GenerateProposal() 110 | s.Send <- protocol.NewMessage(protocol.CmdInMy18StartReq, 0x1, false, append(data, 0x1)) 111 | s.key.State = protocol.SecurityKeyProposed 112 | } 113 | -------------------------------------------------------------------------------- /emulator/connection.go: -------------------------------------------------------------------------------- 1 | package emulator 2 | 3 | import ( 4 | "encoding/hex" 5 | log "github.com/sirupsen/logrus" 6 | "net" 7 | "sync" 8 | "time" 9 | 10 | "github.com/buxtronix/phev2mqtt/client" 11 | "github.com/buxtronix/phev2mqtt/protocol" 12 | ) 13 | 14 | type connState int 15 | 16 | const ( 17 | conClosed connState = iota 18 | conTCPOpen 19 | conSecInit 20 | conRegisterStart 21 | conEstablished 22 | ) 23 | 24 | func NewConnection(conn net.Conn, car *Car) *Connection { 25 | log.Infof("Connection received!\n") 26 | return &Connection{ 27 | state: conClosed, 28 | car: car, 29 | conn: conn, 30 | key: &protocol.SecurityKey{}, 31 | Send: make(chan *protocol.PhevMessage, 5), 32 | 33 | listeners: []*client.Listener{}, 34 | } 35 | } 36 | 37 | // A Connection implements a client connection service. 38 | type Connection struct { 39 | car *Car 40 | conn net.Conn 41 | key *protocol.SecurityKey 42 | Send chan *protocol.PhevMessage 43 | 44 | listeners []*client.Listener 45 | lMu sync.Mutex 46 | 47 | state connState 48 | 49 | registerIndex int 50 | settingsSender *protocol.SettingsSender 51 | } 52 | 53 | func (s *Connection) Close() error { 54 | s.state = conClosed 55 | if s.conn != nil { 56 | return s.conn.Close() 57 | } 58 | return nil 59 | } 60 | 61 | // Create and return a new Listener. 62 | func (s *Connection) AddListener() *client.Listener { 63 | s.lMu.Lock() 64 | defer s.lMu.Unlock() 65 | l := &client.Listener{} 66 | l.Start() 67 | s.listeners = append(s.listeners, l) 68 | return l 69 | } 70 | 71 | func (s *Connection) RemoveListener(l *client.Listener) { 72 | newL := []*client.Listener{} 73 | s.lMu.Lock() 74 | defer s.lMu.Unlock() 75 | for _, lis := range s.listeners { 76 | if lis != l { 77 | newL = append(newL, lis) 78 | } 79 | } 80 | s.listeners = newL 81 | } 82 | 83 | func (s *Connection) Start() { 84 | s.state = conTCPOpen 85 | go s.reader() 86 | go s.writer() 87 | go s.manage() 88 | } 89 | 90 | func (s *Connection) reader() { 91 | for { 92 | s.conn.(*net.TCPConn).SetReadDeadline(time.Now().Add(30 * time.Second)) 93 | data := make([]byte, 4096) 94 | n, err := s.conn.Read(data) 95 | if err != nil { 96 | log.Debugf("%%PHEV_SVC_READER_ERROR%% %v", err) 97 | s.conn.Close() 98 | return 99 | } 100 | log.Tracef("%%PHEV_SVC_RECV_RAW%%: %s", hex.EncodeToString(data[:n])) 101 | msgs := protocol.NewFromBytes(data[:n], s.key) 102 | for _, m := range msgs { 103 | if m.Type != protocol.CmdOutPingReq { 104 | log.Debugf("%%PHEV_SVC_RCV_MSG%%: %s", m.ShortForm()) 105 | } 106 | s.lMu.Lock() 107 | for _, l := range s.listeners { 108 | l.Send(m) 109 | } 110 | s.lMu.Unlock() 111 | } 112 | } 113 | } 114 | 115 | func (s *Connection) writer() { 116 | for { 117 | select { 118 | case msg, ok := <-s.Send: 119 | if !ok { 120 | log.Debug("%PHEV_SVC_SEND_CLOSE%") 121 | s.Close() 122 | return 123 | } 124 | if msg.Type != protocol.CmdInPingResp { 125 | log.Debugf("%%PHEV_SVC_SND_MSG%%: %s", msg.ShortForm()) 126 | } 127 | data := msg.EncodeToBytes(s.key) 128 | s.conn.(*net.TCPConn).SetWriteDeadline(time.Now().Add(15 * time.Second)) 129 | if _, err := s.conn.Write(data); err != nil { 130 | log.Debugf("%%PHEV_SVC_WRITE_ERR%%: %v", err) 131 | s.Close() 132 | return 133 | } 134 | } 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /cmd/set.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2021 Ben Buxton 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | package cmd 18 | 19 | import ( 20 | "encoding/hex" 21 | "strings" 22 | "time" 23 | 24 | "github.com/buxtronix/phev2mqtt/client" 25 | log "github.com/sirupsen/logrus" 26 | "github.com/spf13/cobra" 27 | ) 28 | 29 | // setCmd represents the set command 30 | var setCmd = &cobra.Command{ 31 | Use: "set", 32 | Short: "Set register value(s)", 33 | Args: cobra.MinimumNArgs(1), 34 | Long: `Send new values to the car to set register(s). 35 | 36 | Each arg is of the form : - the given register is set to the 37 | given value. Each should be a hex string. 38 | 39 | e.g: 40 | 41 | 0b:02 will set register 0b to the value 02 42 | 43 | `, 44 | Run: runSet, 45 | } 46 | 47 | type regValue struct { 48 | register byte 49 | value []byte 50 | } 51 | 52 | func runSet(cmd *cobra.Command, args []string) { 53 | var register, value []byte 54 | var err error 55 | 56 | setRegisters := []*regValue{} 57 | 58 | for _, arg := range args { 59 | if vals := strings.Split(arg, ":"); len(vals) == 2 { 60 | register, err = hex.DecodeString(vals[0]) 61 | if err != nil { 62 | panic(err) 63 | } 64 | value, err = hex.DecodeString(vals[1]) 65 | if err != nil { 66 | panic(err) 67 | } 68 | setRegisters = append(setRegisters, ®Value{ 69 | register: register[0], value: value, 70 | }) 71 | } 72 | } 73 | 74 | waitTime, err := cmd.Flags().GetDuration("wait_duration") 75 | if err != nil { 76 | panic(err) 77 | } 78 | sendInterval, err := cmd.Flags().GetDuration("send_interval") 79 | if err != nil { 80 | panic(err) 81 | } 82 | 83 | address, _ := cmd.Flags().GetString("address") 84 | cl, err := client.New(client.AddressOption(address)) 85 | if err != nil { 86 | panic(err) 87 | } 88 | 89 | if err := cl.Connect(); err != nil { 90 | panic(err) 91 | } 92 | 93 | if err := cl.Start(); err != nil { 94 | panic(err) 95 | } 96 | log.Infof("Client connected and started!") 97 | log.Infof("Waiting %d", waitTime.String()) 98 | 99 | time.Sleep(waitTime) 100 | 101 | for _, reg := range setRegisters { 102 | log.Infof("Setting register 0x%x to 0x%s", reg.register, hex.EncodeToString(reg.value)) 103 | if err := cl.SetRegister(reg.register, reg.value); err != nil { 104 | panic(err) 105 | } 106 | time.Sleep(sendInterval) 107 | } 108 | 109 | } 110 | 111 | func init() { 112 | clientCmd.AddCommand(setCmd) 113 | 114 | // Here you will define your flags and configuration settings. 115 | 116 | // Cobra supports Persistent Flags which will work for this command 117 | // and all subcommands, e.g.: 118 | // registerCmd.PersistentFlags().String("foo", "", "A help for foo") 119 | 120 | // Cobra supports local flags which will only run when this command 121 | // is called directly, e.g.: 122 | // registerCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") 123 | setCmd.Flags().Duration("wait_duration", 10*time.Second, "How long to wait after connecting to car before sending register update") 124 | setCmd.Flags().Duration("send_interval", 1*time.Second, "Interval between setting each register") 125 | } 126 | -------------------------------------------------------------------------------- /cmd/root.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2021 Ben Buxton 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | package cmd 18 | 19 | import ( 20 | "os" 21 | "fmt" 22 | log "github.com/sirupsen/logrus" 23 | "github.com/wercker/journalhook" 24 | "github.com/spf13/cobra" 25 | "github.com/spf13/viper" 26 | ) 27 | 28 | var ( 29 | cfgFile string 30 | logLevel string 31 | logTimes bool 32 | logSyslog bool 33 | ) 34 | 35 | // rootCmd represents the base command when called without any subcommands 36 | var rootCmd = &cobra.Command{ 37 | Use: "phev2mqtt", 38 | Short: "A utility for communicating with a Mitsubishi PHEV", 39 | Long: `See below for subcommands. For further information 40 | on this tool, see https://github.com/buxtronix/phev2mqtt.`, 41 | PersistentPreRun: func(cmd *cobra.Command, args []string) { 42 | level, err := log.ParseLevel(logLevel) 43 | if err != nil { 44 | panic(err) 45 | } 46 | log.SetLevel(level) 47 | if logSyslog { 48 | journalhook.Enable() 49 | } 50 | if logTimes { 51 | log.SetFormatter(&log.TextFormatter{ 52 | FullTimestamp: true, 53 | }) 54 | } else { 55 | log.SetFormatter(&log.TextFormatter{ 56 | FullTimestamp: false, 57 | DisableColors: true, 58 | DisableTimestamp: true, 59 | }) 60 | } 61 | }, 62 | 63 | // Uncomment the following line if your bare application 64 | // has an action associated with it: 65 | // Run: func(cmd *cobra.Command, args []string) { }, 66 | } 67 | 68 | // Execute adds all child commands to the root command and sets flags appropriately. 69 | // This is called by main.main(). It only needs to happen once to the rootCmd. 70 | func Execute() { 71 | cobra.CheckErr(rootCmd.Execute()) 72 | } 73 | 74 | func init() { 75 | cobra.OnInitialize(initConfig) 76 | 77 | // Here you will define your flags and configuration settings. 78 | // Cobra supports persistent flags, which, if defined here, 79 | // will be global for your application. 80 | 81 | rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.phev2mqtt.yaml)") 82 | rootCmd.PersistentFlags().StringVarP(&logLevel, "verbosity", "v", "info", "logging level to use") 83 | rootCmd.PersistentFlags().BoolVarP(&logTimes, "log_timestamps", "t", false, "coloured logging with timestamps") 84 | rootCmd.PersistentFlags().BoolVarP(&logSyslog, "log_syslog", "s", false, "plain logging to syslog instead of console") 85 | 86 | // Cobra also supports local flags, which will only run 87 | // when this action is called directly. 88 | // rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") 89 | } 90 | 91 | // initConfig reads in config file and ENV variables if set. 92 | func initConfig() { 93 | if cfgFile != "" { 94 | // Use config file from the flag. 95 | viper.SetConfigFile(cfgFile) 96 | } else { 97 | // Find home directory. 98 | home, err := os.UserHomeDir() 99 | cobra.CheckErr(err) 100 | 101 | // Search config in home directory with name ".phev2mqtt" (without extension). 102 | viper.AddConfigPath(home) 103 | viper.SetConfigType("yaml") 104 | viper.SetConfigName(".phev2mqtt") 105 | } 106 | 107 | viper.AutomaticEnv() // read in environment variables that match 108 | 109 | // If a config file is found, read it in. 110 | if err := viper.ReadInConfig(); err == nil { 111 | fmt.Fprintln(os.Stderr, "Using config file:", viper.ConfigFileUsed()) 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /protocol/message_test.go: -------------------------------------------------------------------------------- 1 | package protocol 2 | 3 | import ( 4 | "encoding/hex" 5 | "gopkg.in/d4l3k/messagediff.v1" 6 | "testing" 7 | ) 8 | 9 | func TestDecodeEncodeBytes(t *testing.T) { 10 | tests := []struct { 11 | in string 12 | sk *SecurityKey 13 | want *PhevMessage 14 | }{ 15 | { 16 | in: "f60400060303", 17 | sk: &SecurityKey{keyMap: []byte{0x00, 0x00}}, 18 | want: &PhevMessage{ 19 | Type: 0xf6, 20 | Length: 0x6, 21 | Register: 0x6, 22 | Data: []byte{0x3}, 23 | Checksum: 0x3, 24 | Original: []byte{0xf6, 0x4, 0x0, 0x6, 0x3, 0x3}, 25 | OriginalXored: []byte{0xf6, 0x4, 0x0, 0x6, 0x3, 0x3}, 26 | }, 27 | }, { 28 | in: "502f3fff0f0f0a0d0f0d0d0f0f0f2f3e3f04", 29 | sk: &SecurityKey{keyMap: []byte{0x3f, 0x3f, 0x3f}}, 30 | want: &PhevMessage{ 31 | Type: 0x6f, 32 | Length: 0x12, 33 | Register: 0xc0, 34 | Data: []byte{0x30, 0x30, 0x35, 0x32, 0x30, 0x32, 0x32, 0x30, 0x30, 0x30, 0x10, 0x1, 0x0}, 35 | Checksum: 0x3b, 36 | Xor: 0x3f, 37 | Original: []byte{0x6f, 0x10, 0x0, 0xc0, 0x30, 0x30, 0x35, 0x32, 0x30, 0x32, 0x32, 0x30, 0x30, 0x30, 0x10, 0x1, 0x0, 0x3b}, 38 | OriginalXored: []byte{0x50, 0x2f, 0x3f, 0xff, 0x0f, 0x0f, 0x0a, 0x0d, 0x0f, 0x0d, 0x0d, 0x0f, 0x0f, 0x0f, 0x2f, 0x3e, 0x3f, 0x04}, 39 | }, 40 | }, { 41 | in: "caa2a5a7a5a5a5a5dd", 42 | sk: &SecurityKey{keyMap: []byte{0xa5, 0xa5}}, 43 | want: &PhevMessage{ 44 | Type: 0x6f, 45 | Length: 0x9, 46 | Register: 0x2, 47 | Data: []byte{0x0, 0x0, 0x0, 0x0}, 48 | Checksum: 0x78, 49 | Xor: 0xa5, 50 | Original: []byte{0x6f, 0x7, 0x0, 0x2, 0x0, 0x0, 0x0, 0x0, 0x78}, 51 | OriginalXored: []byte{0xca, 0xa2, 0xa5, 0xa7, 0xa5, 0xa5, 0xa5, 0xa5, 0xdd}, 52 | }, 53 | }, { 54 | in: "3cf4f13360d4", 55 | sk: &SecurityKey{keyMap: []byte{0xf0, 0xa5}}, 56 | want: &PhevMessage{ 57 | Type: 0xcc, 58 | Length: 0x6, 59 | Register: 0xc3, 60 | Data: []byte{0x90}, 61 | Checksum: 0x24, 62 | Xor: 0xf0, 63 | Ack: Ack, 64 | Original: []byte{0xcc, 0x4, 0x1, 0xc3, 0x90, 0x24}, 65 | OriginalXored: []byte{0x3c, 0xf4, 0xf1, 0x33, 0x60, 0xd4}, 66 | }, 67 | }, { 68 | in: "4bf4f1c190a1", 69 | sk: &SecurityKey{keyMap: []byte{0xf0, 0xa5}}, 70 | want: &PhevMessage{ 71 | Type: 0xbb, 72 | Length: 0x6, 73 | Register: 0x31, 74 | Data: []byte{0x60}, 75 | Checksum: 0x51, 76 | Xor: 0xf0, 77 | Ack: Ack, 78 | Original: []byte{0xbb, 0x4, 0x1, 0x31, 0x60, 0x51}, 79 | OriginalXored: []byte{0x4b, 0xf4, 0xf1, 0xc1, 0x90, 0xa1}, 80 | }, 81 | }, { 82 | in: "9ff6f0f3f1e59301", 83 | sk: &SecurityKey{keyMap: []byte{0xf0, 0xa5}}, 84 | want: &PhevMessage{ 85 | Type: 0x6f, 86 | Length: 0x8, 87 | Register: 0x3, 88 | Data: []byte{0x1, 0x15, 0x63}, 89 | Checksum: 0xf1, 90 | Xor: 0xf0, 91 | Original: []byte{0x6f, 0x6, 0x0, 0x3, 0x1, 0x15, 0x63, 0xf1}, 92 | OriginalXored: []byte{0x9f, 0xf6, 0xf0, 0xf3, 0xf1, 0xe5, 0x93, 0x01}, 93 | }, 94 | }, 95 | } 96 | 97 | for _, test := range tests { 98 | t.Run(test.in, func(t *testing.T) { 99 | data, err := hex.DecodeString(test.in) 100 | if err != nil { 101 | t.Fatal(err) 102 | } 103 | p := &PhevMessage{} 104 | if err := p.DecodeFromBytes(data, test.sk); err != nil { 105 | t.Fatalf("DecodeFromBytes() unexpected error: %v", err) 106 | } 107 | p.Reg = nil // Skip reg test for now. 108 | if diff, eq := messagediff.PrettyDiff(test.want, p); !eq { 109 | t.Fatalf("DecodeFromBytes() diff=%s", diff) 110 | } 111 | 112 | outData := test.want.EncodeToBytes(test.sk) 113 | gotData := hex.EncodeToString(outData) 114 | if gotData != test.in { 115 | t.Fatalf("EncodeToBytes: Unexpected. got=%s want=%s", gotData, test.in) 116 | } 117 | }) 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /protocol/raw_test.go: -------------------------------------------------------------------------------- 1 | package protocol 2 | 3 | import ( 4 | "encoding/hex" 5 | "fmt" 6 | "testing" 7 | ) 8 | 9 | func hexCmp(got []byte, want string) string { 10 | gotS := hex.EncodeToString(got) 11 | if gotS != want { 12 | return fmt.Sprintf("got=%s want=%s", gotS, want) 13 | } 14 | return "" 15 | } 16 | 17 | func TestSecurityKey(t *testing.T) { 18 | testData, err := hex.DecodeString("5e0c0001becfe9adada5158b0181") 19 | if err != nil { 20 | t.Fatalf("hex.Decode(): %v", err) 21 | } 22 | 23 | sk := &SecurityKey{} 24 | sk.Update(testData) 25 | 26 | if got, want := sk.securityKey, byte(159); got != want { 27 | t.Fatalf("security_key got=%d want=%d", got, want) 28 | } 29 | if got, want := sk.keyMap[0], byte(246); got != want { 30 | t.Fatalf("keyMap[0] got=%d want=%d", got, want) 31 | } 32 | if got, want := sk.keyMap[255], byte(164); got != want { 33 | t.Fatalf("keyMap[0] got=%d want=%d", got, want) 34 | } 35 | } 36 | 37 | func TestXorMessage(t *testing.T) { 38 | tests := []struct { 39 | in, want string 40 | xor byte 41 | }{ 42 | { 43 | in: "d8b2b7a9b7b725", 44 | xor: 0xb7, 45 | want: "6f05001e000092", 46 | }, 47 | } 48 | 49 | for _, test := range tests { 50 | t.Run(test.in, func(t *testing.T) { 51 | in, err := hex.DecodeString(test.in) 52 | if err != nil { 53 | t.Fatal(err) 54 | } 55 | got := XorMessageWith(in, test.xor) 56 | if diff := hexCmp(got, test.want); diff != "" { 57 | t.Errorf(diff) 58 | } 59 | }) 60 | } 61 | } 62 | 63 | func TestValidateChecksum(t *testing.T) { 64 | tests := []struct { 65 | in string 66 | want bool 67 | }{ 68 | { 69 | in: "bb04016cf01c", 70 | want: true, 71 | }, { 72 | in: "f60400060303", 73 | want: true, 74 | }, { 75 | in: "f60400060304", 76 | want: false, 77 | }, 78 | } 79 | 80 | for _, test := range tests { 81 | t.Run(test.in, func(t *testing.T) { 82 | in, err := hex.DecodeString(test.in) 83 | if err != nil { 84 | t.Fatal(err) 85 | } 86 | if got, want := ValidateChecksum(in), test.want; got != want { 87 | t.Fatalf("got=%v want=%v", got, want) 88 | } 89 | }) 90 | } 91 | } 92 | func TestValidateAndDecodeMessage(t *testing.T) { 93 | tests := []struct { 94 | in, want, remaining string 95 | xor byte 96 | }{ 97 | { 98 | in: "06f4f0f6f3f306f4f0f6f3f3", 99 | want: "f60400060303", 100 | remaining: "06f4f0f6f3f3", 101 | xor: 0xf0, 102 | }, { 103 | in: "ff879094eda82091132d9091ece0a891906f6f93906f6f93c8", 104 | want: "6f1700047d38b00183bd00017c70380100ffff0300ffff0358", 105 | remaining: "", 106 | xor: 0x90, 107 | }, { 108 | in: "d8b2b7a9b7b725", 109 | want: "6f05001e000092", 110 | remaining: "", 111 | xor: 0xb7, 112 | }, { 113 | in: "4ab8bd95bc98", 114 | want: "f60401290024", 115 | remaining: "", 116 | xor: 0xbc, 117 | }, { 118 | in: "f20a000100000000000000fd", 119 | want: "f20a000100000000000000fd", 120 | remaining: "", 121 | xor: 0x00, 122 | }, { 123 | in: "502f3fff0f0f0a0d0f0d0d0f0f0f2f3e3f04", 124 | want: "6f1000c0303035323032323030301001003b", 125 | remaining: "", 126 | xor: 0x3f, 127 | }, { 128 | in: "3cf4f16e55e4", 129 | want: "cc04019ea514", 130 | remaining: "", 131 | xor: 0xf0, 132 | }, { 133 | in: "06f4f0f6f3f3", 134 | want: "f60400060303", 135 | remaining: "", 136 | xor: 0xf0, 137 | }, { 138 | in: "4bf4f19c00ec", 139 | want: "bb04016cf01c", 140 | remaining: "", 141 | xor: 0xf0, 142 | }, 143 | } 144 | 145 | for _, test := range tests { 146 | t.Run(test.in, func(t *testing.T) { 147 | in, err := hex.DecodeString(test.in) 148 | if err != nil { 149 | t.Fatal(err) 150 | } 151 | got, xor, gotRem := ValidateAndDecodeMessage(in) 152 | if gs := hex.EncodeToString(got); gs != test.want { 153 | t.Errorf("got=%s want=%s", gs, test.want) 154 | } 155 | if gs := hex.EncodeToString(gotRem); gs != test.remaining { 156 | t.Errorf("gotRem=%s want=%s", gs, test.remaining) 157 | } 158 | if xor != test.xor { 159 | t.Errorf("Xor got=%x want=%x", xor, test.xor) 160 | } 161 | }) 162 | } 163 | } 164 | -------------------------------------------------------------------------------- /lovelace.yaml: -------------------------------------------------------------------------------- 1 | cards: 2 | - type: horizontal-stack 3 | cards: 4 | - type: button 5 | tap_action: 6 | action: toggle 7 | entity: switch.phev_cool 8 | - type: button 9 | tap_action: 10 | action: toggle 11 | entity: switch.phev_heat 12 | - type: button 13 | tap_action: 14 | action: toggle 15 | entity: switch.phev_windscreen 16 | - type: horizontal-stack 17 | cards: 18 | - type: picture-elements 19 | elements: 20 | - type: state-icon 21 | entity: light.phev_park_lights 22 | style: 23 | top: 95% 24 | left: 30% 25 | - type: state-icon 26 | entity: light.phev_head_lights 27 | style: 28 | top: 5% 29 | left: 50% 30 | - type: state-icon 31 | entity: binary_sensor.phev_boot 32 | style: 33 | top: 90% 34 | left: 50% 35 | - type: state-icon 36 | entity: binary_sensor.phev_bonnet 37 | style: 38 | top: 17% 39 | left: 50% 40 | - type: state-icon 41 | entity: binary_sensor.phev_front_left_door 42 | icon: mdi:car-door 43 | style: 44 | top: 50% 45 | left: 7% 46 | - type: state-icon 47 | entity: binary_sensor.phev_front_right_door 48 | icon: mdi:car-door 49 | style: 50 | top: 50% 51 | left: 90% 52 | - type: state-icon 53 | entity: binary_sensor.phev_rear_left_door 54 | icon: mdi:car-door 55 | style: 56 | top: 65% 57 | left: 7% 58 | - type: state-icon 59 | entity: binary_sensor.phev_rear_right_door 60 | icon: mdi:car-door 61 | style: 62 | top: 65% 63 | left: 90% 64 | - type: state-icon 65 | entity: binary_sensor.phev_charger_connected 66 | style: 67 | top: 80% 68 | left: 90% 69 | - type: state-icon 70 | entity: binary_sensor.phev_locked 71 | style: 72 | top: 60% 73 | left: 50% 74 | image: https://ha.cactii.net/local/car-top-1.png 75 | - type: gauge 76 | tap_action: 77 | action: toggle 78 | entity: sensor.phev_battery 79 | unit: '%' 80 | - type: custom:button-card 81 | entity: binary_sensor.phev_charger_connected 82 | name: Charger 83 | aspect_ratio: 1/1.7 84 | tap_action: 85 | action: more-info 86 | entity: switch.phev_disable_charge_timer 87 | styles: 88 | grid: 89 | - position: relative 90 | custom_fields: 91 | notification: 92 | - background-color: | 93 | [[[ 94 | if (states['binary_sensor.phev_charging'].state == "on") 95 | return "green"; 96 | return "red"; 97 | ]]] 98 | - border-radius: 50% 99 | - position: absolute 100 | - left: 60% 101 | - top: 10% 102 | - height: 40px 103 | - width: 40px 104 | - font-size: 14px 105 | - line-height: 40px 106 | custom_fields: 107 | notification: > 108 | [[[ return 109 | Math.floor(states['sensor.phev_charge_remaining'].state) +'m']]] 110 | state: 111 | - value: 'on' 112 | icon: mdi:power-plug 113 | label: Plugged In 114 | - value: 'off' 115 | icon: mdi:power-plug-off 116 | label: Unplugged 117 | -------------------------------------------------------------------------------- /cmd/register.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2021 Ben Buxton 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | package cmd 18 | 19 | import ( 20 | "time" 21 | 22 | "github.com/buxtronix/phev2mqtt/client" 23 | "github.com/buxtronix/phev2mqtt/protocol" 24 | log "github.com/sirupsen/logrus" 25 | "github.com/spf13/cobra" 26 | ) 27 | 28 | // registerCmd represents the register command 29 | var registerCmd = &cobra.Command{ 30 | Use: "register", 31 | Short: "Register client with the car", 32 | Long: `Register phev2mqtt with the car. 33 | 34 | You will need to first put the car into registration mode, then run 35 | this command within 5 minutes. 36 | 37 | The car will register the MAC address that connects to it - typically the 38 | MAC address of the TCP client that ultimately connects to the car. If you 39 | are going via a NAT gateway, etc, then bear this in mind. 40 | 41 | `, 42 | Run: runRegister, 43 | } 44 | 45 | // unRegisterCmd represents the unregister command 46 | var unRegisterCmd = &cobra.Command{ 47 | Use: "unregister", 48 | Short: "Un register client from the car", 49 | Long: `Unregister this phev2mqtt instance from the car. 50 | 51 | The car will unregister the MAC address that connects to it - typically the 52 | MAC address of the TCP client that ultimately connects to the car. If you 53 | are going via a NAT gateway, etc, then bear this in mind. 54 | 55 | `, 56 | Run: runRegister, 57 | } 58 | 59 | func runRegister(cmd *cobra.Command, args []string) { 60 | var err error 61 | 62 | address, _ := cmd.Flags().GetString("address") 63 | cl, err := client.New(client.AddressOption(address)) 64 | if err != nil { 65 | panic(err) 66 | } 67 | 68 | if err := cl.Connect(); err != nil { 69 | panic(err) 70 | } 71 | 72 | if err := cl.Start(); err != nil { 73 | panic(err) 74 | } 75 | log.Infof("Client connected and started!") 76 | 77 | vinCh := make(chan string) 78 | 79 | go func() { 80 | for { 81 | select { 82 | case msg, ok := <-cl.Recv: 83 | if !ok { 84 | log.Errorf("Connection closed.") 85 | close(vinCh) 86 | return 87 | } 88 | switch msg.Type { 89 | case protocol.CmdInResp: 90 | if msg.Ack != protocol.Request { 91 | break 92 | } 93 | if reg, ok := msg.Reg.(*protocol.RegisterVIN); ok { 94 | vinCh <- reg.VIN 95 | } 96 | cl.Send <- &protocol.PhevMessage{ 97 | Type: protocol.CmdOutSend, 98 | Register: msg.Register, 99 | Ack: protocol.Ack, 100 | Xor: msg.Xor, 101 | Data: []byte{0x0}, 102 | } 103 | } 104 | } 105 | } 106 | }() 107 | 108 | vin, ok := <-vinCh 109 | if !ok { 110 | log.Errorf("Client closed before recieving VIN") 111 | return 112 | } 113 | 114 | reg := byte(0x10) 115 | if cmd.Use == "unregister" { 116 | log.Infof("Attempting to unregister from car (VIN: %s)...", vin) 117 | reg = 0x15 118 | } else { 119 | log.Infof("Attempting to register to car (VIN: %s)...", vin) 120 | } 121 | if err := cl.SetRegister(reg, []byte{0x1}); err != nil { 122 | log.Errorf("Failed to (un)register: %v", err) 123 | return 124 | } 125 | cl.Close() 126 | time.Sleep(time.Second) 127 | log.Infof("Success!") 128 | } 129 | 130 | func init() { 131 | clientCmd.AddCommand(registerCmd) 132 | clientCmd.AddCommand(unRegisterCmd) 133 | 134 | // Here you will define your flags and configuration settings. 135 | 136 | // Cobra supports Persistent Flags which will work for this command 137 | // and all subcommands, e.g.: 138 | // registerCmd.PersistentFlags().String("foo", "", "A help for foo") 139 | 140 | // Cobra supports local flags which will only run when this command 141 | // is called directly, e.g.: 142 | // registerCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") 143 | registerCmd.Flags().Duration("wait_duration", 10*time.Second, "How long to wait after connecting to car before sending registration command") 144 | unRegisterCmd.Flags().Duration("wait_duration", 10*time.Second, "How long to wait after connecting to car before sending registration command") 145 | } 146 | -------------------------------------------------------------------------------- /protocol/raw.go: -------------------------------------------------------------------------------- 1 | package protocol 2 | 3 | import ( 4 | "encoding/hex" 5 | log "github.com/sirupsen/logrus" 6 | "math/rand" 7 | ) 8 | 9 | type SecurityState int 10 | 11 | const ( 12 | SecurityEmpty = iota 13 | SecurityKeyProposed 14 | SecurityKeyAccepted 15 | ) 16 | 17 | // SecurityKey implements the algorithm for the session encoding/decoding 18 | // keys. 19 | type SecurityKey struct { 20 | State SecurityState 21 | proposedKey []byte 22 | securityKey byte 23 | keyMap []byte 24 | sNum, rNum byte 25 | } 26 | 27 | func (s *SecurityKey) GenerateProposal() []byte { 28 | s.proposedKey = make([]byte, 8) 29 | for i := 0; i < 8; i++ { 30 | s.proposedKey[i] = byte(rand.Intn(256)) 31 | } 32 | s.State = SecurityKeyProposed 33 | return s.proposedKey 34 | } 35 | 36 | func (s *SecurityKey) AcceptProposal() { 37 | s.Update(append([]byte{0x0, 0x0, 0x0, 0x0}, s.proposedKey...)) 38 | s.State = SecurityKeyAccepted 39 | } 40 | 41 | // Generate the security keys from the 0x5e/0x4e initialisation 42 | // packets. The payload for these packets runs through the below 43 | // algorithm which initially generates a security key from the data, 44 | // then from this security key a key map is generated, essentially 45 | // an array of session keys which are rotated through. 46 | func (s *SecurityKey) Update(packet []byte) { 47 | if len(packet) < 12 { 48 | s.keyMap = []byte{} // Clear security keys. 49 | s.securityKey = 0x0 50 | s.sNum = 0 51 | s.rNum = 0 52 | log.Debugf("%%PHEV_SEC_KEY_CLEAR%% Cleared security key") 53 | return 54 | } 55 | // Calculate security key from provided packet. 56 | result := (packet[4] & 0x8) >> 3 57 | result |= (packet[5] & 0x8) >> 2 58 | result |= (packet[6] & 0x8) >> 1 59 | result |= (packet[7] & 0x8) 60 | result |= (packet[8] & 0x8) << 1 61 | result |= (packet[9] & 0x8) << 2 62 | result |= (packet[10] & 0x8) << 3 63 | result |= (packet[11] & 0x8) << 4 64 | s.securityKey = byte(result) 65 | // From this key, generate the key map. 66 | s_key := int(s.securityKey) 67 | s.keyMap = make([]byte, 256) 68 | for i := 0; i < len(s.keyMap); i++ { 69 | s.keyMap[i] = byte(i) 70 | } 71 | 72 | index := 0 73 | for i := 0; i < 256; i++ { 74 | index += int(s.keyMap[i]) 75 | index += s_key 76 | index %= 256 77 | temp := s.keyMap[i] 78 | s.keyMap[i] = s.keyMap[index] 79 | s.keyMap[index] = temp 80 | } 81 | // Reset the keymap send/receive indices. 82 | s.sNum = 0 83 | s.rNum = 0 84 | log.Debugf("%%PHEV_SEC_KEY_UPDATE%% Updated security key") 85 | } 86 | 87 | // Fetch and optionally increment the index for the received 88 | // key (sent from the car). The key is incremented after a packet 89 | // of type 0x6f is sent from the car. Otherwise the same key index 90 | // is used. 91 | // The returned value is XORed with the raw packet from the car before 92 | // decoding it. 93 | func (s *SecurityKey) RKey(increment bool) byte { 94 | if len(s.keyMap) == 0 { 95 | log.Tracef("r_key=empty") 96 | return 0 97 | } 98 | ret := s.rNum 99 | if increment { 100 | s.rNum++ 101 | } 102 | log.Tracef("r_key=%d", s.keyMap[ret]) 103 | return s.keyMap[ret] 104 | } 105 | 106 | // Fetch and optionally increment the index for the send 107 | // key (sent to the car). The key is incremented after a packet 108 | // of type 0xf6 is sent to the car. Otherwise the same key index 109 | // is used. 110 | // The returned value is XORed with the raw packet before sending 111 | // it to the car. 112 | func (s *SecurityKey) SKey(increment bool) byte { 113 | if len(s.keyMap) == 0 { 114 | log.Tracef("s_key=empty") 115 | return 0 116 | } 117 | ret := s.sNum 118 | if increment { 119 | s.sNum++ 120 | } 121 | log.Tracef("s_key=%d", s.keyMap[ret]) 122 | return s.keyMap[ret] 123 | } 124 | 125 | func XorMessageWith(message []byte, xor byte) []byte { 126 | msg := make([]byte, len(message)) 127 | for i := range message { 128 | msg[i] = message[i] ^ xor 129 | } 130 | return msg 131 | } 132 | 133 | func Checksum(message []byte) byte { 134 | length := message[1] + 2 135 | 136 | b := byte(0) 137 | for i := byte(0); ; i++ { 138 | if i >= length-1 { 139 | break 140 | } 141 | b = (byte)(message[i] + b) 142 | } 143 | return b 144 | } 145 | 146 | func ValidateChecksum(message []byte) bool { 147 | length := int(message[1]) + 2 148 | if len(message) < length { 149 | return false 150 | } 151 | wantSum := message[length-1] 152 | 153 | return Checksum(message) == wantSum 154 | } 155 | 156 | // Validate and decode message. Returns the decoded/validated message, 157 | // plus any trailing data. 158 | func ValidateAndDecodeMessage(message []byte) ([]byte, byte, []byte) { 159 | if len(message) < 4 { 160 | log.Debugf("Short msg\n") 161 | return nil, 0, nil 162 | } 163 | xor := message[2] 164 | msg := XorMessageWith(message, xor) 165 | if !ValidateChecksum(msg) { 166 | xor ^= 1 167 | msg = XorMessageWith(message, xor) 168 | if !ValidateChecksum(msg) { 169 | log.Debugf("Bad sum for (%s)\n", hex.EncodeToString(message)) 170 | return nil, 0, nil 171 | } 172 | } 173 | length := msg[1] + 2 174 | if len(message) > int(length) { 175 | return msg[:length], xor, message[length:] 176 | } 177 | return msg[:length], xor, nil 178 | } 179 | -------------------------------------------------------------------------------- /cmd/emulator.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2021 Ben Buxton 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | package cmd 18 | 19 | import ( 20 | "encoding/hex" 21 | "fmt" 22 | "github.com/buxtronix/phev2mqtt/emulator" 23 | "github.com/spf13/cobra" 24 | "strings" 25 | 26 | mqtt "github.com/eclipse/paho.mqtt.golang" 27 | log "github.com/sirupsen/logrus" 28 | ) 29 | 30 | // emulatorCmd represents the emulate command 31 | var emulatorCmd = &cobra.Command{ 32 | Use: "emulator", 33 | Short: "Emulate a car, to enable app testing", 34 | Long: `Starts up a service that emulates a car. 35 | 36 | If --mqtt_server is specified, it will connect to the given 37 | MQTT server, and allow you to send registers to the client, 38 | at topic phev/emu/set/register/ 39 | `, 40 | RunE: func(cmd *cobra.Command, args []string) error { 41 | emu := &emu{} 42 | return emu.Run(cmd, args) 43 | }, 44 | } 45 | 46 | type emu struct { 47 | client mqtt.Client 48 | options *mqtt.ClientOptions 49 | mqttData map[string]string 50 | 51 | car *emulator.Car 52 | prefix string 53 | } 54 | 55 | func (e *emu) topic(topic string) string { 56 | return fmt.Sprintf("%s%s", e.prefix, topic) 57 | } 58 | 59 | func (e *emu) Run(cmd *cobra.Command, args []string) error { 60 | 61 | mqttServer, _ := cmd.Flags().GetString("mqtt_server") 62 | mqttUsername, _ := cmd.Flags().GetString("mqtt_username") 63 | mqttPassword, _ := cmd.Flags().GetString("mqtt_password") 64 | e.prefix, _ = cmd.Flags().GetString("mqtt_topic_prefix") 65 | 66 | if mqttServer != "" { 67 | e.options = mqtt.NewClientOptions(). 68 | AddBroker(mqttServer). 69 | SetClientID("phev2mqtt_emu"). 70 | SetUsername(mqttUsername). 71 | SetPassword(mqttPassword). 72 | SetAutoReconnect(true). 73 | SetDefaultPublishHandler(e.handleIncomingMqtt). 74 | SetWill(e.topic("/available"), "offline", 0, true) 75 | 76 | e.client = mqtt.NewClient(e.options) 77 | if token := e.client.Connect(); token.Wait() && token.Error() != nil { 78 | return token.Error() 79 | } 80 | if token := e.client.Subscribe(e.topic("/set/#"), 0, nil); token.Wait() && token.Error() != nil { 81 | return token.Error() 82 | } 83 | 84 | } 85 | e.mqttData = map[string]string{} 86 | 87 | return e.manageCar(cmd) 88 | } 89 | 90 | func (e *emu) publish(topic, payload string) { 91 | if e.client == nil { 92 | return 93 | } 94 | if cache := e.mqttData[topic]; cache != payload { 95 | e.client.Publish(e.topic(topic), 0, false, payload) 96 | e.mqttData[topic] = payload 97 | } 98 | } 99 | 100 | func (e *emu) handleIncomingMqtt(client mqtt.Client, msg mqtt.Message) { 101 | topicParts := strings.Split(msg.Topic(), "/") 102 | log.Infof("Topic got=%s want=%s", msg.Topic(), e.topic("/set/register/")) 103 | switch { 104 | case strings.HasPrefix(msg.Topic(), e.topic("/set/register/")): 105 | if len(topicParts) != 5 { 106 | log.Infof("Bad topic format [%s]", msg.Topic()) 107 | return 108 | } 109 | register, err := hex.DecodeString(topicParts[4]) 110 | if err != nil { 111 | log.Infof("Bad register in topic [%s]: %v", msg.Topic(), err) 112 | return 113 | } 114 | data, err := hex.DecodeString(string(msg.Payload())) 115 | if err != nil { 116 | log.Infof("Bad payload [%s]: %v", msg.Payload(), err) 117 | return 118 | } 119 | if err := e.car.SetRegister(register[0], data); err != nil { 120 | log.Infof("Error setting register %02x: %v", register[0], err) 121 | return 122 | } 123 | } 124 | } 125 | 126 | func (e *emu) manageCar(cmd *cobra.Command) error { 127 | var err error 128 | address, _ := cmd.Flags().GetString("address") 129 | e.car, err = emulator.NewCar(emulator.AddressOption(address)) 130 | if err != nil { 131 | return err 132 | } 133 | if err := e.car.Begin(); err != nil { 134 | return err 135 | } 136 | e.publish("/available", "online") 137 | select {} 138 | } 139 | 140 | func init() { 141 | rootCmd.AddCommand(emulatorCmd) 142 | 143 | // Here you will define your flags and configuration settings. 144 | 145 | // Cobra supports Persistent Flags which will work for this command 146 | // and all subcommands, e.g.: 147 | // watchCmd.PersistentFlags().String("foo", "", "A help for foo") 148 | 149 | // Cobra supports local flags which will only run when this command 150 | // is called directly, e.g.: 151 | emulatorCmd.PersistentFlags().String("address", ":8080", "Address to listen on") 152 | emulatorCmd.Flags().String("mqtt_server", "tcp://127.0.0.1:1883", "Address of MQTT server") 153 | emulatorCmd.Flags().String("mqtt_username", "", "Username to login to MQTT server") 154 | emulatorCmd.Flags().String("mqtt_password", "", "Password to login to MQTT server") 155 | emulatorCmd.Flags().String("mqtt_topic_prefix", "phev/emu", "Prefix for MQTT topics") 156 | } 157 | -------------------------------------------------------------------------------- /emulator/car.go: -------------------------------------------------------------------------------- 1 | package emulator 2 | 3 | import ( 4 | "encoding/hex" 5 | "fmt" 6 | "github.com/buxtronix/phev2mqtt/protocol" 7 | log "github.com/sirupsen/logrus" 8 | "golang.org/x/sync/errgroup" 9 | "math/rand" 10 | "net" 11 | "time" 12 | ) 13 | 14 | const listenAddress = ":8080" 15 | 16 | // A Car represents a virtual emulated car. 17 | type Car struct { 18 | // Registers are the current registers and settings for Car. 19 | Registers []protocol.Register 20 | // Settings are the vehicle settings. 21 | Settings *protocol.Settings 22 | address string 23 | connections []*Connection 24 | } 25 | 26 | // Begin starts the emulator. 27 | func (c *Car) Begin() error { 28 | l, err := net.Listen("tcp4", c.address) 29 | if err != nil { 30 | return err 31 | } 32 | rand.Seed(time.Now().Unix()) 33 | 34 | go func() { 35 | defer l.Close() 36 | for { 37 | conn, err := l.Accept() 38 | if err != nil { 39 | log.Errorf("Accept() error: %v") 40 | return 41 | } 42 | svc := NewConnection(conn, c) 43 | c.connections = append(c.connections, svc) 44 | 45 | go svc.Start() 46 | } 47 | }() 48 | log.Debugf("%%PHEV_EMULATOR_START%% Started PHEV emulator, address=%s", c.address) 49 | return nil 50 | } 51 | 52 | // SetRegister sends a register to client. 53 | func (c *Car) SetRegister(register byte, value []byte) error { 54 | g := new(errgroup.Group) 55 | for _, conn := range c.connections { 56 | g.Go(func() error { 57 | timer := time.After(10 * time.Second) 58 | l := conn.AddListener() 59 | defer conn.RemoveListener(l) 60 | SETREG: 61 | conn.Send <- protocol.NewMessage(protocol.CmdInResp, register, false, value) 62 | for { 63 | select { 64 | case <-timer: 65 | return fmt.Errorf("timed out attempting to set register %02x", register) 66 | case msg, ok := <-l.C: 67 | if !ok { 68 | return fmt.Errorf("listener channel closed") 69 | } 70 | if msg.Type == protocol.CmdInBadEncoding { 71 | goto SETREG 72 | } 73 | if msg.Type == protocol.CmdOutSend && msg.Ack == protocol.Ack && msg.Register == register { 74 | return nil 75 | } 76 | } 77 | } 78 | }) 79 | } 80 | return g.Wait() 81 | } 82 | 83 | // An Option configures the emulator. 84 | type Option func(c *Car) 85 | 86 | // AddressOption configures the address to the Phev. 87 | func AddressOption(address string) func(*Car) { 88 | return func(c *Car) { 89 | c.address = address 90 | } 91 | } 92 | 93 | // NewCar returns a new Car. You get a Car! Everyone gets a Car! 94 | func NewCar(opts ...Option) (*Car, error) { 95 | c := &Car{ 96 | Registers: defaultRegisters, 97 | Settings: &protocol.Settings{}, 98 | } 99 | for _, o := range opts { 100 | o(c) 101 | } 102 | for _, s := range defaultSettings { 103 | setting, err := hex.DecodeString(s) 104 | if err != nil { 105 | return nil, err 106 | } 107 | if err := c.Settings.FromRegister(setting); err != nil { 108 | return nil, err 109 | } 110 | } 111 | return c, nil 112 | } 113 | 114 | // Returns a generic register with the provided value. 115 | func mustRegister(register byte, value string) protocol.Register { 116 | v, err := hex.DecodeString(value) 117 | if err != nil { 118 | panic(err) 119 | } 120 | return &protocol.RegisterGeneric{Reg: register, Value: v} 121 | } 122 | 123 | var defaultRegisters = []protocol.Register{ 124 | mustRegister(0x06, "002D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D0100"), 125 | mustRegister(0x7, "00"), 126 | mustRegister(0x0b, "00"), 127 | mustRegister(0x0c, "01"), 128 | mustRegister(0x0d, "04"), 129 | mustRegister(0x0f, "00"), 130 | mustRegister(0x10, "000000"), 131 | mustRegister(0x11, "00"), 132 | mustRegister(0x12, "160a0712391805"), 133 | mustRegister(0x13, "00"), 134 | mustRegister(0x14, "00000000000000"), 135 | // &protocol.RegisterVIN{VIN: "JMFXDGG2WJZ00048", Registrations: 2}, 136 | mustRegister(0x15, "032E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E0100"), 137 | mustRegister(0x17, "01"), 138 | mustRegister(0x1a, "0300000000"), 139 | mustRegister(0x1b, "11"), 140 | mustRegister(0x1c, "03"), 141 | mustRegister(0x1d, "06000000"), 142 | mustRegister(0x1e, "0000"), 143 | mustRegister(0x1f, "00ffff"), 144 | mustRegister(0x21, "00"), 145 | mustRegister(0x22, "000000000000"), 146 | mustRegister(0x23, "0000000202"), 147 | mustRegister(0x24, "02000000000000000000"), 148 | mustRegister(0x25, "0e00ff"), 149 | mustRegister(0x26, "00"), 150 | mustRegister(0x27, "00"), 151 | mustRegister(0x28, "00"), 152 | mustRegister(0x29, "000200"), 153 | mustRegister(0x2C, "00"), 154 | mustRegister(0xC0, "30303532303232303030110000"), 155 | mustRegister(0x01, "0100"), 156 | mustRegister(0x02, "0100"), 157 | mustRegister(0x3, "011563"), 158 | mustRegister(0x04, "7d38b00183bd00017c70380100ffff0300ffff03"), 159 | mustRegister(0x5, "0100fe0700fe0700fe0700fe0700fe07"), 160 | mustRegister(0x06, "002D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D2D0100"), 161 | // &protocol.RegisterVIN{VIN: "JMFXDGG2WJZ00048", Registrations: 2}, 162 | mustRegister(0x15, "032E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E2E0100"), 163 | mustRegister(0x2A, "00"), 164 | mustRegister(0x2C, "00"), 165 | mustRegister(0x3, "011563"), 166 | &protocol.RegisterBatteryWarning{Warning: 0}, 167 | &protocol.RegisterWIFISSID{SSID: "REMOTEc0ffee"}, 168 | } 169 | 170 | var defaultSettings = []string{ 171 | "023a003b003c0000", 172 | "02e201e301640e00", 173 | "02e501a61ea71e00", 174 | "026b0e2c002d0000", 175 | "022e006f00300000", 176 | "0231007206730600", 177 | "02b4003506360e00", 178 | "02370e3806390000", 179 | "023a003b003c0000", 180 | "024106420603fe00", 181 | "02c41e850e861e00", 182 | "02473ec81e093f00", 183 | "02ca018bfe4c4300", 184 | "024d1e0e064f0600", 185 | "0210121106d20100", 186 | "02d301d401551e00", 187 | "02161ed701d80100", 188 | "0219061a23db0100", 189 | "02dc015d065e0600", 190 | "021f00600ee10100", 191 | "02e801e9016a3e00", 192 | } 193 | -------------------------------------------------------------------------------- /cmd/pcap.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2021 Ben Buxton 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | 18 | //go:build pcap 19 | 20 | package cmd 21 | 22 | import ( 23 | "encoding/hex" 24 | "fmt" 25 | "net" 26 | "strings" 27 | "time" 28 | 29 | "github.com/buxtronix/phev2mqtt/protocol" 30 | "github.com/google/gopacket" 31 | "github.com/google/gopacket/layers" 32 | "github.com/google/gopacket/pcap" 33 | log "github.com/sirupsen/logrus" 34 | "github.com/spf13/cobra" 35 | ) 36 | 37 | // pcapCmd represents the pcap command 38 | var pcapCmd = &cobra.Command{ 39 | Use: "pcap", 40 | Short: "Decode packets from a PCAP traffic dump", 41 | Long: `Reads packets from a PCAP file generated by a packet sniffer 42 | such as Wireshark. 43 | 44 | The decoder filters TCP packets to and from port 8080. 45 | 46 | This can also read files from a TCP connection. Specify 47 | "tcp:
:". This can be useful for realtime monitoring 48 | via Android (https://wladimir-tm4pda.github.io/porting/tcpdump.html) 49 | `, 50 | Args: cobra.ExactArgs(1), 51 | Run: func(cmd *cobra.Command, args []string) { 52 | var handle *pcap.Handle 53 | var err error 54 | if parts := strings.Split(args[0], ":"); len(parts) == 3 && parts[0] == "tcp" { 55 | conn, err := net.Dial("tcp", fmt.Sprintf("%s:%s", parts[1], parts[2])) 56 | if err != nil { 57 | log.Fatal(err) 58 | } 59 | if tcpconn, ok := conn.(*net.TCPConn); ok { 60 | if tc, err := tcpconn.File(); err == nil { 61 | handle, err = pcap.OpenOfflineFile(tc) 62 | if err != nil { 63 | log.Fatal(err) 64 | } 65 | } 66 | } 67 | } else { 68 | handle, err = pcap.OpenOffline(args[0]) 69 | } 70 | if err != nil { 71 | log.Fatal(err) 72 | } 73 | defer handle.Close() 74 | securityKey = &protocol.SecurityKey{} 75 | pings, _ = cmd.Flags().GetBool("pings") 76 | 77 | packetSource := gopacket.NewPacketSource(handle, handle.LinkType()) 78 | var currentTime time.Time 79 | pNum := 0 80 | for packet := range packetSource.Packets() { 81 | if m := packet.Metadata(); m != nil { 82 | if pNum > 0 { 83 | if r, _ := cmd.Flags().GetBool("latency"); r { 84 | time.Sleep(m.CaptureInfo.Timestamp.Sub(currentTime)) 85 | } 86 | currentTime = m.CaptureInfo.Timestamp 87 | } else { 88 | currentTime = m.CaptureInfo.Timestamp 89 | } 90 | } 91 | pNum += 1 92 | decodePacket(cmd, packet) 93 | } 94 | }, 95 | } 96 | 97 | func decodePacket(cmd *cobra.Command, packet gopacket.Packet) { 98 | dir := "?" 99 | tcpLayer := packet.Layer(layers.LayerTypeTCP) 100 | if tcpLayer != nil { 101 | tcp, _ := tcpLayer.(*layers.TCP) 102 | if tcp.SrcPort == 8080 { 103 | dir = "in " 104 | } else if tcp.DstPort == 8080 { 105 | dir = "out " 106 | } 107 | if tcp.SYN && tcp.ACK { 108 | log.Infof("TCP-SYN-ACK\n") 109 | } 110 | if tcp.FIN { 111 | log.Infof("TCP-FIN\n") 112 | } 113 | if tcp.RST { 114 | log.Infof("TCP-RST\n") 115 | } 116 | } 117 | 118 | d, _ := cmd.Flags().GetString("direction") 119 | if dir == "in " && d == "out" { 120 | return 121 | } 122 | if dir == "out " && d == "in" { 123 | return 124 | } 125 | 126 | al := packet.ApplicationLayer() 127 | if al != nil { 128 | processPayload(cmd, al.Payload(), dir) 129 | } 130 | 131 | if err := packet.ErrorLayer(); err != nil { 132 | log.Errorf("error decoding packet:", err) 133 | } 134 | } 135 | 136 | func processPayload(cmd *cobra.Command, data []byte, dir string) { 137 | log.Tracef("%%PHEV_PCAP_RAW_%s%%: %s\n", strings.ToUpper(dir), hex.EncodeToString(data)) 138 | msgs := protocol.NewFromBytes(data, securityKey) 139 | for _, msg := range msgs { 140 | if r, _ := cmd.Flags().GetBool("registers"); r { 141 | handleRegisters(msg) 142 | return 143 | } 144 | if !pings && (msg.Type == protocol.CmdOutPingReq || msg.Type == protocol.CmdInPingResp) { 145 | return 146 | } 147 | log.Infof("%s [%02x] %s", dir, msg.Xor, msg.ShortForm()) 148 | } 149 | } 150 | 151 | var regs = map[byte]string{} 152 | 153 | var pings bool 154 | 155 | func handleRegisters(m *protocol.PhevMessage) { 156 | if m.Type == protocol.CmdInResp { 157 | data := hex.EncodeToString(m.Data) 158 | if d := regs[m.Register]; d != data { 159 | if m.Reg != nil { 160 | log.Infof("UPDATEREG 0x%02x: %s -> %s (%s)\n", m.Register, d, data, m.Reg.String()) 161 | } else { 162 | log.Infof("UPDATEREG 0x%02x: %s -> %s\n", m.Register, d, data) 163 | } 164 | regs[m.Register] = data 165 | } 166 | } 167 | } 168 | 169 | func init() { 170 | decodeCmd.AddCommand(pcapCmd) 171 | 172 | // Here you will define your flags and configuration settings. 173 | 174 | // Cobra supports Persistent Flags which will work for this command 175 | // and all subcommands, e.g.: 176 | // pcapCmd.PersistentFlags().String("foo", "", "A help for foo") 177 | 178 | // Cobra supports local flags which will only run when this command 179 | // is called directly, e.g.: 180 | // pcapCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") 181 | pcapCmd.Flags().StringP("direction", "d", "both", "Direction to decode") 182 | pcapCmd.Flags().BoolP("latency", "l", false, "Replay with original network latency") 183 | pcapCmd.Flags().BoolP("registers", "R", false, "Show register updates") 184 | pcapCmd.Flags().BoolP("pings", "P", false, "Show ping requests and responses") 185 | } 186 | -------------------------------------------------------------------------------- /client/client.go: -------------------------------------------------------------------------------- 1 | // Package client implements a client for communicating with a Mitsubishi 2 | // Outlander Phev. 3 | package client 4 | 5 | import ( 6 | "encoding/hex" 7 | "fmt" 8 | log "github.com/sirupsen/logrus" 9 | "net" 10 | "sync" 11 | "time" 12 | 13 | "github.com/buxtronix/phev2mqtt/protocol" 14 | ) 15 | 16 | const DefaultAddress = "192.168.8.46:8080" 17 | 18 | // A Listener is for communicating messages from the vehicle to 19 | // interested clients. 20 | type Listener struct { 21 | // C has received messages. 22 | C chan *protocol.PhevMessage 23 | stop bool 24 | } 25 | 26 | func (l *Listener) Start() { 27 | l.stop = false 28 | l.C = make(chan *protocol.PhevMessage, 5) 29 | } 30 | 31 | func (l *Listener) Stop() { 32 | l.stop = true 33 | } 34 | 35 | func (l *Listener) Send(m *protocol.PhevMessage) { 36 | select { 37 | case l.C <- m: 38 | default: 39 | log.Debug("%PHEV_RECV_LISTENER% message not sent") 40 | } 41 | } 42 | 43 | func (l *Listener) ProcessStop() bool { 44 | if l.stop { 45 | close(l.C) 46 | l.stop = false 47 | return true 48 | } 49 | return false 50 | } 51 | 52 | type ModelYear int64 53 | 54 | const ( 55 | ModelYearUnknown ModelYear = iota 56 | ModelYear14 57 | ModelYear18 58 | ModelYear24 59 | ) 60 | 61 | // A Client is a TCP client to a Phev. 62 | type Client struct { 63 | // Recv is a channel where incoming messages from the Phev are sent. 64 | Recv chan *protocol.PhevMessage 65 | // Send is a channel to send messages to the Phev. 66 | Send chan *protocol.PhevMessage 67 | 68 | // Settings are settings for the car. 69 | Settings *protocol.Settings 70 | 71 | listeners []*Listener 72 | lMu sync.Mutex 73 | 74 | address string 75 | conn net.Conn 76 | lastRx time.Time 77 | started chan struct{} 78 | 79 | key *protocol.SecurityKey 80 | 81 | // Keep track of the model year so we can use the correct registers 82 | ModelYear ModelYear 83 | 84 | closed bool 85 | } 86 | 87 | // An Option configures the client. 88 | type Option func(c *Client) 89 | 90 | // AddressOption configures the address to the Phev. 91 | func AddressOption(address string) func(*Client) { 92 | return func(c *Client) { 93 | c.address = address 94 | } 95 | } 96 | 97 | // New returns a new client, not yet connected. 98 | func New(opts ...Option) (*Client, error) { 99 | cl := &Client{ 100 | Recv: make(chan *protocol.PhevMessage, 5), 101 | Send: make(chan *protocol.PhevMessage, 5), 102 | Settings: &protocol.Settings{}, 103 | started: make(chan struct{}, 2), 104 | listeners: []*Listener{}, 105 | address: DefaultAddress, 106 | key: &protocol.SecurityKey{}, 107 | ModelYear: ModelYearUnknown, 108 | } 109 | for _, o := range opts { 110 | o(cl) 111 | } 112 | return cl, nil 113 | } 114 | 115 | // Create and return a new Listener. 116 | func (c *Client) AddListener() *Listener { 117 | c.lMu.Lock() 118 | defer c.lMu.Unlock() 119 | l := &Listener{} 120 | l.Start() 121 | c.listeners = append(c.listeners, l) 122 | return l 123 | } 124 | 125 | func (c *Client) RemoveListener(l *Listener) { 126 | newL := []*Listener{} 127 | c.lMu.Lock() 128 | defer c.lMu.Unlock() 129 | for _, lis := range c.listeners { 130 | if lis != l { 131 | newL = append(newL, lis) 132 | } 133 | } 134 | c.listeners = newL 135 | } 136 | 137 | // Close closes the client. 138 | func (c *Client) Close() error { 139 | c.closed = true 140 | if c.conn == nil { 141 | return nil 142 | } 143 | return c.conn.Close() 144 | } 145 | 146 | // Connect connects to the Phev. 147 | func (c *Client) Connect() error { 148 | conn, err := net.Dial("tcp", c.address) 149 | if err != nil { 150 | return err 151 | } 152 | log.Info("%PHEV_TCP_CONNECTED%") 153 | c.closed = false 154 | c.conn = conn 155 | go c.reader() 156 | go c.writer() 157 | go c.manage() 158 | go c.pinger() 159 | 160 | return nil 161 | } 162 | 163 | var startTimeout = 20 * time.Second 164 | 165 | // Start waits for the client to start. 166 | func (c *Client) Start() error { 167 | log.Debug("%%PHEV_START_AWAIT%%") 168 | startTimer := time.After(startTimeout) 169 | for { 170 | select { 171 | case _, ok := <-c.started: 172 | if !ok { 173 | log.Debug("%%PHEV_START_CLOSED%%") 174 | return fmt.Errorf("receiver closed before getting start request") 175 | } 176 | log.Debug("%%PHEV_START_DONE%%") 177 | case <-startTimer: 178 | log.Debug("%%PHEV_START_TIMEOUT%%") 179 | return fmt.Errorf("timed out waiting for start") 180 | } 181 | return nil 182 | } 183 | } 184 | 185 | // SetRegister sets a register on the car. 186 | func (c *Client) SetRegister(register byte, value []byte) error { 187 | setRegister := func(xor byte) { 188 | c.Send <- &protocol.PhevMessage{ 189 | Type: protocol.CmdOutSend, 190 | Ack: protocol.Request, 191 | Register: register, 192 | Data: value, 193 | Xor: xor, 194 | } 195 | } 196 | xor := byte(0) 197 | timer := time.After(10 * time.Second) 198 | l := c.AddListener() 199 | defer c.RemoveListener(l) 200 | SETREG: 201 | setRegister(xor) 202 | for { 203 | select { 204 | case <-timer: 205 | return fmt.Errorf("timed out attempting to set register %02x", register) 206 | case msg, ok := <-l.C: 207 | if !ok { 208 | return fmt.Errorf("listener channel closed") 209 | } 210 | if msg.Type == protocol.CmdInBadEncoding { 211 | xor = msg.Data[0] 212 | goto SETREG 213 | } 214 | if msg.Type == protocol.CmdInResp && msg.Ack == protocol.Ack && msg.Register == register { 215 | return nil 216 | } 217 | 218 | } 219 | } 220 | } 221 | 222 | func (c *Client) nextRecvMsg(deadline time.Time) (*protocol.PhevMessage, error) { 223 | timer := time.After(deadline.Sub(time.Now())) 224 | for { 225 | select { 226 | case <-timer: 227 | return nil, fmt.Errorf("timed out waiting for message") 228 | case m, ok := <-c.Recv: 229 | if !ok { 230 | return nil, fmt.Errorf("error: receive channel closed") 231 | } 232 | return m, nil 233 | } 234 | } 235 | } 236 | 237 | // Sends periodic pings to the car. 238 | func (c *Client) pinger() { 239 | pingSeq := byte(0xa) 240 | ticker := time.NewTicker(200 * time.Millisecond) 241 | defer ticker.Stop() 242 | for t := range ticker.C { 243 | switch { 244 | case c.closed: 245 | return 246 | case t.Sub(c.lastRx) < 500*time.Millisecond: 247 | continue 248 | } 249 | c.Send <- protocol.NewPingRequestMessage(pingSeq) 250 | pingSeq++ 251 | if pingSeq > 0x63 { 252 | pingSeq = 0 253 | } 254 | } 255 | } 256 | 257 | // manages the connection, handling control messages. 258 | func (c *Client) manage() { 259 | ml := c.AddListener() 260 | defer ml.Stop() 261 | for m := range ml.C { 262 | switch m.Type { 263 | case protocol.CmdInResp: 264 | if m.Ack == protocol.Request && m.Register == protocol.SettingsRegister { 265 | c.Settings.FromRegister(m.Data) 266 | } 267 | case protocol.CmdInStartResp: 268 | c.Send <- protocol.NewPingRequestMessage(0xa) 269 | case protocol.CmdInMy24StartReq: 270 | c.ModelYear = ModelYear24 271 | c.Send <- &protocol.PhevMessage{ 272 | Type: protocol.CmdOutMy24StartResp, 273 | Register: 0x1, 274 | Ack: protocol.Ack, 275 | Xor: m.Xor, 276 | Data: []byte{0x0}, 277 | } 278 | log.Debug("%%PHEV_START24_RECV%%") 279 | c.started <- struct{}{} 280 | case protocol.CmdInMy18StartReq: 281 | c.ModelYear = ModelYear18 282 | c.Send <- &protocol.PhevMessage{ 283 | Type: protocol.CmdOutMy18StartResp, 284 | Register: 0x1, 285 | Ack: protocol.Ack, 286 | Xor: m.Xor, 287 | Data: []byte{0x0}, 288 | } 289 | log.Debug("%%PHEV_START18_RECV%%") 290 | c.started <- struct{}{} 291 | case protocol.CmdInMy14StartReq: 292 | c.ModelYear = ModelYear14 293 | c.Send <- &protocol.PhevMessage{ 294 | Type: protocol.CmdOutMy14StartResp, 295 | Register: 0x1, 296 | Ack: protocol.Ack, 297 | Xor: m.Xor, 298 | Data: []byte{0x0}, 299 | } 300 | log.Debug("%%PHEV_START14_RECV%%") 301 | c.started <- struct{}{} 302 | } 303 | } 304 | close(c.started) 305 | log.Debug("%PHEV_MANAGER_END%%") 306 | } 307 | 308 | func (c *Client) reader() { 309 | for { 310 | c.conn.(*net.TCPConn).SetReadDeadline(time.Now().Add(30 * time.Second)) 311 | data := make([]byte, 4096) 312 | n, err := c.conn.Read(data) 313 | if err != nil { 314 | if !c.closed { 315 | log.Debug("%%PHEV_TCP_READER_ERROR%%: ", err) 316 | } 317 | log.Debug("%PHEV_TCP_READER_CLOSE%") 318 | c.Close() 319 | close(c.Recv) 320 | c.lMu.Lock() 321 | for _, l := range c.listeners { 322 | l.Stop() 323 | } 324 | c.lMu.Unlock() 325 | return 326 | } 327 | c.lastRx = time.Now() 328 | log.Tracef("%%PHEV_TCP_RECV_DATA%%: %s", hex.EncodeToString(data[:n])) 329 | messages := protocol.NewFromBytes(data[:n], c.key) 330 | for _, m := range messages { 331 | log.Debugf("%%PHEV_TCP_RECV_MSG%%: [%02x] %s", m.Xor, m.ShortForm()) 332 | c.lMu.Lock() 333 | for _, l := range c.listeners { 334 | l.Send(m) 335 | } 336 | c.lMu.Unlock() 337 | c.Recv <- m 338 | } 339 | } 340 | } 341 | 342 | func (c *Client) writer() { 343 | for { 344 | select { 345 | case msg, ok := <-c.Send: 346 | if !ok { 347 | log.Debug("%PHEV_TCP_WRITER_CLOSE%") 348 | c.Close() 349 | return 350 | } 351 | msg.Xor = 0 352 | data := msg.EncodeToBytes(c.key) 353 | log.Debugf("%%PHEV_TCP_SEND_MSG%%: [%02x] %s", msg.Xor, msg.ShortForm()) 354 | log.Tracef("%%PHEV_TCP_SEND_DATA%%: %s", hex.EncodeToString(data)) 355 | c.conn.(*net.TCPConn).SetWriteDeadline(time.Now().Add(15 * time.Second)) 356 | if _, err := c.conn.Write(data); err != nil { 357 | if !c.closed { 358 | log.Errorf("%%PHEV_TCP_WRITER_ERROR%%: %v", err) 359 | } 360 | log.Debug("%PHEV_TCP_WRITER_CLOSE%") 361 | c.Close() 362 | return 363 | } 364 | } 365 | } 366 | } 367 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # phev2mqtt - Mitsubishi Outlander PHEV to MQTT gateway 2 | 3 | Utility to interact with a Mitsubishi Outlander PHEV via the Wifi remote 4 | control protocol. 5 | 6 | Inspired by https://github.com/phev-remote/ but written entirely in Go. 7 | 8 | For further hacking, read the [protocol documentation](protocol/README.md). 9 | 10 | Tested against a MY18 vehicle. 11 | 12 | ![Home Assistant Screenshot](phev-ha.png) 13 | 14 | ## Supported functionality 15 | 16 | * MQTT proxy to Phev 17 | * Home Assistant discovery 18 | * Register client to car 19 | * Fetch battery, charge, door, light status 20 | * Set lights and charge enable 21 | * Near-instant response to commands 22 | * *Only tested on a MY18 Phev* 23 | 24 | Also includes some debugging utilities, and a vehicle emulator. 25 | 26 | ## Requirements 27 | 28 | * Go compiler 29 | 30 | ## Licence, etc 31 | 32 | Licenced under the GPLv2. 33 | 34 | Copyright 2021 Ben Buxton 35 | 36 | Contributions and PRs are welcome. 37 | 38 | ## Getting started. 39 | 40 | ### Compiling 41 | 42 | #### Install Go 43 | 44 | * Download and install the latest [Go compiler](https://golang.org/dl/) 45 | * Your distro packager may have a version thats too old 46 | * For raspbian choose the ARMv6 release 47 | 48 | #### Install PCAP dev libraries 49 | 50 | * Optionally, you may want to have libpcap-dev package installed (if building with `-tags pcap`.) 51 | 52 | #### Download, extract, and compile phev2mqtt 53 | 54 | * Download the phev2mqtt archive 55 | * Extract it 56 | * Go into its the top level directory and run `go build` 57 | * Verify it runs with `./phev2mqtt -h` 58 | 59 | ### Connecting to the vehicle. 60 | 61 | #### Configure Wifi client on system running mqtt2phev 62 | 63 | On your computer running the phev2mqtt tools, configure a new Wifi connection to the 64 | car's SSID, 65 | 66 | #### Register the client to the car 67 | 68 | Follow the [Mitsubishi instructions](https://www.mitsubishi-motors.com/en/products/outlander_phev/app/remote/) 69 | to find the Wifi credentials provided with the car. 70 | 71 | Verify that your Wifi connection to the car is established - your local IP address 72 | should be 192.168.8.47. 73 | 74 | Follow the [Mitsubishi instructions](https://www.mitsubishi-motors.com/en/products/outlander_phev/app/remote/) 75 | and put the car into registration mode ("Setup Your Vehicle"). You may need to 76 | re-establish the Wifi connection. 77 | 78 | Register by running `phev2mqtt client register` and you should shortly see a message 79 | indicating successful registration. 80 | 81 | #### Testing the tool 82 | 83 | Once connected to the car, you can sniff for messages by running *phev2mqtt client watch*. 84 | The phone client needs to be disconnected for this to work. 85 | You'll see a bunch of data go by - some of those will be decoded into readable 86 | messages such as charge and AC status. 87 | 88 | ### MQTT Gateway 89 | 90 | The primary feature of this code is to run as a proxy between the car and 91 | MQTT. Registers with car status are sent to MQTT, both as raw register 92 | values and decoded functional values. Commands sent on MQTT topics can 93 | be used to control certain aspects of the vehicle. 94 | 95 | Start the MQTT gateway with: 96 | 97 | `./phev2mqtt client mqtt --mqtt_server tcp://] [--mqtt_password ]` 98 | 99 | The following topics are published: 100 | 101 | | Topic/prefix | Description | 102 | |---|---| 103 | | phev/register/[register] | Raw values of each register, as hex strings | 104 | | phev/available | Wifi connection status to car. *online* or *offline* | 105 | | phev/battery/level | Current drive battery level as a percent | 106 | | phev/climate/status | Whether the car AC is on | 107 | | phev/climate/mode | Mode of the AC, if on. *cool*, *heat*, *windscreen* | 108 | | phev/climate/[mode] | Alternative of above. Modes are *cool*, *heat*, *windscreen* which can be *off* or *on* | 109 | | phev/charge/charging | Whether the battery is charging. *on* or *off* | 110 | | phev/charge/plug | If the charging plug is *unplugged* or *connected*. | 111 | | phev/charge/remaining | Minutes left, if charging. | 112 | | phev/door/locked | Whether the car is locked. *on* or *off* | 113 | | ~~phev/door/front_left~~ | State of doors. *closed* or *open* | 114 | | ~~phev/door/front_right~~ | State of doors. *closed* or *open* | 115 | | phev/door/front_passenger | State of doors. *closed* or *open* | 116 | | phev/door/driver | State of doors. *closed* or *open* | 117 | | phev/door/rear_left | State of doors. *closed* or *open* | 118 | | phev/door/rear_right | State of doors. *closed* or *open* | 119 | | phev/door/bonnet | State of doors. *closed* or *open* | 120 | | phev/door/boot | State of doors. *closed* or *open* | 121 | | phev/lights/parking | Parking lights. *on* or *off* | 122 | | phev/lights/head | Head lights. *on* or *off* | 123 | | phev/lights/hazard | Hazard lights. *on* or *off* | 124 | | phev/lights/interior | Interior lights. *on* or *off* | 125 | | phev/vin | Discovered VIN of the car | 126 | | phev/registrations | Number of wifi clients registered to the car | 127 | 128 | The following topics are subscribed to and can be used to change state on the car: 129 | 130 | | Topic/prefix | Description | 131 | |---|---| 132 | | phev/set/register/[register] | Set register 0x[register] to value 0x[payload] | 133 | | phev/set/parkinglights | Set parking lights *on* or *off* | 134 | | phev/set/headlights | Set head lights *on* or *off* | 135 | | phev/set/cancelchargetimer | Cancel charge timer (any payload) | 136 | | phev/set/climate/[mode] | Set ac/climate state (cool/heat/windscreen/off) for [payload] (10[on]/20/30) | 137 | | phev/set/climate/state | `[payload]=reset` clears "terminated" state | 138 | | phev/connection | Change car connection state to (on/off/restart) | 139 | 140 | #### Home Assistant discovery 141 | 142 | The client supports [Home Assistant MQTT Discovery](https://www.home-assistant.io/docs/mqtt/discovery/) by default. 143 | 144 | After initial discovery, re-run the binary for the entities to appear. You can 145 | search for "phev" in your entity list. Your car should also appear as a device 146 | in the Devices tab. 147 | 148 | You can disable this with `--ha_discovery=false` or change the discovery prefix, the default is `--ha_discovery_prefix=homeassistant`. 149 | 150 | #### Raspbian setup with auto-start 151 | 152 | It's useful to have the tool auto-start when running on e.g a Raspberry Pi. The following 153 | describes how to set this up. 154 | 155 | - Edit or add to `/etc/systemd/network/00-default.link` with the following: 156 | 157 | ``` 158 | [Match] 159 | # This should be the 'real' (default) mac address of the Pi's wireless interface. 160 | MACAddress=b8:27:eb:50:c0:52 161 | 162 | [Link] 163 | # This should be the MAC address to use to connect to the car, per above. 164 | MACAddress=ee:4d:ec:de:7a:91 165 | NamePolicy=kernel database onboard slot path 166 | 167 | ``` 168 | 169 | - Add the car's Wifi info to `/etc/wpa_supplicant/wpa_supplicant.conf`: 170 | 171 | ``` 172 | ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev 173 | update_config=1 174 | country=AU 175 | 176 | network={ 177 | ssid="REMOTE45bhds" 178 | scan_ssid=1 179 | psk="blahblahbla12314" 180 | } 181 | 182 | ``` 183 | 184 | - Add the following to `/etc/systemd/system/phev2mqtt.service`, updating the MQTT address to 185 | suit your setup: 186 | 187 | ``` 188 | [Unit] 189 | Description=phev2mqtt service script 190 | StartLimitIntervalSec=5 191 | After=syslog.target network.target 192 | 193 | [Service] 194 | Type=exec 195 | ExecStart=/usr/local/bin/phev2mqtt --config=/dev/null client mqtt --mqtt_server tcp://192.168.0.88:1883 -v=debug 196 | 197 | # Restart script if stopped 198 | Restart=always 199 | # Wait 30s before restart 200 | RestartSec=30s 201 | 202 | # Tag things in the log 203 | # View with: sudo journalctl -f -u phev2mqtt -o cat 204 | SyslogIdentifier=phev2mqtt 205 | 206 | StandardOutput=syslog 207 | StandardError=syslog 208 | 209 | [Install] 210 | WantedBy=multi-user.target 211 | ``` 212 | 213 | - Copy the `phev2mqtt` binary to /usr/local/bin and make sure it's executable. 214 | 215 | - Start the service with `sudo systemctl start phev2mqtt.service` 216 | 217 | - Enable the service to run at boot, with `sudo systemctl enable phev2mqtt.service`. 218 | 219 | - Restart the Pi and verify that it can connect to the car. Also run `ifconfig` and check 220 | that the `wlan0` interface has the correct mac address. You should also see this interface 221 | have the IP address `192.168.8.47`. 222 | 223 | - Verify that the phev2mqtt service is communicating with the car, by checking 224 | the logs: `sudo journalctl -f -u phev2mqtt -o cat` 225 | 226 | ### Sniffing the official client 227 | 228 | Further development of this library can be done with a packet dump of the official 229 | Mistubishi app. 230 | 231 | A number of sniffer apps for phones are available for this. Two that the author have 232 | used are *Packet Capture* and *PCAP Remote*. These do not require root access, yet 233 | can successfully sniff the traffic into PCAP files for further analysis. 234 | 235 | *Packet Capture* can save the PCAP files to your local phone storage which you can 236 | then extract off the phone. 237 | 238 | *PCAP Remote* is a little more involved, but allows for live sniffing of the traffic. 239 | 240 | Once you have downloaded the PCAP file(s) from the phone, you can analyse them with 241 | the command *phev2mqtt decode pcap *. First build a `phev2mqtt` with pcap features: 242 | `go build -tags pcap`; you will need libpcap for this. Adjust the verbosity level (`-v`) between 243 | `info`, `debug` and `trace` for more details. 244 | 245 | Additionally, the flag `--latency` will use the PCAP packet timestamps to decode 246 | the packets with original timings which can help pinpoint app events. 247 | 248 | You can also specify *tcp::* which will connect to that host/port 249 | over TCP and decode that traffic - useful when live sniffing to a TCP service. 250 | 251 | ### Vehicle emulator 252 | 253 | There is an emulator built in which can be used to test functionality without needing 254 | a real car (and also reduces risk of putting your car into weird states). 255 | 256 | Start it with `phev2mqtt emulator` and then you can point a client at it. 257 | 258 | The official app will always try to connect to IP `192.168.8.46`, so you'll need 259 | to ensure you run `phev2mqtt` on a machine with this IP and which you can 260 | reach via WIFI. The author uses a Raspberry Pi setup as an AP (using hostapd) 261 | and runs `phev2mqtt` on it, though you could also tunnel the TCP connection to 262 | a dev machine. 263 | 264 | The app should successfully be able to register with the emulator (it might take 265 | a couple of goes). 266 | 267 | Any settings sent by the app won't actually change state for now, but it can 268 | be useful for sniffing the app. 269 | -------------------------------------------------------------------------------- /protocol/message.go: -------------------------------------------------------------------------------- 1 | package protocol 2 | 3 | import ( 4 | "encoding/binary" 5 | "encoding/hex" 6 | "fmt" 7 | log "github.com/sirupsen/logrus" 8 | "time" 9 | ) 10 | 11 | const ( 12 | CmdOutPingReq = 0xf3 13 | CmdInPingResp = 0x3f 14 | 15 | CmdOutSend = 0xf6 16 | CmdInResp = 0x6f 17 | 18 | CmdInMy24StartReq = 0x6e 19 | CmdOutMy24StartResp = 0xe6 20 | 21 | CmdInMy18StartReq = 0x5e 22 | CmdOutMy18StartResp = 0xe5 23 | 24 | CmdInMy14StartReq = 0x4e 25 | CmdOutMy14StartResp = 0xe4 26 | 27 | CmdInBadEncoding = 0xbb 28 | CmdInUnkn3 = 0xcc 29 | 30 | CmdInStartResp = 0x2f 31 | CmdOutStartSendMy18 = 0xf2 32 | 33 | CmdInUnkn4 = 0x2e 34 | ) 35 | 36 | const ( 37 | Request byte = 0x0 38 | Ack byte = 0x1 39 | ) 40 | 41 | var ackStr = map[byte]string{ 42 | 0x0: "REQ", 43 | 0x1: "ACK", 44 | } 45 | 46 | var messageStr = map[byte]string{ 47 | 0xf3: "PingReq", 48 | 0x3f: "PingResp", 49 | 0xf6: "SendCmd", 50 | 0x6f: "RespCmd", 51 | 0xe5: "StartResp18", 52 | 0x5e: "StartReq18", 53 | 0xf2: "StartSend", 54 | 0x2f: "StartResp", 55 | 0xe4: "StartResp14", 56 | 0x4e: "StartReq14", 57 | 0xe6: "StartResp24", 58 | 0x6e: "StartReq24", 59 | } 60 | 61 | type PhevMessage struct { 62 | Type byte 63 | Length byte 64 | Ack byte 65 | Register byte 66 | Data []byte 67 | Checksum byte 68 | Xor byte 69 | Original []byte 70 | OriginalXored []byte 71 | Reg Register 72 | } 73 | 74 | func (p *PhevMessage) ShortForm() string { 75 | switch p.Type { 76 | case CmdInPingResp: 77 | return fmt.Sprintf("PING RESP (id %x)", p.Register) 78 | 79 | case CmdOutPingReq: 80 | return fmt.Sprintf("PING REQ (id %x)", p.Register) 81 | 82 | case CmdOutStartSendMy18: 83 | return fmt.Sprintf("START SEND18 (orig %s)", hex.EncodeToString(p.Original)) 84 | 85 | case CmdInStartResp: 86 | return fmt.Sprintf("START RESP (orig: %s)", hex.EncodeToString(p.Original)) 87 | 88 | case CmdOutSend: 89 | if p.Ack == Ack { 90 | return fmt.Sprintf("REGISTER ACK (reg 0x%02x data %s)", p.Register, hex.EncodeToString(p.Data)) 91 | } 92 | return fmt.Sprintf("REGISTER SET (reg 0x%02x data %s)", p.Register, hex.EncodeToString(p.Data)) 93 | 94 | case CmdInResp: 95 | if p.Ack == Request { 96 | if p.Reg != nil { 97 | return fmt.Sprintf("REGISTER NTFY (reg 0x%02x data %s) [%s]", p.Register, hex.EncodeToString(p.Data), p.Reg.String()) 98 | } else { 99 | return fmt.Sprintf("REGISTER NTFY (reg 0x%02x data %s)", p.Register, hex.EncodeToString(p.Data)) 100 | } 101 | } 102 | return fmt.Sprintf("REGISTER SETACK (reg 0x%02x data %s)", p.Register, hex.EncodeToString(p.Data)) 103 | 104 | case CmdInMy24StartReq: 105 | return fmt.Sprintf("START RECV24 (orig %s)", hex.EncodeToString(p.Original)) 106 | 107 | case CmdOutMy24StartResp: 108 | return fmt.Sprintf("START SEND24 (orig %s)", hex.EncodeToString(p.Original)) 109 | 110 | case CmdInMy18StartReq: 111 | return fmt.Sprintf("START RECV18 (orig %s)", hex.EncodeToString(p.Original)) 112 | 113 | case CmdOutMy18StartResp: 114 | return fmt.Sprintf("START SEND18 (orig %s)", hex.EncodeToString(p.Original)) 115 | 116 | case CmdInMy14StartReq: 117 | return fmt.Sprintf("START RECV14 (orig %s)", hex.EncodeToString(p.Original)) 118 | 119 | case CmdOutMy14StartResp: 120 | return fmt.Sprintf("START SEND14 (orig %s)", hex.EncodeToString(p.Original)) 121 | 122 | case CmdInBadEncoding: 123 | return fmt.Sprintf("BAD ENCODING (exp: 0x%02x)", p.Data[0]) 124 | 125 | default: 126 | return p.String() 127 | } 128 | } 129 | 130 | func (p *PhevMessage) RawString() string { 131 | return hex.EncodeToString(p.Original) 132 | } 133 | 134 | func (p *PhevMessage) EncodeToBytes(key *SecurityKey) []byte { 135 | length := byte(len(p.Data) + 3) 136 | data := []byte{ 137 | p.Type, 138 | length, 139 | p.Ack, 140 | p.Register, 141 | } 142 | data = append(data, p.Data...) 143 | data = append(data, Checksum(data)) 144 | var xor byte 145 | switch p.Type { 146 | case CmdInMy24StartReq, CmdOutMy24StartResp, CmdInMy18StartReq, CmdOutMy18StartResp, CmdInMy14StartReq, CmdOutMy14StartResp: 147 | // No xor/key for these messages. 148 | case CmdOutSend: 149 | // Use then increment send key. 150 | xor = key.SKey(true) 151 | default: 152 | // Use but do not increment send key. 153 | xor = key.SKey(false) 154 | } 155 | p.Xor = xor 156 | return XorMessageWith(data, xor) 157 | } 158 | 159 | func (p *PhevMessage) DecodeFromBytes(data []byte, key *SecurityKey) error { 160 | if len(data) < 4 { 161 | return fmt.Errorf("invalid packet length") 162 | } 163 | p.OriginalXored = data 164 | data, xor, _ := ValidateAndDecodeMessage(data) 165 | if len(data) < 4 || len(data) < int(data[1]+2) { 166 | return fmt.Errorf("invalid packet length") 167 | } 168 | p.Type = data[0] 169 | p.Length = data[1] + 2 170 | p.Register = data[3] 171 | p.Data = data[4 : p.Length-1] 172 | p.Checksum = data[p.Length-1] 173 | p.Ack = data[2] 174 | p.Xor = xor 175 | p.Original = data 176 | switch p.Type { 177 | case CmdInMy24StartReq, CmdInMy18StartReq, CmdInMy14StartReq: 178 | key.Update(p.OriginalXored) 179 | case CmdInResp: 180 | key.RKey(true) 181 | case CmdOutSend: 182 | key.SKey(true) 183 | } 184 | if p.Type == CmdInResp && p.Ack == Request { 185 | switch p.Register { 186 | case VINRegister: 187 | p.Reg = new(RegisterVIN) 188 | case SettingsRegister: 189 | p.Reg = new(RegisterSettings) 190 | case TimeRegister: 191 | p.Reg = new(RegisterTime) 192 | case ECUVersionRegister: 193 | p.Reg = new(RegisterECUVersion) 194 | case BatteryLevelRegister: 195 | p.Reg = new(RegisterBatteryLevel) 196 | case BatteryWarningRegister: 197 | p.Reg = new(RegisterBatteryWarning) 198 | case DoorStatusRegister: 199 | p.Reg = new(RegisterDoorStatus) 200 | case ChargePlugRegister: 201 | p.Reg = new(RegisterChargePlug) 202 | case ChargeStatusRegister: 203 | p.Reg = new(RegisterChargeStatus) 204 | case PreACStateRegister: 205 | p.Reg = new(RegisterPreACState) 206 | case ACOperStatusRegister: 207 | p.Reg = new(RegisterACOperStatus) 208 | case ACModeRegister: 209 | p.Reg = new(RegisterACMode) 210 | case WIFISSIDRegister: 211 | p.Reg = new(RegisterWIFISSID) 212 | case LightStatusRegister: 213 | p.Reg = new(RegisterLightStatus) 214 | default: 215 | p.Reg = new(RegisterGeneric) 216 | } 217 | p.Reg.Decode(p) 218 | } 219 | 220 | return nil 221 | } 222 | 223 | func (p *PhevMessage) String() string { 224 | return fmt.Sprintf( 225 | `Cmd: 0x%x (%s) (len %d), Register 0x%x, Data: %s`, 226 | p.Type, messageStr[p.Type], p.Length, p.Register, hex.EncodeToString(p.Data)) 227 | } 228 | 229 | func NewFromBytes(data []byte, key *SecurityKey) []*PhevMessage { 230 | msgs := []*PhevMessage{} 231 | 232 | log.Tracef("%%PHEV_DECODE_FROM_BYTES%%: Raw: %s", hex.EncodeToString(data)) 233 | offset := 0 234 | for { 235 | dat, xor, rem := ValidateAndDecodeMessage(data[offset:]) 236 | if len(dat) == 0 { 237 | offset += 1 238 | if offset >= len(data)-6 { 239 | break 240 | } 241 | continue 242 | } 243 | log.Tracef("%%PHEV_DECODED_FROM_BYTES%%: Raw: %s", hex.EncodeToString(dat)) 244 | dat = XorMessageWith(dat, xor) 245 | p := &PhevMessage{} 246 | err := p.DecodeFromBytes(dat, key) 247 | p.OriginalXored = data[offset : offset+len(dat)] 248 | p.Xor = xor 249 | if err != nil { 250 | log.Errorf("decode error: %v\n", err) 251 | break 252 | } 253 | msgs = append(msgs, p) 254 | if len(rem) < 1 { 255 | break 256 | } 257 | data = rem 258 | offset = 0 259 | } 260 | return msgs 261 | } 262 | 263 | func encodeTime(t time.Time) []byte { 264 | return []byte{ 265 | byte(t.Year() - 2000), 266 | byte(t.Month()), 267 | byte(t.Day()), 268 | byte(t.Hour()), 269 | byte(t.Minute()), 270 | byte(t.Second()), 271 | byte(t.Weekday())} 272 | } 273 | 274 | func decodeTime(m []byte) time.Time { 275 | return time.Date( 276 | 2000+int(m[0]), // Year 277 | time.Month(m[1]), // Month 278 | int(m[2]), // Day of month 279 | int(m[3]), // Hour 280 | int(m[4]), // Minute 281 | int(m[5]), // Second 282 | 0, time.Local) 283 | } 284 | 285 | const ( 286 | BatteryWarningRegister = 0x02 287 | SetACModeRegisterMY14 = 0x02 288 | SetACEnabledRegisterMY14 = 0x04 289 | PreACStateRegister = 0x10 290 | TimeRegister = 0x12 291 | SetAckPreACTermRegister = 0x13 292 | VINRegister = 0x15 293 | SettingsRegister = 0x16 294 | ACOperStatusRegister = 0x1a 295 | SetACModeRegisterMY18 = 0x1b 296 | ACModeRegister = 0x1c 297 | BatteryLevelRegister = 0x1d 298 | ChargePlugRegister = 0x1e 299 | ChargeStatusRegister = 0x1f 300 | LightStatusRegister = 0x23 301 | DoorStatusRegister = 0x24 302 | WIFISSIDRegister = 0x28 303 | ECUVersionRegister = 0xc0 304 | ) 305 | 306 | type Register interface { 307 | Decode(*PhevMessage) 308 | Encode() *PhevMessage 309 | Raw() string 310 | String() string 311 | Register() byte 312 | } 313 | 314 | type RegisterGeneric struct { 315 | Reg byte 316 | Value []byte 317 | } 318 | 319 | func (r *RegisterGeneric) Decode(m *PhevMessage) { 320 | r.Reg = m.Register 321 | r.Value = m.Data 322 | } 323 | 324 | func (r *RegisterGeneric) Encode() *PhevMessage { 325 | return &PhevMessage{ 326 | Register: r.Register(), 327 | Data: r.Value, 328 | } 329 | } 330 | 331 | func (r *RegisterGeneric) Raw() string { 332 | return hex.EncodeToString(r.Value) 333 | } 334 | 335 | func (r *RegisterGeneric) String() string { 336 | return fmt.Sprintf("g(0x%02x): %s", r.Reg, r.Raw()) 337 | } 338 | 339 | func (r *RegisterGeneric) Register() byte { 340 | return r.Reg 341 | } 342 | 343 | type RegisterTime struct { 344 | Time time.Time 345 | raw []byte 346 | } 347 | 348 | func (r *RegisterTime) Decode(m *PhevMessage) { 349 | if len(m.Data) != 7 { 350 | return 351 | } 352 | r.Time = decodeTime(m.Data) 353 | r.raw = m.Data 354 | } 355 | 356 | func (r *RegisterTime) Encode() *PhevMessage { 357 | return &PhevMessage{ 358 | Register: r.Register(), 359 | Data: encodeTime(r.Time), 360 | } 361 | } 362 | 363 | func (r *RegisterTime) Raw() string { 364 | return hex.EncodeToString(r.raw) 365 | } 366 | 367 | func (r *RegisterTime) String() string { 368 | return r.Time.String() 369 | } 370 | 371 | func (r *RegisterTime) Register() byte { 372 | return TimeRegister 373 | } 374 | 375 | type RegisterSettings struct { 376 | register byte 377 | raw []byte 378 | } 379 | 380 | func (r *RegisterSettings) Decode(m *PhevMessage) { 381 | r.register = m.Register 382 | r.raw = m.Data 383 | } 384 | 385 | func (r *RegisterSettings) Encode() *PhevMessage { 386 | return &PhevMessage{ 387 | Register: r.Register(), 388 | Data: r.raw, 389 | } 390 | } 391 | 392 | func (r *RegisterSettings) Raw() string { 393 | return hex.EncodeToString(r.raw) 394 | } 395 | 396 | func (r *RegisterSettings) String() string { 397 | value := binary.LittleEndian.Uint64(r.raw) 398 | return fmt.Sprintf("Car Settings: %016x", value) 399 | } 400 | 401 | func (r *RegisterSettings) Register() byte { 402 | return r.register 403 | } 404 | 405 | type RegisterVIN struct { 406 | VIN string 407 | Registrations int 408 | raw []byte 409 | } 410 | 411 | func (r *RegisterVIN) Decode(m *PhevMessage) { 412 | if m.Register != VINRegister || len(m.Data) != 20 { 413 | return 414 | } 415 | r.VIN = string(m.Data[1:17]) 416 | r.Registrations = int(m.Data[19]) 417 | r.raw = m.Data 418 | } 419 | 420 | func (r *RegisterVIN) Encode() *PhevMessage { 421 | data := []byte{0x3} 422 | data = append(data, []byte(r.VIN)...) 423 | data = append(data, 0x0) 424 | data = append(data, byte(r.Registrations)) 425 | return &PhevMessage{ 426 | Register: r.Register(), 427 | Data: data, 428 | } 429 | } 430 | 431 | func (r *RegisterVIN) Raw() string { 432 | return hex.EncodeToString(r.raw) 433 | } 434 | 435 | func (r *RegisterVIN) String() string { 436 | return fmt.Sprintf("VIN: %s Registrations: %d", r.VIN, r.Registrations) 437 | } 438 | 439 | func (r *RegisterVIN) Register() byte { 440 | return VINRegister 441 | } 442 | 443 | type RegisterECUVersion struct { 444 | Version string 445 | raw []byte 446 | } 447 | 448 | func (r *RegisterECUVersion) Decode(m *PhevMessage) { 449 | if m.Register != ECUVersionRegister || len(m.Data) != 13 { 450 | return 451 | } 452 | r.Version = string(m.Data[:9]) 453 | r.raw = m.Data 454 | } 455 | 456 | func (r *RegisterECUVersion) Encode() *PhevMessage { 457 | data := []byte(r.Version) 458 | data = append(data, []byte{0x11, 0x00, 0x00}...) 459 | return &PhevMessage{ 460 | Register: r.Register(), 461 | Data: data, 462 | } 463 | } 464 | 465 | func (r *RegisterECUVersion) Raw() string { 466 | return hex.EncodeToString(r.raw) 467 | } 468 | 469 | func (r *RegisterECUVersion) String() string { 470 | return fmt.Sprintf("ECU Version: %s", r.Version) 471 | } 472 | 473 | func (r *RegisterECUVersion) Register() byte { 474 | return ECUVersionRegister 475 | } 476 | 477 | type RegisterBatteryLevel struct { 478 | Level int 479 | ParkingLights bool // yes parking lights here. 480 | raw []byte 481 | } 482 | 483 | func (r *RegisterBatteryLevel) Decode(m *PhevMessage) { 484 | if m.Register != BatteryLevelRegister || len(m.Data) != 4 { 485 | return 486 | } 487 | r.Level = int(m.Data[0]) 488 | r.ParkingLights = m.Data[2] == 0x1 489 | r.raw = m.Data 490 | } 491 | 492 | func (r *RegisterBatteryLevel) Encode() *PhevMessage { 493 | data := []byte{byte(r.Level), 0x0, 0x0} 494 | if r.ParkingLights { 495 | data[2] = 0x1 496 | } 497 | 498 | return &PhevMessage{ 499 | Register: r.Register(), 500 | Data: data, 501 | } 502 | } 503 | 504 | func (r *RegisterBatteryLevel) Raw() string { 505 | return hex.EncodeToString(r.raw) 506 | } 507 | 508 | func (r *RegisterBatteryLevel) String() string { 509 | return fmt.Sprintf("Battery level: %d", r.Level) 510 | } 511 | 512 | func (r *RegisterBatteryLevel) Register() byte { 513 | return BatteryLevelRegister 514 | } 515 | 516 | type RegisterBatteryWarning struct { 517 | Warning int 518 | raw []byte 519 | } 520 | 521 | func (r *RegisterBatteryWarning) Decode(m *PhevMessage) { 522 | if m.Register != BatteryWarningRegister || len(m.Data) != 4 { 523 | return 524 | } 525 | r.Warning = int(m.Data[2]) 526 | r.raw = m.Data 527 | } 528 | 529 | func (r *RegisterBatteryWarning) Encode() *PhevMessage { 530 | data := []byte{0x0, 0x0, byte(r.Warning), 0x0} 531 | return &PhevMessage{ 532 | Register: r.Register(), 533 | Data: data, 534 | } 535 | } 536 | 537 | func (r *RegisterBatteryWarning) Raw() string { 538 | return hex.EncodeToString(r.raw) 539 | } 540 | 541 | func (r *RegisterBatteryWarning) String() string { 542 | return fmt.Sprintf("Battery warning: %d", r.Warning) 543 | } 544 | 545 | func (r *RegisterBatteryWarning) Register() byte { 546 | return BatteryWarningRegister 547 | } 548 | 549 | type RegisterDoorStatus struct { 550 | // Locked is true if the vehicle is locked. 551 | Locked bool 552 | // The below are true if the corresponding door is open. 553 | Driver, FrontPassenger, RearLeft, RearRight bool 554 | Bonnet, Boot bool 555 | // Headlight state is in this register! 556 | Headlights bool 557 | raw []byte 558 | } 559 | 560 | func (r *RegisterDoorStatus) Decode(m *PhevMessage) { 561 | if m.Register != DoorStatusRegister || len(m.Data) != 10 { 562 | return 563 | } 564 | r.Locked = m.Data[0] == 0x1 565 | r.Driver = m.Data[3] == 0x1 566 | r.FrontPassenger = m.Data[4] == 0x1 567 | r.RearRight = m.Data[5] == 0x1 568 | r.RearLeft = m.Data[6] == 0x1 569 | r.Boot = m.Data[7] == 0x1 570 | r.Bonnet = m.Data[8] == 0x1 571 | r.Headlights = m.Data[9] == 0x1 572 | r.raw = m.Data 573 | } 574 | 575 | func (r *RegisterDoorStatus) Encode() *PhevMessage { 576 | data := make([]byte, 10) 577 | if r.Locked { 578 | data[0] = 0x1 579 | } 580 | if r.Driver { 581 | data[3] = 0x1 582 | } 583 | if r.FrontPassenger { 584 | data[4] = 0x1 585 | } 586 | if r.RearRight { 587 | data[5] = 0x1 588 | } 589 | if r.RearLeft { 590 | data[6] = 0x1 591 | } 592 | if r.Boot { 593 | data[7] = 0x1 594 | } 595 | if r.Bonnet { 596 | data[8] = 0x1 597 | } 598 | if r.Headlights { 599 | data[9] = 0x1 600 | } 601 | return &PhevMessage{ 602 | Register: r.Register(), 603 | Data: data, 604 | } 605 | } 606 | 607 | func (r *RegisterDoorStatus) Raw() string { 608 | return hex.EncodeToString(r.raw) 609 | } 610 | 611 | func (r *RegisterDoorStatus) String() string { 612 | openStr := "" 613 | if r.FrontPassenger || r.Driver || r.RearRight || r.RearLeft || r.Boot || r.Bonnet { 614 | 615 | openStr = " Open:" 616 | if r.Driver { 617 | openStr += " driver" 618 | } 619 | if r.FrontPassenger { 620 | openStr += " front_passenger" 621 | } 622 | if r.RearRight { 623 | openStr += " rear_right" 624 | } 625 | if r.RearLeft { 626 | openStr += " rear_left" 627 | } 628 | if r.Bonnet { 629 | openStr += " bonnet" 630 | } 631 | if r.Boot { 632 | openStr += " boot" 633 | } 634 | } 635 | if r.Locked { 636 | return "Doors locked." + openStr 637 | } 638 | return "Doors unlocked." + openStr 639 | } 640 | 641 | func (r *RegisterDoorStatus) Register() byte { 642 | return DoorStatusRegister 643 | } 644 | 645 | type RegisterChargeStatus struct { 646 | Charging bool 647 | Remaining int // minutes. 648 | raw []byte 649 | } 650 | 651 | func (r *RegisterChargeStatus) Decode(m *PhevMessage) { 652 | if m.Register != ChargeStatusRegister || len(m.Data) != 3 { 653 | return 654 | } 655 | r.Charging = m.Data[0] == 0x1 656 | r.Remaining = 0 657 | if m.Data[2] != 0xff { 658 | r.Remaining = int(m.Data[2])<<8 | int(m.Data[1]) 659 | } 660 | r.raw = m.Data 661 | } 662 | 663 | func (r *RegisterChargeStatus) Encode() *PhevMessage { 664 | data := make([]byte, 3) 665 | if r.Charging { 666 | data[0] = 0x1 667 | data[1] = byte(r.Remaining % 256) 668 | data[2] = byte(r.Remaining / 256) 669 | } 670 | return &PhevMessage{ 671 | Register: r.Register(), 672 | Data: data, 673 | } 674 | } 675 | 676 | func (r *RegisterACOperStatus) Encode() *PhevMessage { 677 | data := make([]byte, 5) 678 | if r.Operating { 679 | data[1] = 0x1 680 | } 681 | return &PhevMessage{ 682 | Register: r.Register(), 683 | Data: data, 684 | } 685 | } 686 | 687 | func (r *RegisterChargeStatus) Raw() string { 688 | return hex.EncodeToString(r.raw) 689 | } 690 | 691 | func (r *RegisterChargeStatus) String() string { 692 | if r.Charging { 693 | return fmt.Sprintf("Charging, %d remaining.", r.Remaining) 694 | } 695 | return "Not charging" 696 | } 697 | 698 | func (r *RegisterChargeStatus) Register() byte { 699 | return ChargeStatusRegister 700 | } 701 | 702 | type PreACState int8 703 | 704 | const ( 705 | PreACOff PreACState = 0 706 | PreACOn PreACState = 2 707 | PreACTerminated PreACState = 3 708 | ) 709 | 710 | type RegisterPreACState struct { 711 | State PreACState 712 | raw []byte 713 | } 714 | 715 | func (r *RegisterPreACState) Encode() *PhevMessage { 716 | panic("unimplemented") 717 | return nil 718 | } 719 | 720 | func (r *RegisterPreACState) Decode(m *PhevMessage) { 721 | // MY'18 data length is 3 bytes, MY'14 uses 1 byte 722 | // We only decode the operating state in 0th byte 723 | if len(m.Data) < 1 { 724 | return 725 | } 726 | r.State = PreACState(m.Data[0]) 727 | r.raw = m.Data 728 | } 729 | 730 | func (r *RegisterPreACState) Raw() string { 731 | return hex.EncodeToString(r.raw) 732 | } 733 | 734 | func (r *RegisterPreACState) String() string { 735 | switch r.State { 736 | case PreACOff: 737 | return "Pre-AC off" 738 | case PreACOn: 739 | return "Pre-AC on" 740 | case PreACTerminated: 741 | return "Pre-AC terminated (door opened or battery low?)" 742 | default: 743 | return fmt.Sprintf("Pre-AC: unknown (%v)", r.State) 744 | } 745 | } 746 | 747 | func (r *RegisterPreACState) Register() byte { 748 | return PreACStateRegister 749 | } 750 | 751 | type RegisterACOperStatus struct { 752 | Operating bool 753 | raw []byte 754 | } 755 | 756 | func (r *RegisterACOperStatus) Decode(m *PhevMessage) { 757 | // MY'18 data length is 5 bytes, MY'14 uses 2 bytes 758 | // We only decode the operating state in byte 2 759 | if m.Register != ACOperStatusRegister || len(m.Data) < 2 { 760 | return 761 | } 762 | r.Operating = m.Data[1] == 1 763 | r.raw = m.Data 764 | } 765 | 766 | func (r *RegisterACOperStatus) Raw() string { 767 | return hex.EncodeToString(r.raw) 768 | } 769 | 770 | func (r *RegisterACOperStatus) String() string { 771 | if r.Operating { 772 | return "AC on" 773 | } 774 | return "AC off" 775 | } 776 | 777 | func (r *RegisterACOperStatus) Register() byte { 778 | return ACOperStatusRegister 779 | } 780 | 781 | type RegisterACMode struct { 782 | Mode string 783 | Duration uint8 784 | raw []byte 785 | } 786 | 787 | func (r *RegisterACMode) Decode(m *PhevMessage) { 788 | if len(m.Data) != 1 { 789 | return 790 | } 791 | switch m.Data[0] & 0x0f { 792 | case 0: 793 | r.Mode = "unknown" 794 | case 1: 795 | r.Mode = "cool" 796 | case 2: 797 | r.Mode = "heat" 798 | case 3: 799 | r.Mode = "windscreen" 800 | } 801 | switch m.Data[0] & 0xf0 { 802 | case 0x00: 803 | r.Duration = 10 804 | case 0x10: 805 | r.Duration = 20 806 | case 0x20: 807 | r.Duration = 30 808 | } 809 | r.raw = m.Data 810 | } 811 | 812 | func (r *RegisterACMode) Encode() *PhevMessage { 813 | var data byte 814 | switch r.Mode { 815 | case "unknown": 816 | data = 0x0 817 | case "cool": 818 | data = 0x1 819 | case "heat": 820 | data = 0x2 821 | case "windscreen": 822 | data = 0x3 823 | } 824 | return &PhevMessage{ 825 | Register: r.Register(), 826 | Data: []byte{data}, 827 | } 828 | } 829 | 830 | func (r *RegisterACMode) Raw() string { 831 | return hex.EncodeToString(r.raw) 832 | } 833 | 834 | func (r *RegisterACMode) String() string { 835 | return r.Mode 836 | } 837 | 838 | func (r *RegisterACMode) Register() byte { 839 | return ACModeRegister 840 | } 841 | 842 | type RegisterChargePlug struct { 843 | Connected bool 844 | raw []byte 845 | } 846 | 847 | func (r *RegisterChargePlug) Decode(m *PhevMessage) { 848 | if len(m.Data) != 2 { 849 | return 850 | } 851 | r.Connected = (m.Data[1] == 1 || m.Data[0] > 0) 852 | r.raw = m.Data 853 | } 854 | 855 | func (r *RegisterChargePlug) Encode() *PhevMessage { 856 | data := make([]byte, 2) 857 | if r.Connected { 858 | data[1] = 0x1 859 | } 860 | return &PhevMessage{ 861 | Register: r.Register(), 862 | Data: data, 863 | } 864 | } 865 | 866 | func (r *RegisterChargePlug) Raw() string { 867 | return hex.EncodeToString(r.raw) 868 | } 869 | 870 | func (r *RegisterChargePlug) String() string { 871 | if r.Connected { 872 | return "Charger connected" 873 | } 874 | return "Charger disconnected" 875 | } 876 | 877 | func (r *RegisterChargePlug) Register() byte { 878 | return ChargePlugRegister 879 | } 880 | 881 | type RegisterWIFISSID struct { 882 | SSID string 883 | raw []byte 884 | } 885 | 886 | func (r *RegisterWIFISSID) Decode(m *PhevMessage) { 887 | if m.Register != WIFISSIDRegister || len(m.Data) != 32 { 888 | return 889 | } 890 | r.raw = []byte(m.Data) 891 | r.raw = append([]byte{}, m.Data...) 892 | dat := append([]byte{}, m.Data...) 893 | for i, b := range dat { 894 | if b == 0xff { 895 | dat[i] = 0x0 896 | } 897 | } 898 | r.SSID = string(dat) 899 | } 900 | 901 | func (r *RegisterWIFISSID) Encode() *PhevMessage { 902 | data := []byte(r.SSID) 903 | padding := make([]byte, 32-len(r.SSID)) 904 | return &PhevMessage{ 905 | Register: r.Register(), 906 | Data: append(data, padding...), 907 | } 908 | } 909 | 910 | func (r *RegisterWIFISSID) Raw() string { 911 | return hex.EncodeToString(r.raw) 912 | } 913 | 914 | func (r *RegisterWIFISSID) String() string { 915 | return fmt.Sprintf("SSID: %s", r.SSID) 916 | } 917 | 918 | func (r *RegisterWIFISSID) Register() byte { 919 | return WIFISSIDRegister 920 | } 921 | 922 | func NewPingRequestMessage(id byte) *PhevMessage { 923 | return NewMessage(CmdOutPingReq, id, false, []byte{0x0}) 924 | } 925 | 926 | func NewPingResponseMessage(id byte) *PhevMessage { 927 | return NewMessage(CmdInPingResp, id, true, []byte{0x0}) 928 | } 929 | 930 | func NewMessage(typ, register byte, ack bool, data []byte) *PhevMessage { 931 | msg := &PhevMessage{ 932 | Type: typ, 933 | Register: register, 934 | Data: data, 935 | } 936 | if ack { 937 | msg.Ack = Ack 938 | } 939 | return msg 940 | } 941 | 942 | type RegisterLightStatus struct { 943 | Interior bool 944 | Hazard bool 945 | raw []byte 946 | } 947 | 948 | func (r *RegisterLightStatus) Encode() *PhevMessage { 949 | panic("unimplemented") 950 | return nil 951 | } 952 | 953 | func (r *RegisterLightStatus) Decode(m *PhevMessage) { 954 | if len(m.Data) != 5 { 955 | return 956 | } 957 | // Switches between 2 for Off and 1 for On. 958 | r.Interior = m.Data[4]&0b11 == 1 959 | r.Hazard = m.Data[3]&0b11 == 1 960 | r.raw = m.Data 961 | } 962 | 963 | func (r *RegisterLightStatus) Raw() string { 964 | return hex.EncodeToString(r.raw) 965 | } 966 | 967 | func (r *RegisterLightStatus) String() string { 968 | return fmt.Sprintf("Hazard lights: %t; Interior lights: %t.", r.Hazard, r.Interior) 969 | } 970 | 971 | func (r *RegisterLightStatus) Register() byte { 972 | return LightStatusRegister 973 | } 974 | -------------------------------------------------------------------------------- /protocol/README.md: -------------------------------------------------------------------------------- 1 | # PHEV Remote protocol (MY18) 2 | 3 | A brief description of the protocol used. Determined by analysis and reverse 4 | engineering, together the looking at the [phev-remote](https://github.com/phev-remote) 5 | code. 6 | 7 | ## Network transport 8 | 9 | The client device connects to the car using an SSID with a default format 10 | of *REMOTExxxxxx* where *xxxxxx* is an arbitrary string. 11 | 12 | The car assigns the client an IP address over DHCP, usually 192.168.8.47. The 13 | car itself is 192.168.8.46. 14 | 15 | The client communicates to the car's address over TCP port 8080. Within the 16 | TCP connection, binary packets are used to exchange data. 17 | 18 | ## Packet format 19 | 20 | Each packet has the following format: 21 | 22 | ```text 23 | | 1 byte | 1 byte | 1 byte | n bytes ... | 1 byte | 24 | | [Type] [Length] [Ack] [Data] [Checksum] | 25 | ``` 26 | 27 | The fields are: 28 | 29 | ### Type 30 | 31 | One byte. 32 | 33 | The type of the packet. Most packet types have a corresponding response type. 34 | See below for known types. 35 | 36 | ### Length 37 | 38 | One byte 39 | 40 | The length of the packet, less two. For example a packet that contains two 41 | data bytes has a length field of 4. 42 | 43 | ### Ack 44 | 45 | One byte 46 | 47 | The acknowledgement field. Will be 0 for request packets, and 1 for packets 48 | acknowledging a request type. 49 | 50 | ### Data 51 | 52 | Variable length 53 | 54 | The data payload for the packet. Depends on the command. The length of this 55 | field is 4 less than the value in the *Length* field. 56 | 57 | ### Checksum 58 | 59 | One byte 60 | 61 | The checksum is a basic packet integrity check. To calculate its value, add 62 | up of all the previous bytes in the packet. The least significant octet is 63 | the checksum. 64 | 65 | For example, given a packet of `f3040020`, the sum is 0x117, so the checksum 66 | is `0x17`. Thus the entire packet is `f304002017`. 67 | 68 | ## Security and XOR encoding 69 | 70 | Most packets on the wire are encoded with a simple XOR obfuscation algorithm. 71 | Packets from the car will be encoded using a rolling code scheme, and packets 72 | from the client to the car are expected to be encoded similarly. 73 | 74 | The algorithm was reverse engineered by @zivillian in 75 | [this issue](https://github.com/buxtronix/phev2mqtt/issues/16) which 76 | contains more detailed notes. 77 | 78 | 1. Initial security key 79 | 80 | Shortly after client connection (and at occasional times during the connection), the 81 | car sends an initialisation packet of type `0x5e` or `0x4e`, depending on the year. 82 | The payload of this packet is used to firstly derive a `security_key` which is a 83 | single byte. 84 | 85 | Using this security key, a `key_map` is generated containing 256 distinct byte 86 | values. These byte values are used for the lifetime of the connection or until 87 | another initialisation packet is received. 88 | 89 | Two index values are initialised, starting at zero. We'll call these `s_num` and 90 | `r_num` for the send (to car) and receive (from car) directions. The `key_map` 91 | values at the indices represented by `s_num` and `r_num` are the actual encoding 92 | keys, we will call `s_key` and `r_key`. 93 | 94 | 2. Packet encoding 95 | 96 | After the security key map has been established, all further packets to the car 97 | must be "encrypted" with the current `s_key`. Packets received from the car will 98 | be "encrypted" with the current `r_key`, so must be "decrypted" before further decoding. 99 | 100 | The "encryption" is done by simply XORing each byte in the packet with the current 101 | corresponding key value, either `key_map[s_num]` or `key_map[r_num]`. Being XOR, 102 | the "decryption" is done the same symmetrical way. 103 | 104 | 3. s_num and r_num value incrementing 105 | 106 | The send and receive keys (i.e `s_key` and `r_key`) only change when certain 107 | packets are sent/received. Otherwise they may be used for multiple packets. 108 | 109 | When the car sends a packet of type `0x6f`, the `r_num` is incremented, hence 110 | the new `r_key` will be `key_map[r_num]`. Note that this change is used for 111 | packets *after* the `0x6f` packet. 112 | 113 | When the client sends a packet of type `0xf6`, the `s_num` is incremented, hence 114 | the new `s_key` will be `key_map[s_num]`. Note that this change is used for 115 | packets *after* the `0xf6` packet. 116 | 117 | `r_num` or `s_num` rollover back to zero if they increment from `0xff`. 118 | 119 | ## Packet types 120 | 121 | Summary: 122 | 123 | | Value | Name | Direction | Description | 124 | |-------|-------------------|---------------|--------------------------------------| 125 | | 0xf3 | Ping Request | client -> car | Ping/Keepalive request | 126 | | 0x3f | Ping response | car -> client | Ping / Keepalive response | 127 | | 0x6f | Register changed | car -> client | Notify a register has been updated | 128 | | 0xf6 | Register update | client -> car | Client register change ack/set | 129 | | 0x5e | Security init | car -> client | Initialise security keys (MY18) | 130 | | 0xe5 | Security ack | client -> car | Ack security keys (MY18) | 131 | | 0x4e | Security init | car -> client | Initialise security keys (MY14) | 132 | | 0xe4 | Security ack | client -> car | Ack security keys (MY14) | 133 | | 0x2f | Keepalive request | car -> client | Sent by car to check client presence | 134 | | 0xbb | Bad Xor? | car -> client | Sent when XOR value is incorrect. | 135 | | 0xcc | Bad Xor? | car -> client | Sent when XOR value is incorrect. | 136 | 137 | ### Ping request (0xf3) 138 | 139 | Format: 140 | 141 | ```text 142 | [f3][04][00][][00][] 143 | ``` 144 | 145 | Seems to be a keepalive sent to the car from the client. The initial XOR seems to be 00 146 | until a 0x5e packet is received from the car. The `` increments up to 0x63 then 147 | overflows back to 0x0. 148 | 149 | ### Ping response (0x3f) 150 | 151 | Format: 152 | 153 | ```text 154 | [3f][04][01][][00][] 155 | ``` 156 | 157 | Response to a 0xf3 packet, sent from the car to the client. The `` matches the 158 | request, though the XOR seems to be chosen by the car and future register update packets 159 | match this XOR until another ping exchange. 160 | 161 | ### Register changed (0x6f) 162 | 163 | Format: 164 | 165 | ```text 166 | [6f][][][][][] 167 | ``` 168 | 169 | Used to notify the client that a setting register has changed on the car. 170 | 171 | If `` is zero, then indicates a notification of a register value. If `` 172 | is one, this is a response to a register setting change requested by the client. 173 | 174 | The `` is a one-byte value signifying the corresponding register number. 175 | 176 | The `` is variable length and dependent on the specific register. 177 | 178 | Registers are described below. 179 | 180 | ### Register update/ack (0xf6) 181 | 182 | ```text 183 | [f6][][][][][] 184 | ``` 185 | 186 | Used by the client to notify the car of either an ack of a received register update, or setting a new register value. 187 | 188 | If `` is zero, indicates that a register value is to be changed. The `` and `` fields indicate the register and new value. 189 | 190 | If `` is one, is a response to an update (above) received from the car. The `` field is the register value being acked. The `` field contains a single `0x0` byte. 191 | 192 | ### Init security (0x5e) 193 | 194 | ```text 195 | [5e][0c][00][][] 196 | ``` 197 | 198 | Sent by the car after around initial ping/keepalive exchanges. 199 | 200 | The `` contents are 12 bytes, used to initialise the XOR encryption key map (see above). 201 | 202 | This packet is not XOR encrypted. 203 | 204 | ### Init ack (0xe5) 205 | 206 | ```text 207 | [e5][04][01][0100][] 208 | ``` 209 | 210 | Sent in response to a 0x5e packet. Always seems to be the same. 211 | 212 | This packet is not XOR encrypted. 213 | 214 | ### Bad XOR (0xbb) 215 | 216 | ```text 217 | [bb][06][01][][] 218 | ``` 219 | 220 | Sent by the car if a received packet is encoded with the incorrect XOR value. 221 | 222 | The meaning of the value in the `` field is, well, unknown. 223 | 224 | The `` field contains the XOR value which is expected. If the offending 225 | packet is reset using this value for the Xor, then it will likely be accepted. 226 | 227 | This can be a workaround given the current unknown algorithm for generating 228 | XOR values. 229 | 230 | ## Registers 231 | 232 | Registers contain the bulk of information on the state of the vehicle. 233 | 234 | ### Read registers (car to client) 235 | 236 | There seem to be two types of register layout (A/B). 237 | 238 | | Register | Name | Length | Location | Fields | Description | 239 | |----------|------------------------------|--------|-----------|-------------------------------|-------------------------------------| 240 | |0x1 | ?? | 2 | 0 | [1,1] | | 241 | |0x2 | Battery warning | 4 | 2 | [1,1,1,1] | | 242 | |0x3 | ?? | 3 | 6 | [1,1,1] | | 243 | |0x4 | Charge timer settings | 20 / 1 | 10 / ?? | [3,1,3,1,3,1,3,1,3,1] / [] | | 244 | |0x5 | Climate timer settings | 16 / 1 | 30 / 235 | [1,2,1,2,1,2,1,2,1,2,1] / [1] | | 245 | |0x6 | ?? | 20 / 1 | 74 / 46 | [1,17,1,1] / [1] | Similar to 0x15 | 246 | |0x7 | ?? | 1 | 237 | [1] | | 247 | |0x8 | ?? | 1 | 234 | [1] | | 248 | |0x9 | ?? | 1 | 49 | [1] | | 249 | |0xa | ?? | 1 | 50 | [1] | | 250 | |0xb | ?? | 1 | 238 / 236 | [1] | | 251 | |0xc | ?? | 1 | 51 | [1] | | 252 | |0xd | ?? | 1 | 52 | [1] | | 253 | |0xe | ?? | 1 | 53 | [1] | | 254 | |0xf | ?? | 1 | 54 | [1] | | 255 | |0x10 | AirCon State | 3 / 1 | 55 | [1,1,1] / [1] | | 256 | |0x11 | ?? | 1 | 58 | [1] | | 257 | |0x12 | TimeSync | 7 | 59 | [7] | | 258 | |0x13 | ?? | 1 | 66 | [1] | | 259 | |0x14 | ?? | 7 | 67 | [6,1] | | 260 | |0x15 | VIN | 20 | 246 / 74 | [19,11] / [1,17,1,1] | | 261 | |0x16 | ?? | 8 | 95 | [8] | Seems to convey some other settings | 262 | |0x17 | ?? | 1 | 103 | [1] | | 263 | |0x18 | ?? | 4 / 16 | 276 / 104 | [1,1,2] / [5,3,5,3] | | 264 | |0x19 | ?? | 9 | 120 | [1,5,3] | | 265 | |0x1a | Ignition status | 5 / 2 | 129 | [1,1,1,1,1] / [1,1] | | 266 | |0x1b | ?? | 1 | 134 | [1] | | 267 | |0x1c | AirCon Mode | 1 | 136 | [1] | | 268 | |0x1d | Battery Level / light status | 4 | 137 | [1,1,1,1] | | 269 | |0x1e | Charge plug status | 2 | 141 | [1,1] | | 270 | |0x1f | Charge State | 3 | 143 | [1,2] | | 271 | |0x20 | ?? | 10 | 146 | [2,2,2,2,2] | | 272 | |0x21 | ?? | 1 | 156 | [1] | | 273 | |0x22 | ?? | 6 | 157 | [2,2,2] | | 274 | |0x23 | Interior/Hazard Lights + AC? | 5 | 163 | [1,1,1,1,1] | | 275 | |0x24 | Door Lock Status | 10 | 168 | [1,1,1,1,1,1,1,1,1,1] | | 276 | |0x25 | ?? | 3 | 178 | [1,1,1] | | 277 | |0x26 | ?? | 1 | 181 | [1] | | 278 | |0x27 | ?? | 1 | 182 | [1] | | 279 | |0x28 | ?? | 32 | 183 | [33] | | 280 | |0x29 | ?? | 3 / 2 | 216 | [1,1,1] / [1,1] | | 281 | |0x2a | ?? | 1 | 219 | [1] | | 282 | |0x2b | ?? | 10 | 220 | [10] | | 283 | |0x2c | ?? | 1 | 233 | [1] | | 284 | |0xc0 | ECU Version | 13 | 220 | [10,2,1] | | 285 | 286 | ### 0x02 - Battery warning 287 | 288 | ### 0x0b - Parking light status 289 | 290 | ### 0x05 - Climate timer 291 | 292 | 16 bytes. 293 | 294 | |Byte(s) | Description | 295 | |--------|-------------| 296 | | 0 | Unknown | 297 | | 1-3 | Timer 1 | 298 | | 4-6 | Timer 2 | 299 | | 7-9 | Timer 3 | 300 | | 10-12 | Timer 4 | 301 | | 13-15 | Timer 5 | 302 | 303 | #### Timer 1..5 304 | 305 | __must be converted from big endian to little endian__ to be useful 306 | 307 | ```text 308 | 0xa5f0afe -> 0xfef0a5 309 | ``` 310 | 311 | ```text 312 | 0xfef0a5 = 11111110 11110000 10100101 313 | | | | | | | 314 | Bit23 Bit17 | Bit9 | Bit0 315 | Bit12 Bit2 316 | ``` 317 | 318 | | __Bits__ | Description | 319 | |----------|---------------------------------------------| 320 | | 0-1 | Duration: 0=10min 1=20min 2=30min ?3=40min? | 321 | | 2 | Sunday | 322 | | 3 | Monday | 323 | | 4 | Tuesday | 324 | | 5 | Wednesday | 325 | | 6 | Thursday | 326 | | 7 | Friday | 327 | | 8 | Saturday | 328 | | 9-11 | Minute: 0=0 1=10 2=20 3=30 4=40 5=50 | 329 | | 12-16 | Hour: 0=0 1=1 2=2 ... 21=21 22=22 23=23 | 330 | | 17 | on | 331 | | 18 | off | 332 | | 19-23 | Unknown (unused?) | 333 | 334 | ### 0x10 - Preconditioning status 335 | 336 | 3 bytes. 337 | 338 | | Byte(s) | Description | 339 | |---------|-------------| 340 | | 0 | Preconditioning state [0 = off, 2 = on, 3 = cancelled by open door/low battery] | 341 | | 1 | Unknown | 342 | | 2 | Unknown | 343 | 344 | 02b00b = windscreen on/10min 345 | 026e09 = windscreen on/10min (on another vehicle) 346 | 030000 = after door openining 347 | 000000 = precondition not active/terminated normally (e.g. timer elapsed.) 348 | 349 | ### 0x12 - Car time sync 350 | 351 | ### 0x15 - Vin / registration state 352 | 353 | Vin info and regstration status. 354 | 355 | | Byte(s) | Description | 356 | |--|--| 357 | |0 | Unknown | 358 | |1-18 | VIN (ascii) | 359 | |19 | Number of registered clients | 360 | 361 | ### 0x17 - Charge timer state 362 | 363 | ### 0x1a - Ignition status 364 | 365 | Probably some other info, but at least ignition status is shown. 366 | 367 | | Byte | Description | 368 | |--|--| 369 | | 0 | Ignition state. 0x0=off 0x3=acc 0x4=on | 370 | | 1-4 | Unknown, currently only seen as 0x0 | 371 | 372 | ### 0x1c - Aircon mode 373 | 374 | Single byte. 375 | 376 | | Value | Description | 377 | |--|--| 378 | |0 | Unknown | 379 | |1 | Cooling | 380 | |2 | Heating | 381 | |3 | Windscreen | 382 | 383 | ### 0x1d - Drive battery level / parking light status 384 | 385 | ```text 386 | 10000003 387 | ``` 388 | 389 | | Byte(s) | Description | 390 | |--|--| 391 | |0 | Drive battery level % | 392 | |1 | Unknown | 393 | |2 | Parking light status 0/1 | 394 | |3 | Unknown | 395 | 396 | ### 0x1e - Charge plug status 397 | 398 | 0000 - Unplugged 399 | 0001 - Plugged in, not charging 400 | 401 | ### 0x1f - Charging status 402 | 403 | | Byte(s) | Description | 404 | |--|--| 405 | |0 | Charge status [0=not charging 1=charging]| 406 | | 1-2 | Charge time remaining | 407 | 408 | ### 0x23 - Interior/Hazard lights + Something AC? 409 | 410 | Interior lights ON: `0000000201` 411 | Interior lights OFF: `0000000202` 412 | Hazard lights ON: `0000000102` 413 | Hazard lights OFF: `0000000202` 414 | 415 | AC timer sniff: 416 | 417 | | Mode | Start | End | Register | 418 | |---|---|---|---| 419 | | heat | 0 | 10 | 0001000202 | 420 | | windscreen | 0 | 10 | 0101000202 | 421 | 422 | ### 0x24 - Door / Lock status 423 | 424 | ```text 425 | Byte 0 426 | | 427 | 1000000000 428 | | 429 | Byte 9 430 | ``` 431 | 432 | Below shows what is represented by each byte. For door/boot/bonnet, 433 | the value is 1 if open, else 0. 434 | 435 | 0 - Lock status [1=locked 2=unlocked] 436 | 437 | 3 - Drivers Door (side depends if LHD/RHD) 438 | 439 | 4 - Front Passenger Door (side depends if LHD/RHD) 440 | 441 | 5 - Read Right Door 442 | 443 | 6 - Rear Left Door 444 | 445 | 7 - Boot / Trunk 446 | 447 | 8 - Bonnet / Hood 448 | 449 | 9 - Headlight state 450 | 451 | ### 0xc0 - ECU Version string 452 | 453 | A string with the software version of the ECU. 454 | 455 | ## Write registers (client to car) 456 | 457 | | Register | Name | Description/values | 458 | |----------|----------------------------|------------------------| 459 | | 0x5 | Sync time | See below | 460 | | 0x6 | Request udpated state | 0x3 | 461 | | 0xa | Set head lights | 0x1=on 0x2=off | 462 | | 0xb | Set parking lights | 0x1=on 0x2=off | 463 | | 0xe | Save settings?? | Sent after 0xf command | 464 | | 0xf | Update settings | | 465 | | 0x10 | Register Wifi client | 0x1 | 466 | | 0x13 | Reset PreAC state | 0x1 | 467 | | 0x15 | Unregister Wifi client | 0x1 | 468 | | 0x1a | Set climate timer | See below | 469 | | 0x1b | Set climate state | See below | 470 | | 0x17 | Cancel charge timer | | 471 | | 0x19 | Set charge timer schedule | | 472 | | 0x1a | Set climate timer schedule | | 473 | 474 | ### 0x05 - Sync Time 475 | 476 | 8 bytes. 477 | 478 | | Byte(s) | Description | 479 | |---------|---------------| 480 | | 0 | Year - 2000 | 481 | | 1 | Month | 482 | | 2 | Day of month | 483 | | 3 | Hour | 484 | | 4 | Minute | 485 | | 5 | Second | 486 | | 6 | Day of week | 487 | | 7 | Device rooted | 488 | 489 | ### 0x10 - Register wifi client 490 | 491 | This command is issued when the car is in registration mode. A new client that connects 492 | to the car sends this command, then the car registers its mac address as a valid client. 493 | 494 | ### 0x15 - Unregister Wifi client 495 | 496 | This command is issued in any mode (registration or otherwise). It removes the Wifi 497 | registration for the client (based on the MAC address it sees for the TCP client). 498 | 499 | ### 0x1a - set climate timer 500 | 501 | 16 bytes. 502 | 503 | |Byte(s) | Description | 504 | |--------|-------------| 505 | | 0-2 | Timer 1 | 506 | | 3-5 | Timer 2 | 507 | | 6-8 | Timer 3 | 508 | | 9-11 | Timer 4 | 509 | | 12-14 | Timer 5 | 510 | | 15 | Unknown | 511 | 512 | The Encoding for Timer 1 to 5 is the same as for [reading](#timer-15) 513 | 514 | ### 0x1b - set climate state 515 | 516 | ```text 517 | [02[state][duration][start]] 518 | ``` 519 | 520 | * Byte 0 - 02 521 | * Byte 1 - climate state 522 | * 01 - cooling 523 | * 02 - heating 524 | * 03 - windscreen 525 | * Byte 2 - Duration 526 | * 00 - 10 mins 527 | * 01 - 20 mins 528 | * 02 - 30 mins 529 | * Byte 3 - Delay before start 530 | * 00 - 0 mins / now 531 | * 01 - 5 mins 532 | * 02 - 10 mins 533 | 534 | ## Notes 535 | 536 | Things discovered sniffing the app... 537 | 538 | ```text 539 | AC data sniff. 540 | 541 | Windscreen for 10 mins: 542 | 543 | INFO[0000] out [a1] REGISTER SET (reg 0x1b data 02030000) 544 | INFO[0000] in [a1] REGISTER NTFY (reg 0x10 data 02b00b) 545 | INFO[0000] in [55] REGISTER NTFY (reg 0x1a data 0001000000) 546 | INFO[0000] in [70] REGISTER NTFY (reg 0x1c data 03) 547 | 548 | Heat in 5 mins for 10 mins: 549 | 550 | INFO[0000] out [70] REGISTER SET (reg 0x1b data 02020001) 551 | INFO[0000] in [01] REGISTER NTFY (reg 0x1a data 0000000101) 552 | INFO[0000] in [86] REGISTER NTFY (reg 0x1c data 02) 553 | 554 | Heat in 0 mins for 10 mins: 555 | 556 | INFO[0000] out [73] REGISTER SET (reg 0x1b data 02020000) 557 | INFO[0000] in [73] REGISTER NTFY (reg 0x10 data 02b020) 558 | INFO[0000] in [22] REGISTER NTFY (reg 0x1a data 0001000000) 559 | INFO[0000] in [50] REGISTER NTFY (reg 0x1c data 02) 560 | 561 | Heat in 0 mins for 20 mins 562 | INFO[0000] out [4e] REGISTER SET (reg 0x1b data 02020100) 563 | INFO[0000] in [1c] REGISTER NTFY (reg 0x10 data 02b034) 564 | INFO[0000] in [e7] REGISTER NTFY (reg 0x1a data 0001010000) 565 | INFO[0000] in [c6] REGISTER NTFY (reg 0x1c data 02) 566 | 567 | Cool 0 mins for 10 mins 568 | INFO[0170] out [5f] REGISTER SET (reg 0x1b data 02010000) 569 | INFO[0170] in [5b] REGISTER NTFY (reg 0x10 data 02b139) 570 | INFO[0171] in [18] REGISTER NTFY (reg 0x1a data 0001000000) 571 | INFO[0171] in [95] REGISTER NTFY (reg 0x1c data 01) 572 | 573 | Cool 10 mins for 10 mins 574 | SETREG 0x1b: -> 02010002 575 | 576 | Climate timer: 577 | t1 12:00 cool for 10 mins repeat sun: 578 | set 0x1a: -> 04c00200fe0700fe0700fe0700fe0701 579 | get 0x05: -> 0100fe0700fe0700fe0700fe0700fe07 580 | 581 | t2 07:50 cool for 20 mins repeat sunMonTue: 582 | set 0x1a: -> 04c0021d7a0200fe0700fe0700fe0701 583 | get 0x05: -> 0204c00200fe0700fe0700fe0700fe07 584 | 585 | disable all: 586 | 587 | set 0x1a: 04c0041d7a0400fe0700fe0700fe0701 588 | 589 | reset all: 590 | 591 | set 0x1a: 00fe0700fe0700fe0700fe0700fe0701 592 | 593 | Unplug charger (disabled due timer): 594 | 595 | UPDATEREG 0x0c: 01 -> 04 596 | UPDATEREG 0x0d: 01 -> 02 597 | UPDATEREG 0x1e: 0001 -> 0000 598 | 599 | Plug in charger (disabled due timer): 600 | 601 | UPDATEREG 0x0d: 02 -> 01 602 | UPDATEREG 0x1e: 0000 -> 0001 603 | 604 | Plug in charger (within time period): 605 | phev/register/1e 0002 606 | charge starts: 607 | phev/register/1e 0202 608 | 609 | unplug: 610 | phev/register/1e 0002 611 | then: 612 | phev/register/1e 0003 613 | 614 | plug in: 615 | phev/register/1e 0002 616 | (charges) 617 | 618 | unplug from charging: 619 | 620 | UPDATEREG 0x1e: 0202 -> 0102 621 | UPDATEREG 0x1e: 0102 -> 0002 622 | UPDATEREG 0x1e: 0002 -> 0003 623 | 624 | plug in, charge: 625 | 626 | UPDATEREG 0x1e: 0000 -> 0002 627 | UPDATEREG 0x1e: 0002 -> 0202 628 | 629 | Charge timer: 630 | 631 | disabl timer3: 0x19: 7d38b00183bd00017c70380200ffff0300ffff0302 632 | enable timer3: 0x19: 7d38b00183bd00017c70380100ffff0300ffff0302 633 | 634 | settings at 0x4 635 | 636 | setting "exterior lights on rmt unlock: 637 | 638 | - off -> 0x0f=2b00 639 | - parking -> 0x0f=2b01 640 | - head -> 0x0f=2b02 641 | 642 | setting "charge light cutout" 643 | 644 | - off -> 0x0f=0700 645 | - 1min -> 0x0f=0701 646 | - 2min -> 0x0f=0702 647 | - 5min -> 0x0f=0703 648 | - 10min -> 0x0f=0704 649 | 650 | setting "headlights on exiting vehicle" 651 | 652 | - off -> 0x0f=2a00 653 | - 15s -> 0x0f=2a01 654 | - 30s -> 0x0f=2a02 655 | - 1min-> 0x0f=2a03 656 | - 3min-> 0x0f=2a04 657 | 658 | light ones above followed by setting 0x0e->0x0 659 | ``` 660 | -------------------------------------------------------------------------------- /cmd/mqtt.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2021 Ben Buxton 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | package cmd 18 | 19 | import ( 20 | "bytes" 21 | "encoding/hex" 22 | "fmt" 23 | "github.com/buxtronix/phev2mqtt/client" 24 | "github.com/buxtronix/phev2mqtt/protocol" 25 | "github.com/spf13/cobra" 26 | "github.com/spf13/viper" 27 | "os/exec" 28 | "strings" 29 | "time" 30 | 31 | mqtt "github.com/eclipse/paho.mqtt.golang" 32 | log "github.com/sirupsen/logrus" 33 | ) 34 | 35 | const defaultWifiRestartCmd = "sudo ip link set wlan0 down && sleep 3 && sudo ip link set wlan0 up" 36 | 37 | // mqttCmd represents the mqtt command 38 | var mqttCmd = &cobra.Command{ 39 | Use: "mqtt", 40 | Short: "Start an MQTT bridge.", 41 | Long: `Maintains a connected to the Phev (retry as needed) and also to an MQTT server. 42 | 43 | Status data from the car is passed to the MQTT topics, and also some commands from MQTT 44 | are sent to control certain aspects of the car. See the phev2mqtt Github page for 45 | more details on the topics. 46 | `, 47 | SilenceUsage: true, 48 | RunE: func(cmd *cobra.Command, args []string) error { 49 | mc := &mqttClient{climate: new(climate)} 50 | return mc.Run(cmd, args) 51 | }, 52 | } 53 | 54 | // Tracks complete climate state as on and mode are separately 55 | // sent by the car. 56 | type climate struct { 57 | state *protocol.PreACState 58 | mode *string 59 | } 60 | 61 | func (c *climate) setMode(m string) { 62 | c.mode = &m 63 | } 64 | func (c *climate) setState(state protocol.PreACState) { 65 | c.state = &state 66 | } 67 | 68 | func (c *climate) mqttStates() map[string]string { 69 | m := map[string]string{ 70 | "/climate/state": "off", 71 | "/climate/cool": "off", 72 | "/climate/heat": "off", 73 | "/climate/windscreen": "off", 74 | } 75 | if c.mode == nil || c.state == nil { 76 | return m 77 | } 78 | switch *c.state { 79 | case protocol.PreACOn: m["/climate/state"] = *c.mode 80 | case protocol.PreACOff: { 81 | m["/climate/state"] = "off" 82 | return m 83 | } 84 | case protocol.PreACTerminated: { 85 | m["/climate/state"] = "terminated" 86 | return m 87 | } 88 | default: { 89 | m["/climate/state"] = "unknown" 90 | return m 91 | } 92 | } 93 | m["/climate/state"] = *c.mode 94 | switch *c.mode { 95 | case "cool": 96 | m["/climate/cool"] = "on" 97 | case "heat": 98 | m["/climate/heat"] = "on" 99 | case "windscreen": 100 | m["/climate/windscreen"] = "on" 101 | } 102 | return m 103 | } 104 | 105 | var lastWifiRestart time.Time 106 | 107 | func restartWifi(cmd *cobra.Command) error { 108 | restartRetryTime := viper.GetDuration("wifi_restart_retry_time") 109 | 110 | if time.Now().Sub(lastWifiRestart) < restartRetryTime { 111 | return nil 112 | } 113 | defer func() { 114 | lastWifiRestart = time.Now() 115 | }() 116 | 117 | restartCommand := viper.GetString("wifi_restart_command") 118 | if restartCommand == "" { 119 | log.Debugf("wifi restart disabled") 120 | return nil 121 | } 122 | 123 | log.Debugf("Attempting to restart wifi") 124 | 125 | restartCmd := exec.Command("/bin/sh", "-c", restartCommand) 126 | 127 | stdoutStderr, err := restartCmd.CombinedOutput() 128 | if len( stdoutStderr ) > 0 { 129 | log.Infof("Output from wifi restart: %s", stdoutStderr) 130 | } 131 | return err 132 | } 133 | 134 | type mqttClient struct { 135 | client mqtt.Client 136 | options *mqtt.ClientOptions 137 | mqttData map[string]string 138 | updateInterval time.Duration 139 | 140 | phev *client.Client 141 | lastConnect time.Time 142 | lastError error 143 | 144 | prefix string 145 | 146 | haDiscovery bool 147 | haDiscoveryPrefix string 148 | haPublishedDiscovery bool 149 | 150 | climate *climate 151 | enabled bool 152 | } 153 | 154 | func (m *mqttClient) topic(topic string) string { 155 | return fmt.Sprintf("%s%s", m.prefix, topic) 156 | } 157 | 158 | func (m *mqttClient) Run(cmd *cobra.Command, args []string) error { 159 | m.enabled = true // Default. 160 | 161 | mqttServer := viper.GetString("mqtt_server") 162 | mqttUsername := viper.GetString("mqtt_username") 163 | mqttPassword := viper.GetString("mqtt_password") 164 | mqttDisableSet := viper.GetBool("mqtt_disable_register_set_command") 165 | m.prefix = viper.GetString("mqtt_topic_prefix") 166 | m.haDiscovery = viper.GetBool("ha_discovery") 167 | m.haDiscoveryPrefix = viper.GetString("ha_discovery_prefix") 168 | m.updateInterval = viper.GetDuration("update_interval") 169 | wifiRestartTime := viper.GetDuration("wifi_restart_time") 170 | restartCommand := viper.GetString("wifi_restart_command") 171 | 172 | if restartCommand == "" { 173 | log.Infof("WiFi restart disabled") 174 | } 175 | 176 | m.haPublishedDiscovery = false 177 | m.lastError = nil 178 | 179 | m.options = mqtt.NewClientOptions(). 180 | AddBroker(mqttServer). 181 | SetClientID("phev2mqtt"). 182 | SetUsername(mqttUsername). 183 | SetPassword(mqttPassword). 184 | SetAutoReconnect(true). 185 | SetDefaultPublishHandler(m.handleIncomingMqtt). 186 | SetWill(m.topic("/available"), "offline", 0, true) 187 | 188 | m.client = mqtt.NewClient(m.options) 189 | if token := m.client.Connect(); token.Wait() && token.Error() != nil { 190 | return token.Error() 191 | } 192 | 193 | if !mqttDisableSet { 194 | if token := m.client.Subscribe(m.topic("/set/#"), 0, nil); token.Wait() && token.Error() != nil { 195 | return token.Error() 196 | } 197 | } else { 198 | log.Info("Setting vechicle registers via MQTT is disabled") 199 | } 200 | if token := m.client.Subscribe(m.topic("/connection"), 0, nil); token.Wait() && token.Error() != nil { 201 | return token.Error() 202 | } 203 | if token := m.client.Subscribe(m.topic("/settings/#"), 0, nil); token.Wait() && token.Error() != nil { 204 | return token.Error() 205 | } 206 | 207 | m.mqttData = map[string]string{} 208 | 209 | for { 210 | if m.enabled { 211 | if err := m.handlePhev(cmd); err != nil { 212 | // Do not flood the log with the same messages every second 213 | if m.lastError == nil || m.lastError.Error() != err.Error() { 214 | log.Error(err) 215 | m.lastError = err 216 | } 217 | } 218 | // Publish as offline if last connection was >30s ago. 219 | if time.Now().Sub(m.lastConnect) > 30*time.Second { 220 | m.client.Publish(m.topic("/available"), 0, true, "offline") 221 | } 222 | // Restart Wifi interface if > wifi_restart_time. 223 | if wifiRestartTime > 0 && time.Now().Sub(m.lastConnect) > wifiRestartTime { 224 | if err := restartWifi(cmd); err != nil { 225 | log.Errorf("Error restarting wifi: %v", err) 226 | } 227 | } 228 | } 229 | 230 | time.Sleep(time.Second) 231 | } 232 | } 233 | 234 | func (m *mqttClient) publish(topic, payload string) { 235 | // if cache := m.mqttData[topic]; cache != payload { 236 | m.client.Publish(m.topic(topic), 0, false, payload) 237 | m.mqttData[topic] = payload 238 | // } 239 | } 240 | 241 | func (m *mqttClient) handleIncomingMqtt(mqtt_client mqtt.Client, msg mqtt.Message) { 242 | log.Infof("Topic: [%s] Payload: [%s]", msg.Topic(), msg.Payload()) 243 | 244 | topicParts := strings.Split(msg.Topic(), "/") 245 | if strings.HasPrefix(msg.Topic(), m.topic("/set/register/")) { 246 | if len(topicParts) != 4 { 247 | log.Infof("Bad topic format [%s]", msg.Topic()) 248 | return 249 | } 250 | register, err := hex.DecodeString(topicParts[3]) 251 | if err != nil { 252 | log.Infof("Bad register in topic [%s]: %v", msg.Topic(), err) 253 | return 254 | } 255 | data, err := hex.DecodeString(string(msg.Payload())) 256 | if err != nil { 257 | log.Infof("Bad payload [%s]: %v", msg.Payload(), err) 258 | return 259 | } 260 | if err := m.phev.SetRegister(register[0], data); err != nil { 261 | log.Infof("Error setting register %02x: %v", register[0], err) 262 | return 263 | } 264 | } else if msg.Topic() == m.topic("/connection") { 265 | payload := strings.ToLower(string(msg.Payload())) 266 | switch payload { 267 | case "off": 268 | m.enabled = false 269 | m.phev.Close() 270 | m.client.Publish(m.topic("/available"), 0, true, "offline") 271 | case "on": 272 | m.enabled = true 273 | case "restart": 274 | m.enabled = true 275 | m.client.Publish(m.topic("/available"), 0, true, "offline") 276 | m.phev.Close() 277 | } 278 | } else if msg.Topic() == m.topic("/set/parkinglights") { 279 | values := map[string]byte{"on": 0x1, "off": 0x2} 280 | if v, ok := values[strings.ToLower(string(msg.Payload()))]; ok { 281 | if err := m.phev.SetRegister(0xb, []byte{v}); err != nil { 282 | log.Infof("Error setting register 0xb: %v", err) 283 | return 284 | } 285 | } 286 | } else if msg.Topic() == m.topic("/set/headlights") { 287 | values := map[string]byte{"on": 0x1, "off": 0x2} 288 | if v, ok := values[strings.ToLower(string(msg.Payload()))]; ok { 289 | if err := m.phev.SetRegister(0xa, []byte{v}); err != nil { 290 | log.Infof("Error setting register 0xb: %v", err) 291 | return 292 | } 293 | } 294 | } else if msg.Topic() == m.topic("/set/cancelchargetimer") { 295 | if err := m.phev.SetRegister(0x17, []byte{0x1}); err != nil { 296 | log.Infof("Error setting register 0x17: %v", err) 297 | return 298 | } 299 | if err := m.phev.SetRegister(0x17, []byte{0x11}); err != nil { 300 | log.Infof("Error setting register 0x17: %v", err) 301 | return 302 | } 303 | } else if strings.HasPrefix(msg.Topic(), m.topic("/set/climate/state")) { 304 | payload := strings.ToLower(string(msg.Payload())) 305 | if payload == "reset" { 306 | if err := m.phev.SetRegister(protocol.SetAckPreACTermRegister, []byte{0x1}); err != nil { 307 | log.Infof("Error acknowledging Pre-AC termination: %v", err) 308 | return 309 | } 310 | } 311 | } else if strings.HasPrefix(msg.Topic(), m.topic("/set/climate/")) { 312 | topic := msg.Topic() 313 | payload := strings.ToLower(string(msg.Payload())) 314 | 315 | modeMap := map[string]byte{"off": 0x0, "OFF": 0x0, "cool": 0x1, "heat": 0x2, "windscreen": 0x3, "mode": 0x4} 316 | durMap := map[string]byte{"10": 0x0, "20": 0x1, "30": 0x2, "on": 0x0, "off": 0x0} 317 | parts := strings.Split(topic, "/") 318 | mode, ok := modeMap[parts[len(parts)-1]] 319 | if !ok { 320 | log.Errorf("Unknown climate mode: %s", parts[len(parts)-1]) 321 | return 322 | } 323 | if mode == 0x4 { // set/climate/mode -> "heat" 324 | mode = modeMap[payload] 325 | payload = "on" 326 | } 327 | if payload == "off" { 328 | mode = 0x0 329 | } 330 | duration, ok := durMap[payload] 331 | if mode != 0x0 && !ok { 332 | log.Errorf("Unknown climate duration: %s", payload) 333 | return 334 | } 335 | 336 | if m.phev.ModelYear == client.ModelYear14 { 337 | // Set the AC mode first 338 | registerPayload := bytes.Repeat([]byte{0xff}, 15) 339 | registerPayload[0] = 0x0 340 | registerPayload[1] = 0x0 341 | registerPayload[6] = mode | duration 342 | if err := m.phev.SetRegister(protocol.SetACModeRegisterMY14, registerPayload); err != nil { 343 | log.Infof("Error setting AC mode: %v", err) 344 | return 345 | } 346 | 347 | // Then, enable/disable the AC 348 | acEnabled := byte(0x02) 349 | if mode == 0x0 { 350 | acEnabled = 0x01 351 | } 352 | if err := m.phev.SetRegister(protocol.SetACEnabledRegisterMY14, []byte{acEnabled}); err != nil { 353 | log.Infof("Error setting AC enabled state: %v", err) 354 | return 355 | } 356 | } else if m.phev.ModelYear == client.ModelYear18 || m.phev.ModelYear == client.ModelYear24 { 357 | state := byte(0x02) 358 | if mode == 0x0 { 359 | state = 0x1 360 | } 361 | if err := m.phev.SetRegister(protocol.SetACModeRegisterMY18, []byte{state, mode, duration, 0x0}); err != nil { 362 | log.Infof("Error setting AC mode: %v", err) 363 | return 364 | } 365 | } 366 | } else if msg.Topic() == m.topic("/settings/dump") { 367 | log.Infof("CURRENT_SETTINGS:") 368 | log.Infof("\n%s", m.phev.Settings.Dump()) 369 | m.phev.Settings.Clear() 370 | } else { 371 | log.Errorf("Unknown topic from mqtt: %s", msg.Topic()) 372 | } 373 | } 374 | 375 | func (m *mqttClient) handlePhev(cmd *cobra.Command) error { 376 | var err error 377 | address := viper.GetString("address") 378 | m.phev, err = client.New(client.AddressOption(address)) 379 | if err != nil { 380 | return err 381 | } 382 | 383 | if err := m.phev.Connect(); err != nil { 384 | return err 385 | } 386 | 387 | if err := m.phev.Start(); err != nil { 388 | return err 389 | } 390 | m.client.Publish(m.topic("/available"), 0, true, "online") 391 | 392 | m.lastError = nil 393 | 394 | defer func() { 395 | m.lastConnect = time.Now() 396 | }() 397 | 398 | var encodingErrorCount = 0 399 | var lastEncodingError time.Time 400 | 401 | updaterTicker := time.NewTicker(m.updateInterval) 402 | for { 403 | select { 404 | case <-updaterTicker.C: 405 | m.phev.SetRegister(0x6, []byte{0x3}) 406 | case msg, ok := <-m.phev.Recv: 407 | if !ok { 408 | log.Infof("Connection closed.") 409 | updaterTicker.Stop() 410 | return fmt.Errorf("Connection closed.") 411 | } 412 | switch msg.Type { 413 | case protocol.CmdInBadEncoding: 414 | if time.Now().Sub(lastEncodingError) > 15*time.Second { 415 | encodingErrorCount = 0 416 | } 417 | if encodingErrorCount > 50 { 418 | m.phev.Close() 419 | updaterTicker.Stop() 420 | return fmt.Errorf("Disconnecting due to too many errors") 421 | } 422 | encodingErrorCount += 1 423 | lastEncodingError = time.Now() 424 | case protocol.CmdInResp: 425 | if msg.Ack != protocol.Request { 426 | break 427 | } 428 | m.publishRegister(msg) 429 | m.phev.Send <- &protocol.PhevMessage{ 430 | Type: protocol.CmdOutSend, 431 | Register: msg.Register, 432 | Ack: protocol.Ack, 433 | Xor: msg.Xor, 434 | Data: []byte{0x0}, 435 | } 436 | } 437 | } 438 | } 439 | } 440 | 441 | var boolOnOff = map[bool]string{ 442 | false: "off", 443 | true: "on", 444 | } 445 | var boolOpen = map[bool]string{ 446 | false: "closed", 447 | true: "open", 448 | } 449 | 450 | func (m *mqttClient) publishRegister(msg *protocol.PhevMessage) { 451 | dataStr := hex.EncodeToString(msg.Data) 452 | m.publish(fmt.Sprintf("/register/%02x", msg.Register), dataStr) 453 | switch reg := msg.Reg.(type) { 454 | case *protocol.RegisterVIN: 455 | m.publish("/vin", reg.VIN) 456 | m.publishHomeAssistantDiscovery(reg.VIN, m.prefix, "Phev") 457 | m.publish("/registrations", fmt.Sprintf("%d", reg.Registrations)) 458 | case *protocol.RegisterECUVersion: 459 | m.publish("/ecuversion", reg.Version) 460 | case *protocol.RegisterACMode: 461 | m.climate.setMode(reg.Mode) 462 | for t, p := range m.climate.mqttStates() { 463 | m.publish(t, p) 464 | } 465 | case *protocol.RegisterPreACState: 466 | m.climate.setState(reg.State) 467 | for t, p := range m.climate.mqttStates() { 468 | m.publish(t, p) 469 | } 470 | case *protocol.RegisterChargeStatus: 471 | m.publish("/charge/charging", boolOnOff[reg.Charging]) 472 | if reg.Remaining < 1000 { 473 | m.publish("/charge/remaining", fmt.Sprintf("%d", reg.Remaining)) 474 | } else { 475 | log.Debugf("Ignoring charge remanining reading: %v", reg.Remaining) 476 | if cache := m.mqttData["/charge/remaining"]; cache != "" { 477 | m.publish("/charge/remaining", cache) 478 | log.Debugf("Publishing last best known charge remaining reading: %v", cache) 479 | } 480 | } 481 | case *protocol.RegisterDoorStatus: 482 | m.publish("/door/locked", boolOpen[!reg.Locked]) 483 | m.publish("/door/rear_left", boolOpen[reg.RearLeft]) 484 | m.publish("/door/rear_right", boolOpen[reg.RearRight]) 485 | m.publish("/door/front_right", boolOpen[reg.Driver]) 486 | m.publish("/door/driver", boolOpen[reg.Driver]) 487 | m.publish("/door/front_left", boolOpen[reg.FrontPassenger]) 488 | m.publish("/door/front_passenger", boolOpen[reg.FrontPassenger]) 489 | m.publish("/door/bonnet", boolOpen[reg.Bonnet]) 490 | m.publish("/door/boot", boolOpen[reg.Boot]) 491 | m.publish("/lights/head", boolOnOff[reg.Headlights]) 492 | case *protocol.RegisterBatteryLevel: 493 | if (reg.Level > 5) && (reg.Level < 255) { 494 | m.publish("/battery/level", fmt.Sprintf("%d", reg.Level)) 495 | } else { 496 | if cache := m.mqttData["/battery/level"]; cache != "" { 497 | m.publish("/battery/level", cache ) 498 | log.Debugf("Ignoring battery level reading: %v, publishing last best known: %v", reg.Level, cache) 499 | } 500 | } 501 | m.publish("/lights/parking", boolOnOff[reg.ParkingLights]) 502 | case *protocol.RegisterLightStatus: 503 | m.publish("/lights/interior", boolOnOff[reg.Interior]) 504 | m.publish("/lights/hazard", boolOnOff[reg.Hazard]) 505 | case *protocol.RegisterChargePlug: 506 | if reg.Connected { 507 | m.publish("/charge/plug", "connected") 508 | } else { 509 | m.publish("/charge/plug", "unplugged") 510 | } 511 | } 512 | } 513 | 514 | // Publish home assistant discovery message. 515 | // Uses the vehicle VIN, so sent after VIN discovery. 516 | func (m *mqttClient) publishHomeAssistantDiscovery(vin, topic, name string) { 517 | 518 | if m.haPublishedDiscovery || !m.haDiscovery { 519 | return 520 | } 521 | m.haPublishedDiscovery = true 522 | discoveryData := map[string]string{ 523 | // Doors. 524 | "%s/binary_sensor/%s_door_locked/config": `{ 525 | "device_class": "lock", 526 | "name": "__NAME__ Locked", 527 | "state_topic": "~/door/locked", 528 | "payload_off": "closed", 529 | "payload_on": "open", 530 | "avty_t": "~/available", 531 | "unique_id": "__VIN___door_locked", 532 | "device": { 533 | "name": "PHEV __VIN__", 534 | "identifiers": ["phev-__VIN__"], 535 | "manufacturer": "Mitsubishi", 536 | "model": "Outlander PHEV"}, 537 | "~": "__TOPIC__"}`, 538 | "%s/binary_sensor/%s_door_bonnet/config": `{ 539 | "device_class": "door", 540 | "name": "__NAME__ Bonnet", 541 | "state_topic": "~/door/bonnet", 542 | "payload_off": "closed", 543 | "payload_on": "open", 544 | "avty_t": "~/available", 545 | "unique_id": "__VIN___door_bonnet", 546 | "device": { 547 | "name": "PHEV __VIN__", 548 | "identifiers": ["phev-__VIN__"], 549 | "manufacturer": "Mitsubishi", 550 | "model": "Outlander PHEV"}, 551 | "~": "__TOPIC__"}`, 552 | "%s/binary_sensor/%s_door_boot/config": `{ 553 | "device_class": "door", 554 | "name": "__NAME__ Boot", 555 | "state_topic": "~/door/boot", 556 | "payload_off": "closed", 557 | "payload_on": "open", 558 | "avty_t": "~/available", 559 | "unique_id": "__VIN___door_boot", 560 | "dev": { 561 | "name": "PHEV __VIN__", 562 | "identifiers": ["phev-__VIN__"], 563 | "manufacturer": "Mitsubishi", 564 | "model": "Outlander PHEV" 565 | }, 566 | "~": "__TOPIC__"}`, 567 | "%s/binary_sensor/%s_door_front_passenger/config": `{ 568 | "device_class": "door", 569 | "name": "__NAME__ Front Passenger Door", 570 | "state_topic": "~/door/front_passenger", 571 | "payload_off": "closed", 572 | "payload_on": "open", 573 | "avty_t": "~/available", 574 | "unique_id": "__VIN___door_front_passenger", 575 | "dev": { 576 | "name": "PHEV __VIN__", 577 | "identifiers": ["phev-__VIN__"], 578 | "manufacturer": "Mitsubishi", 579 | "model": "Outlander PHEV" 580 | }, 581 | "~": "__TOPIC__"}`, 582 | "%s/binary_sensor/%s_door_driver/config": `{ 583 | "device_class": "door", 584 | "name": "__NAME__ Driver Door", 585 | "state_topic": "~/door/driver", 586 | "payload_off": "closed", 587 | "payload_on": "open", 588 | "avty_t": "~/available", 589 | "unique_id": "__VIN___door_driver", 590 | "dev": { 591 | "name": "PHEV __VIN__", 592 | "identifiers": ["phev-__VIN__"], 593 | "manufacturer": "Mitsubishi", 594 | "model": "Outlander PHEV" 595 | }, 596 | "~": "__TOPIC__"}`, 597 | "%s/binary_sensor/%s_door_rear_left/config": `{ 598 | "device_class": "door", 599 | "name": "__NAME__ Rear Left Door", 600 | "state_topic": "~/door/rear_left", 601 | "payload_off": "closed", 602 | "payload_on": "open", 603 | "avty_t": "~/available", 604 | "unique_id": "__VIN___door_rear_left", 605 | "dev": { 606 | "name": "PHEV __VIN__", 607 | "identifiers": ["phev-__VIN__"], 608 | "manufacturer": "Mitsubishi", 609 | "model": "Outlander PHEV" 610 | }, 611 | "~": "__TOPIC__"}`, 612 | "%s/binary_sensor/%s_door_rear_right/config": `{ 613 | "device_class": "door", 614 | "name": "__NAME__ Rear Right Door", 615 | "state_topic": "~/door/rear_right", 616 | "payload_off": "closed", 617 | "payload_on": "open", 618 | "avty_t": "~/available", 619 | "unique_id": "__VIN___door_rear_right", 620 | "dev": { 621 | "name": "PHEV __VIN__", 622 | "identifiers": ["phev-__VIN__"], 623 | "manufacturer": "Mitsubishi", 624 | "model": "Outlander PHEV" 625 | }, 626 | "~": "__TOPIC__"}`, 627 | 628 | // Battery and charging 629 | "%s/sensor/%s_battery_level/config": `{ 630 | "device_class": "battery", 631 | "name": "__NAME__ Battery", 632 | "state_topic": "~/battery/level", 633 | "state_class": "measurement", 634 | "unit_of_measurement": "%", 635 | "avty_t": "~/available", 636 | "unique_id": "__VIN___battery_level", 637 | "dev": { 638 | "name": "PHEV __VIN__", 639 | "identifiers": ["phev-__VIN__"], 640 | "manufacturer": "Mitsubishi", 641 | "model": "Outlander PHEV" 642 | }, 643 | "~": "__TOPIC__"}`, 644 | "%s/sensor/%s_battery_charge_remaining/config": `{ 645 | "name": "__NAME__ Charge Remaining", 646 | "state_topic": "~/charge/remaining", 647 | "unit_of_measurement": "min", 648 | "avty_t": "~/available", 649 | "unique_id": "__VIN___battery_charge_remaining", 650 | "dev": { 651 | "name": "PHEV __VIN__", 652 | "identifiers": ["phev-__VIN__"], 653 | "manufacturer": "Mitsubishi", 654 | "model": "Outlander PHEV" 655 | }, 656 | "~": "__TOPIC__"}`, 657 | "%s/binary_sensor/%s_charger_connected/config": `{ 658 | "device_class": "plug", 659 | "name": "__NAME__ Charger Connected", 660 | "state_topic": "~/charge/plug", 661 | "payload_on": "connected", 662 | "payload_off": "unplugged", 663 | "avty_t": "~/available", 664 | "unique_id": "__VIN___charger_connected", 665 | "dev": { 666 | "name": "PHEV __VIN__", 667 | "identifiers": ["phev-__VIN__"], 668 | "manufacturer": "Mitsubishi", 669 | "model": "Outlander PHEV" 670 | }, 671 | "~": "__TOPIC__"}`, 672 | "%s/binary_sensor/%s_battery_charging/config": `{ 673 | "device_class": "battery_charging", 674 | "name": "__NAME__ Charging", 675 | "state_topic": "~/charge/charging", 676 | "payload_on": "on", 677 | "payload_off": "off", 678 | "avty_t": "~/available", 679 | "unique_id": "__VIN___battery_charging", 680 | "dev": { 681 | "name": "PHEV __VIN__", 682 | "identifiers": ["phev-__VIN__"], 683 | "manufacturer": "Mitsubishi", 684 | "model": "Outlander PHEV" 685 | }, 686 | "~": "__TOPIC__"}`, 687 | "%s/switch/%s_cancel_charge_timer/config": `{ 688 | "name": "__NAME__ Disable Charge Timer", 689 | "icon": "mdi:timer-off", 690 | "state_topic": "~/battery/charging", 691 | "command_topic": "~/set/cancelchargetimer", 692 | "avty_t": "~/available", 693 | "unique_id": "__VIN___cancel_charge_timer", 694 | "dev": { 695 | "name": "PHEV __VIN__", 696 | "identifiers": ["phev-__VIN__"], 697 | "manufacturer": "Mitsubishi", 698 | "model": "Outlander PHEV" 699 | }, 700 | "~": "__TOPIC__"}`, 701 | // Climate 702 | "%s/switch/%s_climate_heat/config": `{ 703 | "name": "__NAME__ Heat", 704 | "icon": "mdi:weather-sunny", 705 | "state_topic": "~/climate/heat", 706 | "command_topic": "~/set/climate/heat", 707 | "payload_off": "off", 708 | "payload_on": "on", 709 | "avty_t": "~/available", 710 | "unique_id": "__VIN___climate_heat", 711 | "dev": { 712 | "name": "PHEV __VIN__", 713 | "identifiers": ["phev-__VIN__"], 714 | "manufacturer": "Mitsubishi", 715 | "model": "Outlander PHEV" 716 | }, 717 | "~": "__TOPIC__"}`, 718 | "%s/switch/%s_climate_cool/config": `{ 719 | "name": "__NAME__ cool", 720 | "icon": "mdi:air-conditioner", 721 | "state_topic": "~/climate/cool", 722 | "command_topic": "~/set/climate/cool", 723 | "payload_off": "off", 724 | "payload_on": "on", 725 | "avty_t": "~/available", 726 | "unique_id": "__VIN___climate_cool", 727 | "dev": { 728 | "name": "PHEV __VIN__", 729 | "identifiers": ["phev-__VIN__"], 730 | "manufacturer": "Mitsubishi", 731 | "model": "Outlander PHEV" 732 | }, 733 | "~": "__TOPIC__"}`, 734 | "%s/switch/%s_climate_windscreen/config": `{ 735 | "name": "__NAME__ windscreen", 736 | "state_topic": "~/climate/windscreen", 737 | "command_topic": "~/set/climate/windscreen", 738 | "payload_off": "off", 739 | "payload_on": "on", 740 | "avty_t": "~/available", 741 | "unique_id": "__VIN___climate_windscreen", 742 | "dev": { 743 | "name": "PHEV __VIN__", 744 | "identifiers": ["phev-__VIN__"], 745 | "manufacturer": "Mitsubishi", 746 | "model": "Outlander PHEV" 747 | }, 748 | "icon": "mdi:car-defrost-front", 749 | "~": "__TOPIC__"}`, 750 | "%s/select/%s_climate_on/config": `{ 751 | "name": "__NAME__ climate state", 752 | "state_topic": "~/climate/mode", 753 | "command_topic": "~/set/climate/mode", 754 | "options": [ "off", "heat", "cool", "windscreen"], 755 | "avty_t": "~/available", 756 | "unique_id": "__VIN___climate_on", 757 | "dev": { 758 | "name": "PHEV __VIN__", 759 | "identifiers": ["phev-__VIN__"], 760 | "manufacturer": "Mitsubishi", 761 | "model": "Outlander PHEV" 762 | }, 763 | "icon": "mdi:car-seat-heater", 764 | "~": "__TOPIC__"}`, 765 | // Lights. 766 | "%s/light/%s_parkinglights/config": `{ 767 | "name": "__NAME__ Park Lights", 768 | "icon": "mdi:car-parking-lights", 769 | "state_topic": "~/lights/parking", 770 | "command_topic": "~/set/parkinglights", 771 | "payload_off": "off", 772 | "payload_on": "on", 773 | "avty_t": "~/available", 774 | "unique_id": "__VIN___parkinglights", 775 | "dev": { 776 | "name": "PHEV __VIN__", 777 | "identifiers": ["phev-__VIN__"], 778 | "manufacturer": "Mitsubishi", 779 | "model": "Outlander PHEV" 780 | }, 781 | "~": "__TOPIC__"}`, 782 | "%s/light/%s_headlights/config": `{ 783 | "name": "__NAME__ Head Lights", 784 | "icon": "mdi:car-light-high", 785 | "state_topic": "~/lights/head", 786 | "command_topic": "~/set/headlights", 787 | "payload_off": "off", 788 | "payload_on": "on", 789 | "avty_t": "~/available", 790 | "unique_id": "__VIN___headlights", 791 | "dev": { 792 | "name": "PHEV __VIN__", 793 | "identifiers": ["phev-__VIN__"], 794 | "manufacturer": "Mitsubishi", 795 | "model": "Outlander PHEV" 796 | }, 797 | "~": "__TOPIC__"}`, 798 | // General topics. 799 | "%s/button/%s_reconnect_wifi/config": `{ 800 | "name": "__NAME__ Restart Wifi connetion", 801 | "icon": "mdi:timer-off", 802 | "command_topic": "~/connection", 803 | "payload_press": "restart", 804 | "avty_t": "~/available", 805 | "unique_id": "__VIN___restart_wifi", 806 | "dev": { 807 | "name": "PHEV __VIN__", 808 | "identifiers": ["phev-__VIN__"], 809 | "manufacturer": "Mitsubishi", 810 | "model": "Outlander PHEV" 811 | }, 812 | "~": "__TOPIC__"}`, 813 | } 814 | mappings := map[string]string{ 815 | "__NAME__": name, 816 | "__VIN__": vin, 817 | "__TOPIC__": topic, 818 | } 819 | for topic, d := range discoveryData { 820 | topic = fmt.Sprintf(topic, m.haDiscoveryPrefix, vin) 821 | for in, out := range mappings { 822 | d = strings.Replace(d, in, out, -1) 823 | } 824 | if token := m.client.Publish(topic, 0, true, d); token.Wait() && token.Error() != nil { 825 | log.Error( token.Error() ) 826 | } 827 | //m.client.Publish(topic, 0, false, "{}") 828 | } 829 | } 830 | 831 | func init() { 832 | clientCmd.AddCommand(mqttCmd) 833 | 834 | // Here you will define your flags and configuration settings. 835 | 836 | // Cobra supports Persistent Flags which will work for this command 837 | // and all subcommands, e.g.: 838 | // mqttCmd.PersistentFlags().String("foo", "", "A help for foo") 839 | 840 | // Cobra supports local flags which will only run when this command 841 | // is called directly, e.g.: 842 | // mqttCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") 843 | mqttCmd.Flags().String("mqtt_server", "tcp://127.0.0.1:1883", "Address of MQTT server") 844 | mqttCmd.Flags().String("mqtt_username", "", "Username to login to MQTT server") 845 | mqttCmd.Flags().String("mqtt_password", "", "Password to login to MQTT server") 846 | mqttCmd.Flags().String("mqtt_topic_prefix", "phev", "Prefix for MQTT topics") 847 | mqttCmd.Flags().Bool("mqtt_disable_register_set_command", false, "Disable vechicle register setting via MQTT") 848 | mqttCmd.Flags().Bool("ha_discovery", true, "Enable Home Assistant MQTT discovery") 849 | mqttCmd.Flags().String("ha_discovery_prefix", "homeassistant", "Prefix for Home Assistant MQTT discovery") 850 | mqttCmd.Flags().Duration("update_interval", 5*time.Minute, "How often to request force updates") 851 | mqttCmd.Flags().Duration("wifi_restart_time", 0, "Attempt to restart Wifi if no connection for this long") 852 | mqttCmd.Flags().Duration("wifi_restart_retry_time", 2*time.Minute, "Interval to attempt Wifi restart") 853 | mqttCmd.Flags().String("wifi_restart_command", defaultWifiRestartCmd, "Command to restart Wifi connection to Phev") 854 | 855 | viper.BindPFlag("mqtt_server", mqttCmd.Flags().Lookup("mqtt_server")) 856 | viper.BindPFlag("mqtt_username", mqttCmd.Flags().Lookup("mqtt_username")) 857 | viper.BindPFlag("mqtt_password", mqttCmd.Flags().Lookup("mqtt_password")) 858 | viper.BindPFlag("mqtt_topic_prefix", mqttCmd.Flags().Lookup("mqtt_topic_prefix")) 859 | viper.BindPFlag("mqtt_disable_register_set_command", mqttCmd.Flags().Lookup("mqtt_disable_register_set_command")) 860 | viper.BindPFlag("ha_discovery", mqttCmd.Flags().Lookup("ha_discovery")) 861 | viper.BindPFlag("ha_discovery_prefix", mqttCmd.Flags().Lookup("ha_discovery_prefix")) 862 | viper.BindPFlag("update_interval", mqttCmd.Flags().Lookup("update_interval")) 863 | viper.BindPFlag("wifi_restart_time", mqttCmd.Flags().Lookup("wifi_restart_time")) 864 | viper.BindPFlag("wifi_restart_retry_time", mqttCmd.Flags().Lookup("wifi_restart_retry_time")) 865 | viper.BindPFlag("wifi_restart_command", mqttCmd.Flags().Lookup("wifi_restart_command")) 866 | } 867 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type 'show c' for details. 659 | 660 | The hypothetical commands 'show w' and 'show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------