Create Syncback Sensors

Home Assistant General


The following script can be added to Syncback Pro to set a sensor for each Profile when the backup completes each will be prefixed with sensor.syncback_, when attached to a profile the script will create or update a sensor for the backup selected.

The friendly name will be set to the Profile name and the Result set to the result of the run.

To use create Long access Token in your Home Assistant Profile and replace TOKEN in the script with your token.

Note: The datetime field in the attributes is to ensure the Last Updated time on the entity is updated.

The Json string sent to Home assistant looks like this

{"entity_id": "sensor.syncback_home_assistant", "state": "ok", "attributes": {"result": "Success", "friendly_name": "Home Assistant", "area": "syncback", "count": "9", "datetime": "Wed 24 03 2021 09:08:08"}

Syncback Pro Basic Script

'
' Send Result of run to Home Assistant
' after a profile runs (if the run is simulated then it does not).
'
' SBLang=Basic
'
'

' The connection details for Home Assistant to send a message
const HAToken = "TOKEN"
const HAEntity = "sensor.syncback"

'
' This is a runtime script
'
Function Description(ByRef ScriptType)
  Description = "Send Home Assistant Update"
  ScriptType = SCRIPTTYPE_RUN
End Function

'
' This routine is called after the profile has finished.
'
Sub RunProfileResult(ProfileResult, ErrMsg)
  Dim sUrl
  Dim sText
  Dim sJson
  Dim oXMLHTTP, sResult
  Dim SendHA
  Dim sAuth
  Dim sAttribute
  Dim sStatus
  Dim sDesc

  ' Check to see if the profile has run
  If SBRunning.Simulated then
    Exit Sub
  End If

  ' Get profile result
  SendHA = True
  Select Case ProfileResult
  Case 0
    ' 0 = No result (ELR_None)
    SendHA = False
  Case 1
    ' 1 = Unknown profile (ELR_UnknownProfile)
    SendHA = False
  Case 2
    ' 2 = Profile is already running (ELR_AlreadyRunning)
    SendHA = False
  Case 3
    ' 3 = Profile has been imported and not run yet (ELR_Imported)
    SendHA = False
  Case 4
    ' 4 = Profile is running (ELR_Running)
    SendHA = False
  End Select

  ' Are we going to update HA?
  If SendHA = False then
    Exit Sub
  End If

  sStatus = "error"
  ' Build the Home Assistant message
  sDesc = "Profile " & SBRunning.Name & " finished on " & FormatDateTime(Now(), 0) & ":"
  sText = ""
  Select Case ProfileResult
  Case 5
    sText = sText & "Internal error"
  Case 9
    sText = sText & "Restore aborted"
  Case 10
    sText = sText & "Restore failed"
  Case 11
    sText = sText & "Restore success"
  Case 12
    sText = sText & "Aborted"
  Case 13
    sText = sText & "Failed"
  Case 14
    sText = sText & "Success"
    sStatus = "ok"
  Case 15
    sText = sText & "Network failure"
  Case 16
    sText = sText & "Scan failure"
  Case 17
    sText = sText & "Compare failure"
  Case 18
    sText = sText & "Run Before stopped profile"
  Case 19
    sText = sText & "Profile disabled"
  Case 20
    sText = sText & "SMART drive errors"
  Case 21
    sText = sText & "Could not email log"
  Case 22
    sText = sText & "Volume Shadow Copy snapshot failed"
  End Select


  sAttribute = Lcase(replace(SBRunning.Name," ","_"))
  sAttribute = replace(sAttribute,".","_")
  sAttribute = replace(sAttribute,"-","_")
  dim sCount
  dim sDT

  sDT = DateToStr(Date) & " " & TimeToStr(Time)
  sCount = SBRunning.GetRuntimeValueStr(1)
  sJson =  "{'state': '"  & sStatus & "', 'attributes': {'result': '" & sText & "'"
  sJson = sJson &  ",'friendly_name': '"&  SBRunning.Name & "'"
  sJson = sJson &  ",'area': 'syncback'"
  sJson = sJson &  ",'count': '" & sCount & "'"
  sJson = sJson &  ",'datetime': '" & sDT & "'"
  sJson = sJson & "}}"
  sJson = replace(sJson,"'","""")
  SBRunning.DebugOut("HAResult", sJson, 1)

  ' Send HA message
  sUrl = "http://homeassistant.local:8123/api/states/" & HAEntity & "_" & sAttribute
  sAuth = "Bearer " & HAToken
  set oXMLHTTP = CreateObject("MSXML2.ServerXMLHTTP.6.0")
  oXMLHTTP.open("POST", sUrl, false)
  oXMLHTTP.SetRequestHeader("Content-Type", "application/json")
  oXMLHTTP.SetRequestHeader("Authorization", sAuth)

  oXMLHTTP.send(sJson)
  sResult = oXMLHTTP.responseText
  SBRunning.DebugOut("HAResult", sResult, 1)
  Set oXMLHTTP = nothing
End Sub

To display the backup information the follow was used,  this includes the custom:flex-table-card from Custom cards for Home Assistant installed via HACS.

      - type: vertical-stack
        cards:
          - type: markdown
            content: '# Backups'
          - type: horizontal-stack
            cards:
              - type: markdown
                content: >-
                  **Last Snapshot**

                  {{ as_timestamp(state_attr('sensor.snapshot_backup',
                  'last_snapshot')) | timestamp_custom('%A at %H:%M 
                  (%d-%m-%y)') }}
              - type: markdown
                content: >-
                  **Syncback**

                  {%set errors =  states.sensor|
                  selectattr('state','eq','error') |
                  selectattr('attributes.area','eq','syncback')           
                  |map(attribute='entity_id')|list |count  %}{%set good = 
                  states.sensor| selectattr('state','eq','ok') |
                  selectattr('attributes.area','eq','syncback')           
                  |map(attribute='entity_id')|list |count  %}{% if errors > 0
                  %}<font color="red">{{errors}} Backup{% if errors > 1 %}s{%
                  endif %} error</font>

                  {%endif%}{{good}} Good backup{% if not(good == 1) %}s{% endif
                  %} 
          - type: 'custom:flex-table-card'
            clickable: true
            sort: last_updated
            entities:
              include: sensor.sync*
            columns:
              - name: Profile
                data: friendly_name
              - name: Result
                data: result
                modify: >-
                    const color = (x == "Success") ? 'green' : 'red';
                    '<span style="color:' + color + ';">' + x + '</span>'

              - name: Age (h)
                data: last_updated
                modify: Math.round((Date.now() - Date.parse(x)) / 36000.) / 100.