def connect_fhem(self): _logger.debug('Establishing FHEM connection') config = self._config["FHEM"] return fhem.Fhem(config["basePath"], protocol=config["protocol"], port=config["port"], username=config["user"], password=config["password"])
def __init__(self, name, timer, config, logger): self.name = name self.config = config self.logger = logger self.mode = MyFHEMClass.MOTION self.timer = timer self.lightState = False self.initConfig() self.fh = fhem.Fhem(self.ip, protocol="https", port=8083, username=self.user, password=self.password, cafile=self.mycertfile) self.logger.info('Init FHEM API OK')
def is_running(self, fhem_url='localhost', protocol='http', port=8083): """ Check if an fhem server is already running. """ fh = fhem.Fhem(fhem_url, protocol=protocol, port=port) ver = fh.send_cmd('version') if ver is not None: fh.close() return ver return None
def __init__(self, MyVarSysData): self.AddReadings = "" self.Log = MyClassLog() self.TimeOut = 1 logging.basicConfig() self.FHEM = fhem.Fhem(MyVarSysData['IP'], port=MyVarSysData['Port'], protocol=MyVarSysData['Protocol'], username=MyVarSysData['User'], password=MyVarSysData['Pass'])
def shutdown(self, fhem_url='localhost', protocol='http', port=8083): """ Shutdown a running FHEM server """ fh = fhem.Fhem(fhem_url, protocol=protocol, port=port) fh.log.level = logging.CRITICAL try: self.log.warning("Shutting down fhem at {}".format(fhem_url)) fh.send_cmd("shutdown") except: pass self.log.warning("Fhem shutdown complete.")
import sys, fhem, logging, time, datetime fh = fhem.Fhem('IP', port=8083, protocol='https', username="", password="") # change according to your fhem configuration logging.basicConfig(level=logging.DEBUG) botname = "NAME" # set telegram bot name to receive status messages light = "NAME" # set light(s) to turn on path_to_file = "PATH" # ex: /opt/fhem/alarm.txt def send_message(text): if botname != "NAME": fh.send_cmd(f"set {botname} message {text} (fhem_wakeup)") alarm_time_file = open(f'{path_to_file}', 'r') alarm_time = str(alarm_time_file.read()).strip() try: alarm_time = datetime.datetime.strptime(alarm_time, '%d. %b %Y at %H:%M') except ValueError: if alarm_time == "None": send_message("No alarm time given. Input = None") sys.exit() else: send_message("Something went wrong.") sys.exit() def sunrise():
if cache_file.is_file(): auth = Auth("MyProject/1.0", json.loads(cache_file.read_text()), token_updated) else: username = input("Username: "******"Password: "******"MyProject/1.0", None, token_updated) try: auth.fetch_token(username, password) except MissingTokenError: auth.fetch_token(username, password, otp_callback()) myring = Ring(auth) myring.update_data() fh = fhem.Fhem(fhem_ip, fhem_port) def sendFhem(str): logger.debug("sending: " + str) global fh fh.send_cmd(str) def askFhemForReading(dev, reading): logger.debug("ask fhem for reading " + reading + " from device " + dev) return fh.get_dev_reading(dev, reading) def askFhemForAttr(dev, attr, default): logger.debug("ask fhem for attribute " + attr + " from device " + dev +
from telegram.ext.updater import Updater from telegram.inline.inlinekeyboardbutton import InlineKeyboardButton from telegram.inline.inlinekeyboardmarkup import InlineKeyboardMarkup from telegram.parsemode import ParseMode from secrets import DEBUG, FHEM, FHEM_NAMES, GROUPS, HEIZ, HEIZ_LIST, MONGO, RASPBEE, RASPBEE_IDS, SENSORS, TELEGRAM if DEBUG: logging.basicConfig(level=logging.DEBUG, stream=sys.stdout, format='%(levelname)s - %(message)s') else: logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', filename="{}/{}".format(os.path.dirname(os.path.realpath(__file__)), 'log/temperature_channel.log')) logger = logging.getLogger(__name__) fh = fhem.Fhem(FHEM['server'], port=FHEM['port'], protocol=FHEM['protocol'], loglevel=3, cafile=FHEM['cafile'], username=FHEM['username'], password=FHEM['password']) def get_fhem(temp_list): temp_list.update( {FHEM_NAMES[k]: {x: {"Value": y['Value'], "Time": y['Time'].astimezone(pytz.timezone('Europe/Berlin'))} for x, y in v.items()} for k, v in fh.get_readings(['humidity', 'temperature'], name="Temp.*").items()}) def get_heiz(temp_list): try: temp_list.update( {HEIZ_LIST[z['name']]: {"temperature": {"Value": round(z['rawValue'] * 100) / 100, "Time": datetime.now().astimezone(pytz.timezone('Europe/Berlin'))}} for z in requests.get('http://{}:{}/api/v1/live-data/'.format(HEIZ['ip'], HEIZ['port'])).json() if z['name'] in HEIZ_LIST})
'settings_FHEM_port' : FHEM_port, 'settings_json_data_logdir' : json_data_logdir, 'version' : getVER(ser), 'serial' : getSERIAL(ser), 'device' : device } print "{:<30} {:<20}".format('Key','Label') for key, value in config.iteritems(): print "{:<30} {:<20}".format(key, value) if fhem_data_log == True: import fhem fh = fhem.Fhem(FHEM_server) fh.connect() if fh.connected(): fh.send_cmd("define " + device + " dummy") stateFormat = " stateFormat { sprintf('Radiation: %s nsV/h (%s CPM@%s °C)', ReadingsVal('GQ_GMC_320E_plus','rad_nsvh',''), ReadingsVal('GQ_GMC_320E_plus','rad_cpm',''), ReadingsVal('GQ_GMC_320E_plus','temperature_C',''), )}" fh.send_cmd("attr " + device + stateFormat) for key, value in config.items(): fh.send_cmd("setreading " + device + " " + str(key) + " " + str(value)) try: print "\n{:<25} {:<10} {:<10} {:<10} {:<10}".format('datetime','rad_cpm','rad_nsvh','voltage_V','temperature_T') while True:
{'protocol': 'https', 'port': 8084}, {'protocol': 'https', 'port': 8085, 'username': '******', 'password': '******'}, ] first = True print("") print("----------------- Fhem ------------") print("Testing python-fhem Fhem():") for connection in connections: print('Testing connection to {} via {}'.format( config['testhost'], connection)) fh = fhem.Fhem(config['testhost'], **connection) devs = [ {'name': 'clima_sensor1', 'readings': {'temperature': 18.2, 'humidity': 88.2}}, {'name': 'clima_sensor2', 'readings': {'temperature': 19.1, 'humidity': 85.7}} ] if first is True: for dev in devs: create_device(fh, dev['name'], dev['readings']) first = False
def _setup(self, force=False): # when description of home.mycroft.ai > Devices > [this mycroft device] # is filled, use this the name of the room where mycroft is located if self.settings.get('device_location', False): dev = DeviceApi() info = dev.get() if 'description' in info: self.device_location = info['description'] LOG.debug("mycroft device location: {}".format(self.device_location)) if self.settings and (force or self.fhem is None): LOG.debug("_setup") portnumber = self.settings.get('portnum') try: portnumber = int(portnumber) except TypeError: portnumber = 8083 except ValueError: # String might be some rubbish (like '') portnumber = 0 self.fhem = \ python_fhem.Fhem(self.settings.get('host'), port=portnumber, csrf=True, protocol=self.settings.get('protocol', 'http').lower(), use_ssl=self.settings.get('ssl', False), username=self.settings.get('username'), password=self.settings.get('password') ) self.fhem.connect() LOG.debug("connect: {}".format(self.fhem.connected())) if self.fhem.connected(): self.allowed_devices_room = self.settings.get( 'room', 'Homebridge') self.ignore_rooms = self.settings.get('ignore_rooms', '') # Check if natural language control is loaded at fhem-server # and activate fallback accordingly LOG.debug("fallback_device_name %s" % self.settings.get('fallback_device_name')) LOG.debug("enable_fallback %s" % self.settings.get('enable_fallback')) if self.settings.get('enable_fallback') and \ self.settings.get('fallback_device_name', ""): fallback_device = \ self.fhem.get_device(self.settings.get( 'fallback_device_name', "")) if fallback_device: # LOG.debug("fallback device {}".format(fallback_device)) self.fallback_device_name = self.settings.get( 'fallback_device_name', "") self.fallback_device_type = self.fhem.get_internals( "TYPE", name=self.fallback_device_name)[ self.fallback_device_name] LOG.debug("fallback_device_type is %s" % self.fallback_device_type) if self.fallback_device_type in [ "Talk2Fhem", "TEERKO", "Babble" ]: self.enable_fallback = True else: self.enable_fallback = False else: self.enable_fallback = False LOG.debug('fhem-fallback enabled: %s' % self.enable_fallback)
def run(typ, freq, data): """ This function is the implementation of the Plugin. If necessary the configuration hast to be set in the config.ini. @type typ: string (FMS|ZVEI|POC) @param typ: Typ of the dataset @type data: map of data (structure see readme.md in plugin folder) @param data: Contains the parameter for dispatch @type freq: string @keyword freq: frequency of the SDR Stick @requires: If necessary the configuration hast to be set in the config.ini. @return: nothing @exception: nothing, make sure this function will never thrown an exception """ try: if configHandler.checkConfig( "fhemCmd" ): #read and debug the config (let empty if no config used) protocol = globalVars.config.get("fhemCmd", "protocol") logging.debug("protocol: %s", protocol) server = globalVars.config.get("fhemCmd", "server") logging.debug("server: %s", server) port = globalVars.config.get("fhemCmd", "port") logging.debug("port: %s", port) username = globalVars.config.get("fhemCmd", "username") logging.debug("username: %s", username) password = globalVars.config.get("fhemCmd", "password") logging.debug("password: %s", password) ########## User Plugin CODE ########## if typ == "FMS": fhemCommand = globalVars.config.get("fhemCmd", "commandFMS") elif typ == "ZVEI": fhemCommand = globalVars.config.get("fhemCmd", "commandZVEI") elif typ == "POC": fhemCommand = globalVars.config.get("fhemCmd", "commandPOC") else: logging.warning("Invalid Typ: %s", typ) return False fhemCommand = wildcardHandler.replaceWildcards(fhemCommand, data) logging.debug("fhemCommand: %s", fhemCommand) fh = fhem.Fhem(server=server, protocol=protocol, port=port, username=username, password=password) fh.send_cmd(fhemCommand) del fh ########## User Plugin CODE ########## except: logging.error("unknown error") logging.debug("unknown error", exc_info=True)
import sys from devices import UVR16x2, RSM610, VirtualDevice from functions import JalousieSteuerung from config import config network = canopen.Network() network.connect(channel='can0', bustype='socketcan') network.scanner.search(0x3F) time.sleep(1) fh = fhem.Fhem(args.fhem_ip, port=args.fhem_port, protocol='telnet', username=args.fhem_username, password=args.fhem_password) fh.connect() if fh.connected(): print("Connected to FHEM!") else: print("Couldnt connect to FHEM!") exit(0) vd = VirtualDevice( { "type": "VirtualDevice", "name": "FHEM Configurator Script" }, network, 63)
logFormatter = logging.Formatter( "%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s") handler = logging.handlers.RotatingFileHandler('./logs/motion.log', maxBytes=1024 * 1024, backupCount=5) handler.setFormatter(logFormatter) logger = logging.getLogger('Logger') logger.setLevel(logging.INFO) logger.addHandler(handler) logger.info('Test FHEM') logger.info('Load config') config = configparser.ConfigParser() config.read('./motion-sensor.ini') ip = config.get("FHEM", "fhem_ip") user = config.get("FHEM", "fhem_user") password = config.get("FHEM", "fhem_pass") mycertfile = config.get("FHEM", "fhem_cafile") fhemdevice = config.get("FHEM", "fhem_switchDeviceName") fh = fhem.Fhem(ip, protocol="https", port=8083, username=user, password=password, cafile=mycertfile) fh.send_cmd("set " + fhemdevice + " off")
sys.path.append('/opt/fhemExtended/RPiSensors') import max6675 header = """\ __ _ ______ _ _ _ / _| | | ____| | | | | | | | |_| |__ ___ _ __ ___ | |__ __ _| |_ ___ _ __ __| | ___ __| | | _| '_ \ / _ \ '_ ` _ \| __| \ \/ / __/ _ \ '_ \ / _` |/ _ \/ _` | | | | | | | __/ | | | | | |____ > <| || __/ | | | (_| | __/ (_| | |_| |_| |_|\___|_| |_| |_|______/_/\_\\__\___|_| |_|\__,_|\___|\__,_| """ print header fh = fhem.Fhem("fhem") sensor = max6675.Max6675(0, 0) old_temp = -999 def getTempMax6675(measurments, rate, std): i = np.array([]) for j in range(0, measurments): i = np.append(i, [sensor.temperature]) time.sleep(rate) print i print "Std: ", np.std(i) print "Med: ", np.median(i).round(1) if (np.std(i) <= std): temp = np.median(i).round(1)