E' possibile trasmettere segnali a Databoom utilizzando piattaforme per la supervisione ed il controllo industriali facenti uso della tecnologia software HMI/Scada, quale Movicon.
L'invio dei dati è implementato attraverso la stesura di uno script Visual Basic.
Riferimenti
Prima di procedere con la scrittura del codice, è necessario aggiungere al proprio script alcuni riferimenti (Menù Edit -> References...):
- Microsoft WinHTTP Services (5.1)
- Microsoft Scripting Runtime (1.0)
Script VB
Lo script seguente mostra un possibile approccio all'inoltro delle proprie variabili in Movicon a Databoom.
Sub Main()
Dim http As WinHttp.WinHttpRequest
Dim UrlToPostTo As String
Dim UrlClockGet As String
Dim sDate As String
Dim lngTimeout As Long
Dim JSONString As String
Dim canConn As Boolean
Dim oAuthToken As String
Dim FSO As FileSystemObject
Dim TS As TextStream
Set FSO = New FileSystemObject
Dim logsDirectory As String
logsDirectory = "LOGS"
Dim logs<SIGNAL 1>, logs<SIGNAL 2> As String
logs<SIGNAL 1> = "LOGS\<SIGNAL 1>.txt"
logs<SIGNAL 2> = "LOGS\<SIGNAL 2>.txt"
oAuthToken = "Bearer <OAUTH TOKEN DATABOOM>"
UrlClockGet = "https://api.databoom.com/v1/auth/gmtclock/plain"
UrlToPostTo = "https://api.databoom.com/v1/signals/push"
If Not FSO.FolderExists(logsDirectory) Then
FSO.CreateFolder(logsDirectory)
End If
Set TS = FSO.OpenTextFile(logs<SIGNAL 1>, ForAppending, True)
TS.Close
Set TS = FSO.OpenTextFile(logs<SIGNAL 2>, ForAppending, True)
TS.Close
lngTimeout = 30000
canConn = True
Set http = New WinHttp.WinHttpRequest
http.SetTimeouts lngTimeout, lngTimeout, lngTimeout, lngTimeout
http.Open "GET", UrlClockGet, False
http.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
On Error GoTo HandleDateRequest
http.Send
sDate = http.ResponseText
http.Open "POST", UrlToPostTo, False
http.SetRequestHeader "Content-Type", "application/json"
http.SetRequestHeader "Authorization", oAuthToken
Dim <SIGNAL 1>, <SIGNAL 2>
If GetVariableValue("<SIGNAL 1>") Then
<SIGNAL 1> = GetVariableValue("<SIGNAL 1>")
Else
<SIGNAL 1> = -999999
End If
If GetVariableValue("<SIGNAL 2>") Then
<SIGNAL 1> = GetVariableValue("<SIGNAL 2>")
Else
<SIGNAL 2> = -999999
End If
JSONString = "{""device"":""<TOKEN DEVICE>"",""date"":" + sDate + ", ""signals"":["
JSONString = JSONString + "{""name"":""<TOKEN SIGNAL 1>"",""value"":"+ Replace(<SIGNAL 1>,",",".") +"},"
JSONString = JSONString + "{""name"":""<TOKEN SIGNAL 2>"",""value"":"+ Replace(<SIGNAL 2>,",",".") +"}"
JSONString = JSONString + "]}"
On Error GoTo HandleFailedPost
http.Send "" + JSONString
If canConn = True Then
Dim bulk As String
Dim emptyBulk As Boolean
emptyBulk = True
bulk = "{""device"":""<TOKEN DEVICE>"",""date"":" + sDate + ", ""signals"":{"
bulk = bulk + " ""<TOKEN SIGNAL 1>"" : {""description"":""<SIGNAL 1>"", ""history"":["
addHistory logs<SIGNAL 1>, bulk
If StrComp(Right(bulk, 1),",") = 0 Then
bulk = Left(bulk, Len(bulk) - 1) + "]},"
emptyBulk = False
Else
bulk = bulk + "]},"
End If
bulk = bulk + " ""<TOKEN SIGNAL 2>"" : {""description"":""<SIGNAL 2>"", ""history"":["
addHistory logs<SIGNAL 2>, bulk
If StrComp(Right(bulk, 1),",") = 0 Then
bulk = Left(bulk, Len(bulk) - 1) + "]}}}"
emptyBulk = False
Else
bulk = bulk + "]}}}"
End If
If emptyBulk = False Then
http.Open "POST", UrlToPostTo, False
http.SetRequestHeader "Content-Type", "application/json"
http.SetRequestHeader "Authorization", oAuthToken
On Error GoTo HandleFailedConn
http.Send "" + bulk
If canConn = True Then
cleanHistory logs<SIGNAL 1>
cleanHistory logs<SIGNAL 2>
End If
End If
End If
Set http = Nothing
Set TS = Nothing
Set FSO = Nothing
Exit Sub
HandleFailedConn:
canConn = False
Resume Next
HandleDateRequest:
canConn = False
sDate = Format(Now, "YYYY-MM-DDTHH:NN:SS")
Resume Next
HandleFailedPost:
canConn = False
Set TS = FSO.OpenTextFile(logs<SIGNAL 1>, ForAppending, True)
TS.Write "{""date"":"""+ sDate +""",""value"":"+ Replace(<SIGNAL 1>,",",".") +"}" + vbCrLf
TS.Close
Set TS = FSO.OpenTextFile(logs<SIGNAL 2>, ForAppending, True)
TS.Write "{""date"":"""+ sDate +""",""value"":"+ Replace(<SIGNAL 2>,",",".") +"}" + vbCrLf
TS.Close
JSONString = ""
Resume Next
End Sub
Sub addHistory(ByVal logFile, ByRef bulk)
Dim FSO As FileSystemObject
Dim TS As TextStream
Set FSO = New FileSystemObject
Set TS = FSO.OpenTextFile(logFile, ForReading)
Do Until TS.AtEndOfStream
bulk = bulk + TS.ReadLine + ","
Loop
TS.Close
End Sub
Sub cleanHistory(ByVal logFile)
Dim FSO As FileSystemObject
Dim TS As TextStream
Set FSO = New FileSystemObject
Set TS = FSO.OpenTextFile(logFile, ForWriting, True)
TS.Write ""
TS.Close
End Sub
Nello script prestare particolare attenzione a:
- logsDirectory è il percorso della cartella dove si vogliono salvare i log, se non è presente viene creata.
- Se le variabili non sono leggibili, viene assegnato un valore distintivo -999999 (può essere modificato a piacere).
Replace(<SIGNAL 1>,",",".")
permette di inoltrare valori con decimali che utilizzano il separatore , .- <
OAUTH TOKEN DATABOOM
> è un token generato in Databoom, nella sezione Impostazioni -> Credenziali. - <SIGNAL 1> e <SIGNAL 2> sono le variabili di Movicon che si vogliono inoltrare. Si utilizzano gli stessi valori per nominare anche i file di log. Nell'esempio sono rappresentate due variabili, è possibile aggiungerne altre seguendo la stessa procedura.
- <TOKEN DEVICE> è il token del dispositivo su Databoom.
- <TOKEN SIGNAL 1> e <TOKEN SIGNAL 2> sono i token dei segnali in Databoom. Se i segnali sono già stati creati, <TOKEN SIGNAL #> dev'essere sostituito con il token corrispondente. Al contrario, il token inserito nello script verrà utilizzato per la creazione del segnale sulla piattaforma.
Lo script inoltra i dati ad intervalli regolari, ogni volta che viene richiamato dallo schedulatore. Nel caso non fosse possibile la comunicazione, i dati registrati vengono memorizzati localmente in file di log e verranno inoltrati non appena la connessione sarà ripristinata in un'unica richiesta (bulk).
N.B. sDate
viene restituita dall'API come stringa, già virgolettata. Assicurarsi che nella formazione della stringa JSON i doppi apici siano utilizzati correttamente. La struttura corretta da inoltrare è del tipo {"date":"2018-03-26T09:35:46","value":4}, non {"date":""2018-03-26T09:35:46"","value":8}. In particolare si distinguano i casi fra le assegnazioni di variabili e la scrittura del file:
JSONString = "{""device"":"""",""date"":" + sDate + ", ""signals"":["
bulk = "{""device"":""<TOKEN DEVICE>"",""date"":" + sDate + ", ""signals"":{"
TS.Write "{""date"":"""+ sDate +""",""value"":"+ <SIGNAL 1> +"}" + vbCrLf
TS.Write "{""date"":"""+ sDate +""",""value"":"+ <SIGNAL 2> +"}" + vbCrLf
Schedulatore
Per permettere l'esecuzione permanente dello script è necessario creare un nuovo schedulatore. Dalla finestra "Esploratore Progetto" posizionarsi nella sezione "Lista Oggetti Schedulatori" del proprio progetto e selezionare l'opzione "Nuovo Schedulatore" al click destro del mouse.
Nella finestra delle proprietà del nuovo schedulatore andrà infine selezionato "ogni minuto" in Tipo e il proprio script in Comandi On.
Configurazione completata!
Una volta completata la procedura, Databoom inizierà a registrare i dati inoltrati da Movicon. Per poter consultare i dati e avere una rappresentazione corretta, seguire le indicazioni in Modifica/validazione di un segnale.
0 Commenti