Support for CAN Bus (Peak, Ixxat, canable etc)

yes, slcan is needed to bring up the interface, but i have found a way now to install can-utils , gonna test it later
but i have now installed candlelight firmware, then there is no can-utils needed, just with 1 command “ip link” i can bring up the interface , the stick is recognized with the “gs_usb” driver in kernel as native

for sland you need to mount the ttyusb device to can0 , thats why slcand is needed

Ok firgured it out why can-utils didn’t install, seems the Hassio docker is running alpine 3.12, and can-utits is part of 3.13… that’s why it succeeded with the ssh add-on (based on 3.13) , and not on base Hassio docker (based on 3.12)…
So if I first download the apk package local, then do an apk add command , then it succeeds… So this approach can be used for guys who need slcand…
But i think I am going to use the alternative candlelight firmware, then there is no extra tool needed to bring up the can0 interface…

Thnx for tip @xtra !

Anyway @Jojo-A , what interface do you use? What do you need todo to bring up interface?

I am going to wait now for next HassOs release untill my PR is merged, i need to wait for a beta / rc release to update my HassOS , cause I don’t know how I can upgrade to an development release of HassOS

Unless someone starts a custom component, maybe we can work together on it, then i am going to setup a nother test instance :slight_smile:

@pergola.fabio
currently I use a USB-to-CAN interface from PEAK. On Linux Mint (Ubuntu) no extra drivers needed and working ootb.
Do bring up the interface, I just followed the link above/below:
https://python-can.readthedocs.io/en/master/interfaces/socketcan.html#pcan

I started creating a custom component and currently I stick to the approach to have a dedicated CAN platform which can be chosen as “platform” when creating a new sensor component - more or less as I described here:

But I am totally stuck because I have zero python programming skills, so I currently don’t understand how to interact with the python-can library.
Because of this I dropped a PM to @OpenJeDi if he is willing to assist me in this. I try to do as much as possible by myself. But with zero knowledge, this is pretty hard…

Next month I will order a canable-adapter (china clone) to have similar testing conditions as you in addition to my PEAK adapter.

Python is not that difficult , but if indeed if @OpenJeDi could give us a a start, i am sure we can complete it :+)

Don’t think you need to buy that canable, it’s the same process as canable to bring up the interface (candlelight) , i also bought mine on Aliexpress

Allthough i forgot maybe to add the peak_pci in the PR, i only added peak_usb , are both needed?
(CONFIG_CAN_PEAK_PCI=m)

https://github.com/home-assistant/operating-system/pull/1228/commits/124ebb881943f05e990494b19ce5d0ef3daf8b82

Buts that’s only for HassOs users anyway, we can add later if someone needs it

About python:
yes, I agree that it is basically not that difficult. But I am coming from the Embedded C world. So the programming style is very different in many ways. So currently there is just the knowledge foundation missing. If the foundation is there, the progress would be much more fluent :man_shrugging: .

About PEAK_PCI:
well, of course it “might be”, that someone uses this kind of adapter. But regarding HassOS, I think it will be not necessary to be added. HassOS is (mainly) targeting SBCs, which usually don’t have a PCI interface. So the scenario of HassOS + PEAK-PCI would be very rare. So if needed, it can be added later. But currently I don’t think that it will be needed…

1 Like

First local addon is up and running, see below, canbus.py , didnt post yet, still testing with it, i am already reading messages, thats working, now testing with some rest api calls…

that host_network, priviliged, kernel_modules, is needed to bring up the hardware in the container
also in run.sh, you see i bring down the can0 interface first, while testing and a lot of restarts of the add-on, it was more stable to bring it first down , when it was already up after a restart of the container

Dockerfile file

ARG BUILD_FROM
FROM $BUILD_FROM

ENV LANG C.UTF-8

RUN apk add --no-cache python3 py3-pip
RUN pip install python-can

COPY run.sh /
COPY canbus.py /

RUN chmod a+x /run.sh

CMD [ "/run.sh" ]

run.sh file


#!/usr/bin/with-contenv bashio
lsmod
ifconfig -a | grep can0
ip link set can0 down
ip link set can0 up
ip link | grep can0
python3 canbus.py

config.json file

{
  "name": "Dobiss CAN",
  "version": "3",
  "slug": "dobiss",
  "description": "Doobiss CAN system",
  "startup": "application",
  "arch": ["aarch64", "amd64", "armhf", "armv7", "i386"],
  "kernel_modules": false,
  "host_network": true,
  "privileged": ["NET_ADMIN"],
  "homeassistant_api": true,
  "hassio_api": true,
  "options": {},
  "schema": {}
}
2 Likes

here is already some dirty code that i can use to make REST api calls , based on a canbus message, in this example , when i see this message : “01 45 01 00” , i toggle a input_boolean.test1 :slight_smile:

@tvds , you can use this already :slight_smile: , or extend the switcher with 3 variables… now my third variable is fixed to “toggle” ,we can make it like “toggle” , “turn_on” , "turn_“off”, and use this 3th one in the url

canbus.py file

import can 
import json
from requests import post

def can_message(argument): 
    switcher = { 
        '01 45 01 00': "input_boolean.test1", 
        '01 45 08 00': "input_boolean.test3", 
        '01 45 09 00': "input_boolean.test2", 
    } 
    return switcher.get(data) 

## REST API auth
headers = {
    'Authorization': 'Bearer xxxxx',
    'content-type': 'application/json',
}

## CAN BUS 
bus = can.interface.Bus(bustype='socketcan', channel='can0', bitrate=125000)

while True:
    message = bus.recv()
    #data = "[{}]".format(message.dlc)
    data = ""
    for i in range(0,message.dlc):
        data += " {:02X}".format(message.data[i])
    data = str(data.strip())
    print ("Canbusdata: " + data)
    #print ("Switcher result: " + str(can_message(data)))
    if can_message(data) is not None:
        api = str(can_message(data)).split(".")
        url = "http://localhost:8123/api/services/" + api[0] + "/toggle"
        data_json = {"entity_id": api[0] + "." + api[1]}
        #print(str(url) + "  ---  " + str(data_json))
        response = post(url, headers=headers, data=json.dumps(data_json))
        print(response.text)

final step is better handling for the bus to bring up/down, want todo it in python itself, i sometime have timeouts when bringing up after many restarts , then the add-on fails to start offcourse

EDIT :
for now changed = >
ip link set can0 up type can bitrate 125000
to
ip link set can0 up
so also removed iproute2 from the APK packages , seems iproute2 is not that stable, iproute2 was not needed to set bitrate, but this is not needed also, since bitrate is configured in python

Nice work @pergola.fabio :+1:t2:
Making progress :blush:!

Sorry guys for not stopping by for some time… :confused: .
I have been busy in my “real life” and could not spend time for other things…

Your progress looks amazing :clap: ! Am must confess that I am a little bit embarrassed that you progress straight forward while I am just stuck.

Could you explain very basically your workflow? For comparison:
I just followed the workflow HERE what brought me to the point where Python programming skills are needed (but missing). So I have a canbus.py for my new platform, a new sensor.py for my new component (based on the canbus platform) and the manifest -> more or less the usual development workflow.
BUT: your progress seems to be much more mature. At least you have much more code :wink: . Are you still following the approach with the REST API or what is the current status?

Greetings

well, :slight_smile:
I just played with it, had some time :slight_smile:

i just created an add-on, actually to test the hardware and the PR i submitted for HassOS, so now testing a dev version… i think we need to create an addon, especially for HassOS users , since the hardware itself can only be loaded with extra tools installed
for SLCAN => we need can-utils
for CAN => we need iproute2
both tools are not part of HassOS, so i added them to my add-on container
SLCAN is for me stabler, easier to bring down/up =>> while can was sometimes giving timeouts

anyway, i just played with it , for my project, i am already pleased if i can turn on/off services based on the canbus messages i receive, thats my first goal, thats why i created this add-on , so i dont need the esphome/mcp2515 anymore

next step is offcourse making an component, and not use restapi offcourse, but i am not a developer at all, i just google for scripts :slight_smile:
if he is able to make a custom for our domotic system at home (dobiss), i thnk you will have a nice working example

so we need @OpenJeDi to help us :slight_smile:

anyway @OpenJeDi , i tested canbus, i was able to turn on lights by sending canbus messages, works verry good!! also there is specific canbus message, if we put that on the bus, it will receive the states of all relays!! its like the poll sensor based on TCP we use now , so thats also verry good
that means, we dont need to use TCP at all anymore

basicly we can use your custom already, the send part should be ease to change, instead of sending to TCP, we need to send to canbus, the messages are about the same

for reading/polling states, not sure , i think you need to change code here, because, its not just 1 string that contains all relays, every canbus message is a state, so not sure how you can do this?

Ah, okay. Thanks for the description! Now I can follow again :sweat_smile: .
You might be right about the additional tools that are needed. Currently I don’t know the why how this is handled in HA. A containerized custom component could be one solution. Or maybe it could be loaded/installed just on demand when the platform “canbus:” is added to the configuration.yaml . But as said, I don’t know if this is a common way for integrations in HA…

About the polling:
as I understood it, this could be handled be the python file of the integration itself. It could call the read-function from the python-can library with a specific timeout (like 0,1 s). Other integrations work quite similar.

About the payload (in case of a sensor component):
I would like to handle that as other integrations also do: we should be able to handle it “directly” (use the decimal representation of a specified amount of bytes) or process it as a json payload so we could extract the desired information just from somewhere inside if the CAN bus data field. With a very flexible message processing, we would be able to create both numerical sensors as well as binary sensors.

All my ideas are open for discussion. Please feel free to kick in, if it is just too much crap :wink: .

yeah, gonna strat building my addon this week for my domotica system the control all lights/switches/covers… with a live polling state
i already work with scripts, based on TCP socket, just need to convert them to canbus

@pergola.fabio how is your progress building the addon?

I’m a programmer and could help with the development of the add-on if you need help with python.

My idea is to use esp3266 with MCP2515 running ESPHome and connect them to Home-Assistant running on a raspberry-pi using a “Canable” USB to CAN-bus adapter.

Appreciated, do you also use a dobiss system?
My addon works, i use the canabla as hardware…
With rest API calls i just update the sensors i wants , so good enough :slight_smile:

I also used the ESP before with the MCP board…

But since HassOs 6, i updated the drivers there , so canable is able to load with HassOs…
It’s a cleaner solution, no esp needed anymore

Right now I’m just looking for a solution to use a bus system for wiring my smart home. So, no, I’m not using dobiss. I came across Can-Bus and think this is a pretty solid solution.
I haven’t bought any hardware yet, still looking into it, thats how I ended up at this thread :slight_smile:

Did you create a dedicated HA- Add on or are you still using the script from your post from february

1 Like

Yeah, still using that… But it’s more based on the dobiss system, ideal would be a custom component, not an addon… The custom component needs to load the SLCAN driver…
Then somekind of service to send an can message and an sensor to receive can bus messages…
More an universal component, that everyone can use…

@engal Hi Christoph and nice to see that this topic is still of interest for some people. So: welcome :slight_smile: !
Basically for you: am personally am a big fan of CAN bus, even for home automation. The advantages are already stated here (at least from my point of view): Support for CAN Bus (Peak, Ixxat, canable etc)
Maybe these points help you on your way to a decision.

@pergola.fabio has already done a great job in creating his addon. But I definitely share his opinion, that a dedicated “component” would be better. This is sadly the point where I can not help because of just no knowledge in HA component creation. Yes, I know the documentation and it is great! It is just a case of my mental limitations :sweat_smile: .

I DON’T think, that the SLCAN driver should be loaded or used at all, because I see any advantage to sacrifice the CAN bus’ versatility just for better (?) readability.
SocketCAN should be sufficient and in the Linux kernel since ages. Additionally there is a python library (python-can) that utilizes SocketCAN.

indeed, while testing i had issues with socketcan, specially on HassOS addon , i need to load the driver there
in HassOS, if you want to load additional drivers in kernel, you need to modify the kernel files, so for me as testing slcan was the easiest route
allthough i prefer indeed socketcan, nothing is needed then, but it should be accessible from the custom component (driver)