cancel
Showing results for 
Search instead for 
Did you mean: 
SOLVED

Looking for example in go-lang for binding the Influx-Db

Looking for example in go-lang for binding the Influx-Db

StreetCruiser
Member

Hello everybody.

Just wondering if someone knows any link (or article) how to bind the Influx DB in go-lang in the ctrlX Core environment?

The article I found is using the NodeRed and Telegraf Apps:

https://developer.community.boschrexroth.com/t5/Store-and-How-to/Getting-started-with-InfluxDB-on-ct...

Required is direct binding of the database in the go-lang and App-Builder-Environment for ctrlX Core.

In www there are some examples how to use the Influx DB with go-lang, but the examples don't work in ctrlX Core environment - I guess because of some restriction (firewall?) in port and so on, as well as some unmatched environment variable in Ubuntu.

Any information is highly appreciated. Thanks.

 

10 REPLIES 10

nickH
Community Moderator
Community Moderator

Hi StreetCruiser, 

I found the InfluxDB Client Api for Go online at docs.influxdata.com: here

Can you tell us a little bit more about, what are you trying to do:

  • Does your InfluxDB Client run also on the ctrlX CORE or does it run outside?
  • Do you use the ctrlX COREvirtual to test it or the real ctrlX CORE?
  • Which version of the InfluxDB App do you use?
  • Do you use the right token, do you use the right url?
  • What do you mean with don't work, can you give a error message or something? 

Best regards, 
Nick

nickH
Community Moderator
Community Moderator

I also just found the general Rest-Api of InfluxDB here. You could also send http requests from your go application. 

Additional hint: Influx recommends to use popular tools like postman to test the api.

 

Hi Nick.

 

Thank you so much for your prompt reply. As for your questions:

  • Does your InfluxDB Client run also on the ctrlX CORE or does it run outside?

    It shall run in the ctrlX CORE or ctrlX Virtual, respectively.

  • Do you use the ctrlX COREvirtual to test it or the real ctrlX CORE?

    I am using both of them - virtual for creating the program, core for smoke testing.

  • Which version of the InfluxDB App do you use?

    InfluxDB v2.4.0

  • Do you use the right token, do you use the right url?

    I followed the instruction in the "Get Started" within the app installed for ctrlX Core for programming with go (see attached screenshot).

  • What do you mean with don't work, can you give a error message or something?

    I try to go run main.go in the Visual Studio Code (main.go copied from "Get Started") - it exits immediately with the code 1 (see screenshot attached as well).

 

I guess the code from "Get Started" must be running outside ctrlX Core - it appears strongly to me like a standard example from the manufacturer of InfluxDB.

Any hints what I can do or modify in the standard code to get it run within ctrlX Core environment?

Your help is greatly appreciated. Thanks.

 

nickH
Community Moderator
Community Moderator

I got some hints for you, because you are trying to connect from a port forwarded App Build Environment to the InfluxDB on a port forwarded ctrlX COREvirtual. Therefore you need to configure some things:

1. You have to forward the port 8086 from your ctrlX COREvirtual to your host system. In the ctrlX WORKS settings:

nickH_0-1684933355690.png

2. From your go code, running in the App Build Environment you can now make a connection to the influxdb using this url: "http://10.0.2.2:8086". With the ip 10.0.2.2 you can get from the port forwarded App Build Environment back to the localhost of your Host-PC. 

 

Because you get the message: "unauthorized" I would also check the Token you are using. 

Best regards, 

Nick 

 

CodeShepherd
Community Moderator
Community Moderator

See also the how to "Communicate between a ctrlX COREvirtual and other applications" for information about general communication.

Hello there.

 

Unfortunately I didn't get the example in "Get Started" running - somehow I must have missed some correct settings.

Well forget to mention I am absolutely a beginner in Linux/Ubuntu world and ctrlX App Builder environment; coming from classical, "old" Windows world.

Inbetween I have created an own token and forwarded the port 8086 and create the standard basic project in Visual Studio Code (see attached screenshot).

When debugging, I get the message "context deadline exceeded (Client.Timeout exceeded while awaiting headers)".

 

I guess I am missing quite a lot of things - does somebody know if there is a SDK-like example out there for binding the Influx DB in the ctrlX Core? A very simple example that is capable to run within App Builder for ctrlX Core?  I assume strongly I am missing the right configuration (port forwarding, token, ... and any other prerequisites...). As aforementioned, I am a beginner in Ubuntu/ctrlX Core and may need quite a help in everything  😄

Is there any step-by-step guide how to do it correctly?

 

nickH
Community Moderator
Community Moderator

Hi, 

I just tested it and got it to run with a little go-programm. 

First I did the port forwarding for the virtual ctrlX CORE, which I mentioned in a post above. Then I installed the InfluxDB App on my ctrlX CORE virtual (V1.20). I created a Organisation and a Bucket in the influxDB. Then I created a api-token and copied it out. 

I used the influxdb-client-go from github in my App Build Environment. See this code. First I write a value to influx, then I do a quirie on this: 

 

package main

import (
	"context"
	"fmt"
	"time"
	influxdb2 "github.com/influxdata/influxdb-client-go/v2"
)

const (
	//please insert your organisation, token and bucket here (do the settings prior in influxdb webinterface)
	myToken  = "xxxxxxxxx..." //create a token in influx and paste it in here
	myOrg    = "Boschrexroth" // your organisation name (setting in influxDB)
	myBucket = "TestBucket" // your bucket name (setting in influxDB)
)

func main() {
	// Create a new client using an InfluxDB server base URL and an authentication token
	InfluxDBclient := influxdb2.NewClient("http://10.0.2.2:8086", myToken)

	// write to disired organisation an bucket
	writeAPI := InfluxDBclient.WriteAPIBlocking(myOrg, myBucket)


	// Create a point in influx
	p := influxdb2.NewPointWithMeasurement("metric").
		//AddTag("unit", "temperature").
		AddField("sampleValue", 40.2).
		SetTime(time.Now())
	writeAPI.WritePoint(context.Background(), p)


	// Get query client
	queryAPI := InfluxDBclient.QueryAPI(myOrg)
	// Get parser flux query result
	result, err := queryAPI.Query(context.Background(), `from(bucket:"TestBucket")|> range(start: -1h) |> filter(fn: (r) => r._measurement == "metric")`)
	if err == nil {
			fmt.Printf("row: %s\n", result.Record().String())
	}

	// Ensures background processes finishes
	InfluxDBclient.Close()
}

 

Many thanks for your example. Appreciate it very much!

I will try it and hopefully get a little success.

Hi nickH.

Thanks to your help, I managed somehow to get the example code given by you in the ctrlX Virtual. After modding the code (token, org and bucket) I can see the value 40.2 in the Data Explorer of influxdb, as well as the _measurement and _field properties (see attachment 2023-05-26_11h28_04.png).

BUT:

The code in the following line produced an error:

fmt.Printf("row: %s\n", result.Record().String())

 

I modded the line in order to see the reason and I could chase that result.Record() seemed to return nil.

Here is my modded line:

 

...

func PrintlnEx(strText string) {
    tm := time.Now()
    fmt.Printf(fmt.Sprintf("%.4d-%.2d-%.2d %.2d:%.2d:%.2d.%.3d: %s\r\n", tm.Year(), tm.Month(), tm.Day(), tm.Hour(), tm.Minute(), tm.Second(), tm.Nanosecond()/1000000, strText))
}

 

...

    // Get parser flux query result
    PrintlnEx("  Querying...")
    result, err := queryAPI.Query(context.Background(), `from(bucket:"bucketHdWin")|> range(start: -1h) |> filter(fn: (r) => r._measurement == "metric")`)
    PrintlnEx("  Querying accomplished.")

    if err == nil {
        if result.Record() != nil {
            PrintlnEx(fmt.Sprintf( "    row: %s", result.Record().String() )  )
        } else {
            PrintlnEx("    ERROR: result.Record() returned nil!")     // <-- The runtime landed here.
        }
    } else {
        PrintlnEx(fmt.Sprintf("    ERROR: %s", err.Error()))
    }

    // Ensures background processes finishes
    PrintlnEx("  Closing DB...")
    InfluxDBclient.Close()
    PrintlnEx("  Closing DB accomplished.")

 

 

 

And I could see in the trace output that the result.Record() obviously returned nil (see attachment 2023-05-26_11h34_01.png).

Any hints what could be wrong?

Thanks in advance.

 

 

 

 

 

 

 

 

 

 

nickH
Community Moderator
Community Moderator

Hi @StreetCruiser

I'm happy that you managed to write to the influxDB. 🙂

I looked at the influxdb go client on GitHub a little bit deeper. I found the solution for your problem in the section queries (link). 

You can use result.Next() to iterate over the query response. 

result, err := queryAPI.Query(context.Background(), `from(bucket: "TestBucket") |> range(start: -1h) |> filter(fn: (r) => r["_measurement"] == "metric") |> filter(fn: (r) => r["_field"] == "sampleValue")`)
if err == nil {
	// next() to iterate over query result lines
	for result.Next() {
		// print out result
		fmt.Printf("row: %s\n", result.Record().String())
	}
	if result.Err() != nil {
		fmt.Printf("Query error: %s\n", result.Err().Error())
	}

 

Note: you may have to modify the query for your need. 

Best regards, 

Nick

Icon--AD-black-48x48Icon--address-consumer-data-black-48x48Icon--appointment-black-48x48Icon--back-left-black-48x48Icon--calendar-black-48x48Icon--center-alignedIcon--Checkbox-checkIcon--clock-black-48x48Icon--close-black-48x48Icon--compare-black-48x48Icon--confirmation-black-48x48Icon--dealer-details-black-48x48Icon--delete-black-48x48Icon--delivery-black-48x48Icon--down-black-48x48Icon--download-black-48x48Ic-OverlayAlertIcon--externallink-black-48x48Icon-Filledforward-right_adjustedIcon--grid-view-black-48x48IC_gd_Check-Circle170821_Icons_Community170823_Bosch_Icons170823_Bosch_Icons170821_Icons_CommunityIC-logout170821_Icons_Community170825_Bosch_Icons170821_Icons_CommunityIC-shopping-cart2170821_Icons_CommunityIC-upIC_UserIcon--imageIcon--info-i-black-48x48Icon--left-alignedIcon--Less-minimize-black-48x48Icon-FilledIcon--List-Check-grennIcon--List-Check-blackIcon--List-Cross-blackIcon--list-view-mobile-black-48x48Icon--list-view-black-48x48Icon--More-Maximize-black-48x48Icon--my-product-black-48x48Icon--newsletter-black-48x48Icon--payment-black-48x48Icon--print-black-48x48Icon--promotion-black-48x48Icon--registration-black-48x48Icon--Reset-black-48x48Icon--right-alignedshare-circle1Icon--share-black-48x48Icon--shopping-bag-black-48x48Icon-shopping-cartIcon--start-play-black-48x48Icon--store-locator-black-48x48Ic-OverlayAlertIcon--summary-black-48x48tumblrIcon-FilledvineIc-OverlayAlertwhishlist