#!/usr/bin/env python3

import json

from datetime import datetime, timedelta, timezone

from pyzabbix import ZabbixMetric, ZabbixSender

class ZabbixReporter:
    epoch = datetime(1970, 1, 1, tzinfo = timezone.utc)
    one_second = timedelta(seconds = 1)

    def __init__(self, settings):
        self.sender = ZabbixSender(settings['server'], settings['port'])
        self.hostname = settings['hostname']
        self.discovery_rule_key_prefix = settings['discovery_rule_key_prefix']
        self.category_tool_macro = settings['category_tool_macro']
        self.category_context_macro = settings['category_context_macro']

    def report_categories(self, categories):
        if (len(categories) <= 0):
            return
        to_dict = lambda x: { self.category_tool_macro: '{:s}'.format(x.tool), self.category_context_macro: '{:s}'.format(x.context) }
        category_dict_list = list(map(to_dict, categories))
        discovery_rule_key = '{:s}{:s}'.format(self.discovery_rule_key_prefix, categories[0].tool).lower()
        discovery_rule_payload = json.dumps({ 'data': category_dict_list })
        packet = [ ZabbixMetric(self.hostname, discovery_rule_key, discovery_rule_payload) ]
        self.sender.send(packet)

    def report_activity(self, activity):
        posix_timestamp = (activity.timestamp - self.epoch) // self.one_second
        category = '{:s}.{:s}'.format(activity.tool, activity.type)
        packet = [
          ZabbixMetric(self.hostname, 'STATUS[{:s}]'.format(category), activity.status, posix_timestamp),
          ZabbixMetric(self.hostname, 'DURATION[{:s}]'.format(category), activity.duration, posix_timestamp),
        ]
        self.sender.send(packet)
@@ -1358,98 +1358,208 @@
     
-category = '%7B:s%7D.%7B:s%7D'.format(activity.tool, activity.type)%0A        
+packet = %5B%0A          self._zabbixMetric('STATUS', activity, posix_timestamp),%0A          self._zabbixMetric('DURATION', activity, posix_timestamp)%0A        %5D%0A        self.sender.send(
 packet
- = %5B
+)%0A
 %0A    
-      Z
+def _z
 abbi
@@ -1574,86 +1574,131 @@
 self
-.hostname, 'STATUS%5B%7B:s%7D%5D'.format(category), activity.status, posix_timestamp),
+, metricKind, activity, posix_timestamp):%0A        key = '%7B0%7D_%7B1%7D%5B%7B0%7D.%7B2%7D%5D'.format(activity.tool, metricKind, activity.type)
 %0A   
@@ -1702,17 +1702,22 @@
         
- 
+return
  ZabbixM
@@ -1741,41 +1741,11 @@
 me, 
-'DURATION%5B%7B:s%7D%5D'.format(category)
+key
 , ac
@@ -1755,16 +1755,14 @@
 ity.
-duration
+status
 , po
@@ -1779,48 +1779,4 @@
 amp)
-,%0A        %5D%0A        self.sender.send(packet)

Add tool as a prefix to zabbix metrics key