Flic hub intergration

FYI, setting a webhook instead of an event with the endpoint /api/webhook/<webhook_id> doesn’t require a long lived token

On top of that it’s possible in NR to extract information from the headers, which contain, among other things, the remaining battery of the button.

1 Like

Create an internet request in your Flic app

Set “Post”

under URL: http://ha-local-ip:port/api/webhook/your-webhook-id

in Body (at least you need to specify the click type because it’s nowehere else: single, double or hold): {“click_type”: “single”}

Content Type: application/json

Then in NR, this can be done. Battery life can be found in msg.headers.button-battery-level

1 Like

Hello, thanks for the code you provided. I’m getting the same error as leopold005 when I click a Flic:

Started
TypeError: cannot read property 'statusCode' of undefined
    at [anon] (duktape.c:56634) internal
    at [anon] (root/Flic Hub Module/main.js:17)
    at handleResponse (http.js:62)
    at handlePacket (pipe_communication.js:56)
    at readCallback (pipe_communication.js:93) preventsyield

I’m very new to all of this, but Im happy to do my best to explain anything else.

I’ve assume you’ve changed the URL to be the URL of your home assistant server ?

var url = “xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/api/events/flic”

1 Like

that sounds good, I’ll look at that.

Thanks

1 Like

I’ve switched by Flic Hub Code to using a webhook, so it now looks like this…

// main.js
var buttonManager = require("buttons");
var http = require("http");
var url = "http://192.168.xx.xxx:xxxx/api/webhook/flic-abcd1234fgh12";

buttonManager.on("buttonSingleOrDoubleClickOrHold", function(obj) {
	var button = buttonManager.getButton(obj.bdaddr);
	var clickType = obj.isSingleClick ? "click" : obj.isDoubleClick ? "double_click" : "hold";
	
	http.makeRequest({
		url: url,
		method: "POST",
		headers: {"Content-Type": "application/json"},		
		content: JSON.stringify({"button_name": button.name, "click_type": clickType, "battery_status": button.batteryStatus }),				
	}, function(err, res) {
	});
});

and the automation to accept it…

automation:
  - id: flichub_click_webhook
    alias: Flic button events from Flic Hub - Webhook
    mode: parallel
    
    description: >
      Flic Button commands from flic hub
      Receive as Webhook

    trigger:
      - platform: webhook
        webhook_id: flic-abcd1234fgh12
  
    variables: 
      button_name: "{{ trigger.json.button_name }}"
      click_type: "{{ trigger.json.click_type }}"

    action:    
        # Update Battery Level
      - service: input_number.set_value  
        data:
          entity_id: "input_number.{{ button_name }}_battery"
          value: "{{ trigger.json.battery_status }}"
          
      - do other stuff !
3 Likes

@BruceH5200 thanks for this code, it helped me to integrate with Home Assistant. I made a change to the json that may be useful. To ensure you get a valid entity id I added code to remove spaces and make it lower case and set that with the name:

buttonManager.on("buttonSingleOrDoubleClickOrHold", function(obj) {
	var button = buttonManager.getButton(obj.bdaddr);
	var clickType = obj.isSingleClick ? "click" : obj.isDoubleClick ? "double_click" : "hold";
	var buttonId = button.name.replace(" ", "_").toLowerCase();
	
	http.makeRequest({
		url: url,
		method: "POST",
		headers: {"Content-Type": "application/json"},
		content: JSON.stringify({"button_name": button.name, "button_id": buttonId, "click_type": clickType, "battery_status": button.batteryStatus }),
	}, function(err, res) {
    }
    });
});

For anyone else trying this, the automation examples assumes you have setup an input helper and it has and entity id with the name of the button followed by _battery e.g. flic_button1_battery (hence my need for the id).

2 Likes

Thanks for the info on how to use webhook to trigger a node red flow! Much appreciated!
How do you create the entities for the button batteries?

With the entity node in NR you can create an entity from NR to HA. There are several ways of doing it (setting one webhook id for all buttons or setting a different webhook id for every button or even setting a different webhook id for every click type, it’s up to you). I hope you get the idea with this simple example.

[{"id":"38e00c4e.2f57f4","type":"ha-webhook","z":"ea371c1c.7f63c","name":"webhook","server":"9405c3fe.d0a6c","outputs":1,"webhookId":"your_webhook_id","payloadLocation":"payload","payloadLocationType":"msg","headersLocation":"headers","headersLocationType":"msg","x":980,"y":340,"wires":[["46979cc8.5dd7e4"]]},{"id":"46979cc8.5dd7e4","type":"ha-entity","z":"ea371c1c.7f63c","name":"Your flic button","server":"9405c3fe.d0a6c","version":1,"debugenabled":false,"outputs":1,"entityType":"sensor","config":[{"property":"name","value":"my flic battery"},{"property":"device_class","value":"battery"},{"property":"icon","value":""},{"property":"unit_of_measurement","value":"%"}],"state":"headers.button-battery-level","stateType":"msg","attributes":[],"resend":true,"outputLocation":"","outputLocationType":"none","inputOverride":"allow","x":1160,"y":340,"wires":[[]]},{"id":"9405c3fe.d0a6c","type":"server","name":"Home Assistant","addon":true}]

don’t forget to enable the headers under every webhook node.

1 Like

That’s great, thanks
I’d given my buttons acceptable names like “bedside_bruce” so I didn’t have the issue.
But nice solution to avoid having to do that.

Hey I feel like a total idiot. I can’t figure out the proper YAML code for HA…
I have the hub setup, in the SDK prompt, its sending data successfully. I think my HA can see it just fine, but I can’t figure out the yaml portion of it. Anything I do in the editor comes up with a bunch of errors. Can ANYONE, PLEASE!!.. post their entire HA yaml config code? To integrate a Flic button to control a light as well as its battery level. So basically all I have to do is copy and paste and change my ip and flic id. Thank you in advance!

So you have put the code onto the Flic Hub and it is running when you press a button ?

I have many automations running with the Flicd addon so I made some modifications to the Flic Hub code shared by others in order to keep that automations running with the same Flic Button but now paired to the Flic Hub. The new code also sends some state updates so the buttons are still showed on your dashboards.

const requestManager = require("http");
const buttonManager = require("buttons");

//--------------------------------------------------------------------------------//

const MIN_EVENTS_OFFSET = 600;
const SERVER_HOST = 'http://192.168.XXX.YYY:8123';
const SERVER_AUTH_TOKEN = 'Your Long-Lived Access Token';

//--------------------------------------------------------------------------------//

buttonManager.on("buttonReady", function(obj) {
	var button = buttonManager.getButton(obj.bdaddr);
	sendButtonState(button, 'on');
});

buttonManager.on("buttonDisconnected", function(obj) {
	var button = buttonManager.getButton(obj.bdaddr);
	sendButtonState(button, 'off');
});

buttonManager.on("buttonDeleted", function(obj) {
	var button = buttonManager.getButton(obj.bdaddr);
	sendButtonState(button, 'off');
});

var lasClickTimestamp = 0;
buttonManager.on("buttonSingleOrDoubleClickOrHold", function(obj) {
	const timestamp = Date.now();
	var button = buttonManager.getButton(obj.bdaddr);
	sendButtonState(button, 'on');
	if(timestamp - lasClickTimestamp >= MIN_EVENTS_OFFSET) {
		lasClickTimestamp = timestamp;
		button.clickType = obj.isSingleClick ? "single" : obj.isDoubleClick ? "double" : "hold";
		sendButtonEvent(button);
	} else {
		console.log("Event was ignored");
	}
});

//--------------------------------------------------------------------------------//

function getButtonName(data) {
	return 'flic_' + data.bdaddr.replace(new RegExp(':', 'g'), '');
}

function sendButtonState(button, state) {
	var data = JSON.parse(JSON.stringify(button));
	notifyHomeAssistant({
		'method': "POST",
		'url': SERVER_HOST + "/api/states/binary_sensor." + getButtonName(data),
		'content': JSON.stringify({
			'state': state,
			'attributes': {
				'friendly_name': data.name == null ? getButtonName(data) : data.name
			}
		})
	});
}

function sendButtonEvent(event) {
	var data = JSON.parse(JSON.stringify(event));
	notifyHomeAssistant({
		'method': "POST",
		'url': SERVER_HOST + "/api/events/flic_click",
		'content': JSON.stringify({
			'button_name': getButtonName(data),
			'button_address': data.bdaddr,
			'click_type': data.clickType
		})
	});
}

function notifyHomeAssistant(options) {
	options.headers = {
		'Authorization': 'Bearer ' + SERVER_AUTH_TOKEN,
		'Content-Type': 'application/json'
	};
	requestManager.makeRequest(options, function (error, result) {
		if(error != null) {
			console.log(JSON.stringify(options));
			console.log(error);
		}
	});
}
7 Likes

Thank you. I finally got Flic working with HA thanks to your code.

Thank you blunan.
My flic hub and flic2 buttons are now working reliably (I used to have a lot of stability/connection issues with the flicd addon).
This is an excellent solution that is easy to use for novice users.

Thank you, this works perfectly and is also much faster response compared to using webhooks configured in the flic app.

Thank you Blunan for this!

Slight problem/question. I have one Flic directly connected to my RaspPi using flicd everything works correctly and it also shows a state change when viewing the states tab in Dev tools. I used the Flic SDK following your directions copying all 3 files, long live token, etc. I have another Flic this time connected to the Flic hub. The Flic connected to the hub does show up as a binary object but has a permanent “on” state. When I fire the Flic connected to the hub, Home Assistant recognizes the click type, single, double, hold, and any automation work. I debugged both Flics via Node Red and I see the Flic connected directly to the Pi sends a state change when clicked but the Flic connected to the hub does not, hence the permanent “on” state. Did I miss something in the Flic Hub SDK where it’s not sending the actual state change in Home Assistant? I know it’s not a big deal as the Flic connected to the Flic Hub still work as intended but it’ll be nice to have the state change show up accurately in Home Assistant.

Hi there,
I’m new to HA and what I’d like to achieve is using the above Flic Hub SDK code to have the hub transmit button events to the HA instance.
Setting up the flic hub side is easy but what do I need on the HA side to listen for the events and start different actions for different buttons. But how? Do I need the flic-addon? (My understanding is that it’s only required when you want to pair flic buttons with the Pi directly?
Best
AF360

1 Like

Sorry, I too have the same question. Any guidance would be wonderful.

@JJ6767 Well I figured it out meanwhile, it’s really easy. So assuming you have properly setup the flic 2 Hub LR to send a request on a websocket go to home assistant → configuration → automations and add an empty automation:

As the trigger pick webhook and in the ID-field add what your previously have setup in the flic hub (so your automation is only triggered from your flic button(s).

Next you can filter the automation by defining conditions but that’s optional. Leave it empty if you just want to call an action when the flic button is clicked.

Finally you define the action.
As action type pick call service and as the service pick what floats your boat (the dropdown will show your option’s)

Hope this will get you on the right track, too. :grinning:

Have been spending many hours with the system in the last few days and learned a lot. I‘m loving it!

1 Like