# WebSocket
Using WebSocket you can subscribe to events from your mower(s). Instead of polling the Automower® Connect API for changes you get notifications when the status or positions change. 

To use WebSockets you need to authenticate and have a valid token. You don't need your API key to use WebSocket.

__NOTE:__ 
- Currently WebSocket does not support sending control commands _to_ the mower. For this you need to use the REST API.
- WebSocket has a max time limit of 2 hours. To keep the connection a live you have to reconnect before 2 hours have passed. We are working on a solution for this.
- There is a timeout of 10 minutes in the mower to preserve data traffic and save battery that makes the events to be sent every 15 minutes.
- There is a maximum of 10 simultaneous connections per user
- A user can create a maximum of 1 connection per second

## Authentication
For authentication see __README__

If you get 403 when using Websocket even if the REST API call works. Try to renew the application, that should do the trick. If you still get 403 check that you get the correct scope when creating the access token (`iam:read amc:api`). If you don't have the correct scope you need to connect your application to the Automower API to get the correct scope.

## Ping
To stay connected you can send a ping to tell Websocket to keep the connection alive. The max time is still 2 hours. It's limit in the cloud framework. If you send a ping you won't get a pong. A ping will still work as expected. If you want a response, you can instead send an empty message to get an empty message in response.

## Wscat
Following example uses wscat, install [wscat](https://github.com/websockets/wscat) by installing wscat using npm.

```bash
# install wscat
npm install -g wscat 
```
Run wscat to get events

```bash
wscat -c wss://ws.openapi.husqvarna.dev/v1 -H "Authorization: Bearer &lt;access_token&gt;"
```

## JavaScript
A simple example in Node.js to connect to WebSockets and get events. Requires [ws: a Node.js WebSocket library](https://github.com/websockets/ws)

```bash
# install ws
npm install ws
```

```javascript
const WebSocket = require('ws');

const accessToken = '&lt;access_token&gt;';
const url = 'wss://ws.openapi.husqvarna.dev/v1';

const wss = new WebSocket(url, '', {
    headers: {
        Authorization: `Bearer ${accessToken}`
    }
});

wss.on('message', function incoming(data) {
    console.log(data);
});

// Ping server - to keep alive
setInterval(function(){ wss.send('ping'); }, 60000);
```

## Python
A simple example to connect to Websocket using Python. Requires packages websocket-client. The package can be installed by pip or any other package manager.

```bash
# install websocket
pip install websocket-client
```

```python
# More information about websocket-client can be found here: https://pypi.org/project/websocket-client/
import websocket
import _thread
import time

token = "<your access token>"
auth = "Authorization: Bearer " + token

def on_message(ws, message):
    print ('message received ..')
    print (message)

def on_error(ws, error):
    print ('error happened .. ')
    print (error)

def on_close(ws, close_status_code, close_msg):
    print ("### closed with status: ", close_status_code, " and message: ", close_msg, " ###")
    # max session time is 120 minutes, start a new connection
    if close_status_code is not None: # avoid start if Ctrl+c
      startConnection()

def on_open(ws):
    print ('Opening Websocket connection to the server ... ')

def startConnection():
    print ('Start Websocket connection to the server ... ')
    ws = websocket.WebSocketApp("wss://ws.openapi.husqvarna.dev/v1",
                              on_open=on_open,
                              on_message=on_message,
                              on_error=on_error,
                              on_close=on_close,
                              header = [auth])
    ws.run_forever(ping_interval=60, ping_timeout=10)

if __name__ == "__main__":
    websocket.enableTrace(True)
    startConnection()
```

## Events V2
All V2 events are documented on the page WEBSOCKET API.

## Summary
By using WebSocket you will get fast feedback when a status, position or setting is updated.

## Support
For api related queries, to get access to technical support send an email to <a href="mailto:openapi.servicedesk@husqvarnagroup.com">openapi.servicedesk@husqvarnagroup.com</a>.
