Notes13C写文件,hal层,python读文件
Posted 码农编程录
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Notes13C写文件,hal层,python读文件相关的知识,希望对你有一定的参考价值。
1.C写文件
source /usr/local/bin/openbmc-utils.sh 后就可以用 get_psu_power_sta 1,psu1为0有电。正常情况下只能通过/dev/mtdn来使用(读写访问具体数据),而不能通过/proc/mtd ,/proc/mtd 主要是方便快速了解状态。
scp -r meta-huaqin/meta-hollywood/recipes-plats/hal/files/hal_temp.py root@10.75.92.118:/usr/lib/python3.7/site-packages/hal
curl http://240.1.1.1:8080/api/fan/info/fan1 | python -m json.tool
tail -f /var/log/messages
document.querySelector('video').playbackRate = 3
FILE *fptime;
fptime=fopen("/tmp/time","w");
time_t time_log = time(NULL);
struct tm* tm_log = localtime(&time_log);
fprintf(fptime, "start__ flag[%d] LINE[%d] %04d-%02d-%02d %02d:%02d:%02d\\r\\n",sensor_flag, __LINE__, tm_log->tm_year + 1900, tm_log->tm_mon + 1, tm_log->tm_mday, tm_log->tm_hour, tm_log->tm_min, tm_log->tm_sec);
fflush(fptime);
fclose(fptime);
if(rc<0)
{
FILE *fpLedLog=fopen("/tmp/error","a");
fprintf(fpLedLog,"error__%u__\\r\\n",__LINE__);
fclose(fpLedLog);
goto err;
}
FILE *fpLedColor=fopen(led_color,"w");
fseek(fpLedColor,0,SEEK_SET);
fprintf(fpLedColor,"%s",sensor_flag?LED_GREEN_CODE:LED_YELLOW_CODE);
fflush(fpLedColor);
fclose(fpLedColor);
int main(int argc, char **argv)
{
if(2 == argc)
{
FILE *fpLedCtrl=fopen("/sys/bus/i2c/devices/0-000d/sys_led_ctrl","w");
FILE *fpLedColor=fopen("/sys/bus/i2c/devices/0-000d/sys_led_color","w");
FILE *fpLedLog=fopen("/var/log/sensorMon.log","w");
fprintf(fpLedCtrl,"0x1");
fprintf(fpLedColor,"%s",argv[1]);
fprintf(fpLedLog,"%s\\r\\n",argv[1]);
fclose(fpLedCtrl);
fclose(fpLedLog);
fclose(fpLedColor);
}
}
int mysprintf(char *outBuffer, char *format, ...)
{
va_list aptr;
int ret;
va_start(aptr, format);
ret = vsprintf(outBuffer, format, aptr);
va_end(aptr);
return(ret);
}
2.hal_temp.py
HAL_TEMP_SENSOR = "TEMPERATURE_SENSORS"
HAL_TEMP_CPU = "Cpu"
HAL_TEMP_INLET = "Inlet"
HAL_TEMP_SWITCH = "Switch"
from hal.hal_common import *
import ctypes
"""
class for HAL temperature APIs.
@param temp_dict Dictionary of temperature, in Celcius degress and floating
point number.
Example:
{
"Value": 30.0, #-99999 for fail
"Min": -10.0,
"Max": 50.0
}
"""
class HalTemperature(object):
def __init__(self):
self.temperature_sensors=load_config()[HAL_TEMP_SENSOR]
self.check_temperature_sensors_dict()
def check_temperature_sensors_dict(self):
if (( HAL_TEMP_CPU not in self.temperature_sensors.keys())
or ( HAL_TEMP_INLET not in self.temperature_sensors.keys())
or ( HAL_TEMP_SWITCH not in self.temperature_sensors.keys())):
if( HAL_TEMP_CPU not in self.temperature_sensors.keys()):
syslog.syslog(syslog.LOG_ERR, 'dict key {} is absent!'.format(HAL_TEMP_CPU))
if( HAL_TEMP_INLET not in self.temperature_sensors.keys()):
syslog.syslog(syslog.LOG_ERR, 'dict key {} is absent!'.format(HAL_TEMP_INLET))
if( HAL_TEMP_SWITCH not in self.temperature_sensors.keys()):
syslog.syslog(syslog.LOG_ERR, 'dict key {} is absent!'.format(HAL_TEMP_SWITCH))
exit(1)
def get_cpu_temp(self):
"""
Get CPU temperature.
@return temp_dict for tempperature or None for failure
"""
temp_dict = {}
result = ctypes.c_float()
mylib = ctypes.CDLL('/usr/lib/libpal.so.0.2')
ret = mylib.read_cpu_temp(ctypes.pointer(result))
if ret == -1:
syslog.syslog(syslog.LOG_ERR, 'read {} temp error'.format(HAL_TEMP_CPU))
return None
temp_dict['Value'] = result.value
temp_dict['Min'] = 1
temp_dict['Max'] = 1
return temp_dict
def get_inlet_temp(self):
"""
Get Inlet temperature.
@return temp_dict for tempperature or None for failure
"""
path = self.temperature_sensors['Inlet']['Path']
prefernode = self.temperature_sensors['Inlet']['PreferNode']
file = "temp1_input"
fullpath = '/'.join([path,prefernode,file])
if os.path.exists(fullpath):
value_dict = hal_read_sensor_node(fullpath,fullpath,fullpath,"C")
if value_dict == None:
syslog.syslog(syslog.LOG_ERR, 'read {} node error'.format(fullpath))
return None
value = value_dict.get('Value')
else:
fullpath = seek_file(path,file)
if fullpath == None:
syslog.syslog(syslog.LOG_ERR, 'seek {} in {} error'.format(file,path))
return None
value_dict = hal_read_sensor_node(fullpath,fullpath,fullpath,"C")
if value_dict == None:
syslog.syslog(syslog.LOG_ERR, 'read {} node error'.format(fullpath))
return None
value = value_dict.get('Value')
temp_dict = {}
temp_dict['Value'] = value
temp_dict['Min'] = 1
temp_dict['Max'] = 1
return temp_dict
def get_switch_temp(self):
"""
Get Switch ASIC temperature.
@return temp_dict for tempperature or None for failure
"""
file = "temp1_input"
path=self.temperature_sensors['Switch']
fullpath = '/'.join([path,file])
value_dict = hal_read_sensor_node(fullpath,fullpath,fullpath,"C")
if value_dict == None:
syslog.syslog(syslog.LOG_ERR, 'read {} node error'.format(fullpath))
return None
value = value_dict.get('Value')
temp_dict = {}
temp_dict['Value'] = value
temp_dict['Min'] = 1
temp_dict['Max'] = 1
return temp_dict
def get_all_temp(self):
"""
Get CPU Switch and inlet temperature
@return a dict or None for failure
"""
temp_dict = {}
temp_dict['CPU'] = self.get_cpu_temp()
temp_dict['Switch'] = self.get_switch_temp()
temp_dict['inlet'] = self.get_inlet_temp()
return temp_dict
3.hal_common.py
import os
import sys
import re
import syslog
import json
SYSCPLD_SYSFS_DIR='/sys/bus/i2c/devices/i2c-0/0-000d'
HAL_SENSOR_CONFIG_NAME = "sensors_config.json"
HAL_PLATFOMR_DIR = "/etc/platform"
def hal_run_bmc_cmd(c, source=False):
if source:
cmd = 'source /usr/local/bin/openbmc-utils.sh;'
cmd += c
else:
cmd = c
p = os.popen(cmd)
recv = p.read()
p.close()
return recv
def hal_fru_parse(info):
result = []
for adata in info.split('\\n\\n'):
sresult = {}
for edata in adata.split('\\n'):
tdata = edata.split(':')
if len(edata) == 0:
continue
sresult[tdata[0].strip()] = tdata[1].strip()
if sresult != {}:
result.append(sresult)
return result
def get_board_type():
pass
def load_config(config_file=None):
"""
Load sensors configuration
Configuration file is writen in JSON format. Mandatory keys:
reference to sensor_config.json
@return 0 for success, -1 for failure
"""
if not config_file:
plat_name = "kestrel"
config_file = '/'.join([HAL_PLATFOMR_DIR,plat_name,HAL_SENSOR_CONFIG_NAME])
if not os.path.isfile(config_file):
return None
with open(config_file) as fh:
return json.load(fh)
def get_system_airflow_():
"""
Get system air flow.
@return "F2B"/"B2F" on success, "N/A" for failure
"""
frufile='/tmp/sys-fru'
if os.path.exists(frufile) and os.path.getsize(frufile):
with open(frufile,'r') as f:
recv=f.read()
else:
recv = hal_run_bmc_cmd('/usr/local/bin/fru-util sys', False)
if not recv:
for i in range(0,5,1):
recv = hal_run_bmc_cmd('/usr/local/bin/fru-util sys', False)
if recv:
break
info = hal_fru_parse(recv)
info = info[0]
PN=''
if 'Product Part Number' in info.keys() and info['Product Part Number'].strip():
PN = info['Product Part Number'].strip()
else:
if 'Product Name' in info.keys() and info['Product Name'].strip():
PN = info['Product Name'].strip()
for name in SYS_F2B_AirFlow_FIELD:
if PN.find(name) != -1:
return 'F2B'
for name in SYS_B2F_AirFlow_FIELD:
if PN.find(name) != -1:
return 'B2F'
return 'N/A'
def get_platform_name_():
"""
Get platform name
@return platform name string, e.g.
"""
plat=get_board_type()
airfow = get_system_airflow_()
if airfow == 'N/A':
syslog.syslog(syslog.LOG_ERR, 'system airflow is N/A!')
return None
return Platform_name[plat][airfow]
def hal_read_sensor_node(value_node,max_node,min_node,unit):
dict={}
try:
with open(value_node,'r') as f:
value=f.readline()
with open(max_node,'r') as f:
max=f.readline()
with open(min_node,'r') as f:
min=f.readline()
except:
#syslog.syslog(syslog.LOG_ERR,'read {} failed'.format(value_node))
return None
dict['Value']=float(value)/1000
dict['Max']=float(max)/1000
dict['Min']=float(min)/1000
dict['Unit']=unit
if unit == 'C':
dict['Min']=0.0
elif unit == 'RPM':
dict['Value']=int(value)
dict['Max']=int(max)
dict['Min']=int(min)
elif unit == 'W':
dict['Value']=float(value)/1000000
dict['Max']=float(max)/1000000
dict['Min']=float(min)/1000000
return dict
def is_dir_exist(path):
if os.path.exists(path):
return True
else:
return False
def remove_file(path):
if is_dir_exist(path):
os.remove(path)
return True
def is_key_exist(node, key):
if key in node:
return True
else:
syslog.syslog(syslog.LOG_ERR,'The key "{}" does not exist'.format(key))
return False
def seek_file(path, name):
fullpath = None
for root, dirs, files in os.walk(path):
if name in files:
fullpath = '{0}/{1}'.format(root, name)
break
return fullpath
4.python读文件
import os
def getdir():
for root, dirs, files in os.walk("D:\\soft\\Dict\\8.9.6.0\\otherskins\\simisent"):
#for dir in dirs:
print('root {}'.format(root))
print('dirs {}'.format(dirs))
print('files {}'.format(files))
a=getdir()
def show_files(path, all_files):
file_list = os.listdir(path)
for file in file_list:
cur_path = os.path.join(path, file)
if os.path.isdir(cur_path):
show_files(cur_path, all_files)
else:
all_files.append(file)
return all_files
contents = show_files("D:\\soft\\Dict\\8.9.6.0\\otherskins\\simisent", [])
for content in contents: # 循环打印show_files函数返回的文件名列表
print(content)
以上是关于Notes13C写文件,hal层,python读文件的主要内容,如果未能解决你的问题,请参考以下文章
开机出现加载硬件抽象层(HAL)所需的DLL 文件怎么修复???