示例#1
0
def ack():
    config = get_config()
    taeget_path = 'http://' + config['air_conditioner_api_server']['host'] + ':' + str(config['air_conditioner_api_server']['port'])
    # off request
    try:
        response = requests.get(f'{taeget_path}/ping')
        status_code = response.status_code
        api_state = status_code == 200
    except:
        api_state = False

    publish(
        topic = '/'.join([
            config['project_id'],
            'air_conditioner_api_mqtt_agent',
            'ack'
        ]),
        message = json.dumps({
        "mqttAgent": True,
        "airConditionerApi": api_state
    }),
        qos = 0,
        retain = False,
        keepalive = 60,
    )
示例#2
0
def publish_ack() -> None:
    message = {
        "timestamp": int(datetime.datetime.now().strftime('%s')),
    }
    publish(
        topic=publish_topics['ACK'],
        message=json.dumps(message),
        qos=1,
        retain=False,
    )
示例#3
0
def publish_sensor_config() -> None:
    message = {
        "timestamp": int( datetime.datetime.now().strftime('%s') ),
        "sensors": get_sensor_config_no_calibration(),
    }
    publish(
        topic = publish_topics['SENSOR_CONFIG'],
        message = json.dumps(message),
        qos = 1,
        retain = True,
    )
示例#4
0
def publish_device_state() -> None:
    message = {
        "timestamp": int(datetime.datetime.now().strftime('%s')),
        "devices": get_all_device_state(),
    }
    publish(
        topic=publish_topics['DEVICE_STATE'],
        message=json.dumps(message),
        qos=1,
        retain=True,
    )
示例#5
0
def on_requestby_temperature(type_: str, message: str) -> None:
    if type_ not in ['hot', 'cool']:
        raise ValueError # TODO new Error

    req = json.loads(message)
    temperature = req['temperature']
    airflow_level = req['airflowLevel']

    try:
        response = requests.put(
            url = f'{taeget_path}/on/{type_}',
            json = {
                'temperature': temperature,
                'airflowLevel': airflow_level,
            }
        )
        status_code = response.status_code
        api_state = status_code == 200
    except:
        return # TODO publish error
    
    publish_message = json.dumps({
        'isRunning': True,
        'type': type_,
        'temperature': temperature,
        'dehumidificationLevel': None,
        'airflowLevel': airflow_level,
    })

    print(publish_message)

    publish(
        topic = '/'.join([
            config['project_id'],
            'air_conditioner_api_mqtt_agent',
            'state'
        ]),
        message = publish_message,
        qos = 0,
        retain = True,
        keepalive = 60,
    )
    return
示例#6
0
def off():
    config = get_config()
    taeget_path = 'http://' + config['air_conditioner_api_server'][
        'host'] + ':' + str(config['air_conditioner_api_server']['port'])
    # off request
    response = requests.delete(f'{taeget_path}/off')
    publish(
        topic='/'.join(
            [config['project_id'], 'air_conditioner_api_mqtt_agent', 'state']),
        # TODO get correct state
        message=json.dumps({
            'isRunning': False,
            'type': 'cool',
            'temperature': 26,
            'dehumidificationLevel': None,
            'airflowLevel': '1'
        }),
        qos=0,
        retain=True,
        keepalive=60,
    )
示例#7
0
def on_dehumidify(message: str) -> None:
    req = json.loads(message)
    dehumidification_level = req['dehumidificationLevel']
    airflow_level = req['airflowLevel']

    try:
        response = requests.put(
            url = f'{taeget_path}/on/dehumidify',
            json = {
                'dehumidificationLevel': dehumidification_level,
                'airflowLevel': airflow_level,
            }
        )
        status_code = response.status_code
        api_state = status_code == 200
    except:
        return # TODO publish error

    publish_message = json.dumps({
        'isRunning': True,
        'type': 'dehumidify',
        'temperature': None,
        'dehumidificationLevel': dehumidification_level,
        'airflowLevel': airflow_level,
    })

    print(publish_message)

    publish(
        topic = '/'.join([
            config['project_id'],
            'air_conditioner_api_mqtt_agent',
            'state'
        ]),
        message = publish_message,
        qos = 0,
        retain = True,
        keepalive = 60,
    )
    return
示例#8
0
def publish_sensor_data() -> None:

    sensing_config = get_config_item('SENSING')
    sensor_data_publish_period = sensing_config['SENSOR_DATA_PUBLISH_PERIOD']
    sensing_number = sensing_config['SENSING_NUMBER']
    sensor_config = get_sensor_config()

    total_value = {}
    for sensor in sensor_config:
        # if a sensor exists
        if sensor['sensor']: total_value[sensor['sensor_id']] = 0

    for _ in range(sensing_number):
        for sensor_id in total_value.keys():
            sensor_value = read_mcp(sensor_id)
            total_value[sensor_id] += sensor_value
        time.sleep(sensor_data_publish_period / sensing_number)

    publish_data = {
        "timestamp": int( datetime.datetime.now().strftime('%s') ),
        "sensors": [],
    }

    for sensor in sensor_config:
        # if a sensor does not exists
        if sensor['sensor'] == {}:
            continue

        # Least squares coefficients
        if len(sensor['sensor']['calibration']) > 1:
            a, b = least_squares( sensor['sensor']['calibration'] )
        else:
            # use raw value
            a, b = 1, 0

        publish_data['sensors'].append({
            "sensor_id": sensor['sensor_id'],
            "name": sensor['sensor']['name'],
            "type": sensor['sensor']['type'],
            "value": round( a * total_value[sensor['sensor_id']] / sensing_number + b, 2),
            "raw_value": round(total_value[sensor['sensor_id']] / sensing_number, 1),
        })
    

    publish_topic = publish_topics['SENSOR_DATA'] 
    publish_data_json = json.dumps(publish_data)

    write_current_sensor_values(publish_data_json)

    publish(
        topic = publish_topic,
        message = publish_data_json,
        qos = 0,
        retain = True,
    )

    print_color_log(
        title = LOG_TITLE['SENSOR'],
        title_color = Color.YELLOW,
        text = '{unixtime}: {topic}: {message}'.format(
            unixtime = datetime.datetime.now().strftime('%s'),
            topic = color_text(publish_topic, Color.GREEN),
            message = publish_data_json,
        )
    )