Custom component: Better to listen to event or register a service?

I’m coding a custom component for practice. The idea is to take pictures with raspi camera based on some trigger.

But I’m having difficulties understanding what is the fundamental difference by listening to an event and registering a service and using that. Which one I should use?

I don’t want to use the built in component as it keeps the camera on all the time. And some months back when I was using it the feed crashed after couple days and photos were just black.

Below what I have came up with so far:

from picamera import PiCamera
from time import sleep
import logging

DOMAIN = 'juha_camera'
REQUIREMENTS = ['picamera']

_LOGGER = logging.getLogger(__name__)

def setup(hass, config):
    hass.states.set('juha_camera.picture_count', 'No pictures')

    pictureCount = 0        # Pictures taken since boot
    camera = PiCamera()

    # Take a photo upon receiving event
    def take_photo(event):
        try:
            camera.start_preview()
            sleep(2)
            camera.capture("/home/homeassistant/.homeassistant/photos/image.jpg")
            pictureCount += 1

            hass.states.set('juha_camera.picture_count', pictureCount)
        except:
        	_LOGGER.error("Cannot write file for some reason")
        finally:
            camera.stop_preview()

    # Listen the event bus
    hass.bus.listen('juha_camera_take_photo', take_photo)

    return True

You need to listen for an event if you want to take an action when something happens.

Registering a service creates something that others can call. If you then wanted to take action when something else calls that service, you would still need to listen for an event.

I appreciate that this is a very old thread so I’m really answering for others who might come across it at this point (as I just did while searching for something else)—but in your case, to prevent keeping the camera on, you would probably need to move the PiCamera() call into the take_photo function and also shut it down again at the end (probably by putting camera.close() at the end of the finally block).

Piling on… What is the difference from a component and an integration?