$value) { if ($value === NULL || $value === '') { unset($data[$key]); } } return $data; } // 通过pm2.5获取aqi的值 function get_aqi_and_level_by_pm25($pm25){ if ($pm25 < 35) { // 很好 $aqi = 50 / 35 * $pm25; }elseif ($pm25 >= 35 && $pm25 < 75) { // 好 $aqi = 50 / 40 * ($pm25 - 35) + 50; }elseif ($pm25 >= 75 && $pm25 < 115) { // 一般 $aqi = 50 / 40 * ($pm25 - 75) + 100; }elseif ($pm25 >= 115 && $pm25 < 150) { // 较差 $aqi = 50 / 35 * ($pm25 - 115) + 150; }elseif ($pm25 >= 150 && $pm25 < 250) { // 差 $aqi = 100 / 100 * ($pm25 - 150) + 200; }elseif ($pm25 >= 250 && $pm25 < 350) { // 很差 $aqi = 100 / 100 * ($pm25 - 250) + 300; }elseif ($pm25 >= 350) { // 非常差 $aqi = 100 / 150 * ($pm25 - 350) + 400; } $level = get_aqi_str($aqi); return array('aqi'=>round($aqi),'level'=>$level); } function get_aqi_str($aqi){ if ($aqi < 50) { // 很好 $level = 'Very good'; }elseif ($aqi >= 50 && $aqi < 100) { // 好 $level = 'Good'; }elseif ($aqi >= 100 && $aqi < 150) { // 一般 $level = 'Commonly'; }elseif ($aqi >= 150 && $aqi < 200) { // 较差 $level = 'Poor'; }elseif ($aqi >= 200 && $aqi < 300) { // 差 $level = 'Difference'; }elseif ($aqi >= 300 && $aqi < 400) { // 很差 $level = 'Very bad'; }elseif ($aqi >= 400) { // 非常差 $level = 'Very bad'; } return $level; } // modbus crc 16 校验码计算 function crc16($string) { $crc = 0xFFFF; for ($x = 0; $x < strlen ($string); $x++) { $crc = $crc ^ ord($string[$x]); for ($y = 0; $y < 8; $y++) { if (($crc & 0x0001) == 0x0001) { $crc = (($crc >> 1) ^ 0xA001); } else { $crc = $crc >> 1; } } } $crc = strval(base_convert($crc, 10, 16)); $crc = substr('0000'.$crc, -4); return substr($crc, -2).substr($crc, 0,2); } function crc_result($cmd){ $begin = pack('H*',substr($cmd, 0,2)); for ($i=0; $i < intval(strlen($cmd) / 2) - 1; $i++) { $begin = $begin ^ pack('H*',substr($cmd, $i*2+2,2)); } $begin = unpack('H*', $begin); return substr('00'.$begin[1], -2); } function mqttCmd($sendTopic,$backTopic,$sendData,$timeout = 5,$seq = ''){ require_once './application/libraries/Mqtt.php'; // 订阅信息,接收一个信息后退出 $CI =& get_instance(); $server = $CI->config->item('WIFIMqttServer'); $port = $CI->config->item('WIFIMqttPort'); $username = $CI->config->item('WIFIMqttUsername'); $password = $CI->config->item('WIFIMqttPassword'); $client_id = time().rand(100000,999999); // 设置你的连接客户端id $mqtt = new Mqtt($server, $port, $client_id); if($mqtt->connect(true, NULL, $username, $password)) { //链接不成功再重复执行监听连接 $mqtt->publish($sendTopic, $sendData, 0); // $mqtt->publish('/WEGW/ReadIn/865860046894466', pack('H*','010AA00B'), 2); }else{ return ''; } $topics[$backTopic] = array("qos" => 0,"function" => "procmsg"); // $topics['/WEGW/ReadOut/865860046894466'] = array("qos" => 2, "function" => "procmsg"); // 订阅主题 $mqtt->subscribe($topics, 0); $true = 1; $t = time(); while($true == 1){ $true = $mqtt->proc(); if (!empty($seq) && $true != 1){ $res = unpack('H*', $true['msg']); if (substr($res[1], 0,4) != strtolower($seq) && substr(substr($res[1], 0,4), -2).substr(substr($res[1], 0,4), 0,2) != strtolower($seq)) $true = 1; } if (time() - $t >= $timeout) { return ''; } } $mqtt->close(); return $true; } function get_seq(){ $seq = rand(0,100000000); $seq = base_convert($seq, 10, 16); return substr('0000'.$seq, -4); } function get_check_sum($data){ $sum = 0; for ($i=0; $i < strlen($data)/2; $i++) { $sum += base_convert(substr($data, $i*2,2), 16, 10); } $sum = base_convert($sum, 10, 16); $sum = substr('00'.$sum, -2); return $sum; } // 设置时区 function set_timezone($date,$timezone){ $time = strtotime($date) + $timezone*3600; return date('Y-m-d H:i:s',$time); } //小时数 function secToTime($times){ $result = '00'; if ($times>0) { $hour = floor($times/3600); $minute = floor(($times-3600 * $hour)/60); $second = floor((($times-3600 * $hour) - 60 * $minute) % 60); $result = $hour; } return $result; } // 发送邮件 function send_email($to,$msg,$title = '维修通知'){ // $this->load->library('Smtp'); require_once FCPATH.'application/libraries/Smtp.php'; //******************** 配置信息 ******************************** $CI =& get_instance(); $config = $CI->config->config['email']; $smtpserver = $config['smtp_host'];//SMTP服务器 $smtpserverport = $config['smtp_port'];//SMTP服务器端口 $smtpusermail = $config['user_email'];//SMTP服务器的用户邮箱 $smtpemailto = $to;//发送给谁 $smtpuser = $config['smtp_user'];//SMTP服务器的用户帐号,注:部分邮箱只需@前面的用户名 $smtppass = $config['smtp_pass'];//SMTP服务器的用户密码 $mailtitle = $title;//邮件主题 $mailcontent = $msg;//邮件内容 $mailtype = "HTML";//邮件格式(HTML/TXT),TXT为文本邮件 //************************ 配置信息 **************************** $smtp = new Smtp($smtpserver,$smtpserverport,true,$smtpuser,$smtppass);//这里面的一个true是表示使用身份验证,否则不使用身份验证. $smtp->debug = false;//是否显示发送的调试信息 return $smtp->sendmail($smtpemailto, $smtpusermail, $mailtitle, $mailcontent, $mailtype); } /** * 获取密码安全等级 * @param string $password 密码 * @return int 0:低,1:中,2:高 */ function get_password_level($password){ if(preg_match('/^([0-9]{6,16})$/',$password)){ return 0; } else if (preg_match('/^[0-9 a-z]{6,16}$/',$password)){ return 1; } else if (preg_match('/^[0-9 a-z A-Z !@#$%^&*]{6,16}$/',$password)) { return 2; } return 0; } // 天气信息翻译 function weather_translate_en($code){ $data = array( '100' => 'Sunny/Clear', '101' => 'Cloudy', '102' => 'Few Clouds', '103' => 'Partly Cloudy', '104' => 'Overcast', '200' => 'Windy', '201' => 'Calm', '202' => 'Light Breeze', '203' => 'Moderate/Gentle Breeze', '204' => 'Fresh Breeze', '205' => 'Strong Breeze', '206' => 'High Wind, Near Gale', '207' => 'Gale', '208' => 'Strong Gale', '209' => 'Storm', '210' => 'Violent Storm', '211' => 'Hurricane', '212' => 'Tornado', '213' => 'Tropical Storm', '300' => 'Shower Rain', '301' => 'Heavy Shower Rain', '302' => 'Thundershower', '303' => 'Heavy Thunderstorm', '304' => 'Thundershower with hail', '305' => 'Light Rain', '306' => 'Moderate Rain', '307' => 'Heavy Rain', '308' => 'Extreme Rain', '309' => 'Drizzle Rain', '310' => 'Storm', '311' => 'Heavy Storm', '312' => 'Severe Storm', '313' => 'Freezing Rain', '314' => 'Light to moderate rain', '315' => 'Moderate to heavy rain', '316' => 'Heavy rain to storm', '317' => 'Storm to heavy storm', '318' => 'Heavy to severe storm', '399' => 'Rain', '400' => 'Light Snow', '401' => 'Moderate Snow', '402' => 'Heavy Snow', '403' => 'Snowstorm', '404' => 'Sleet', '405' => 'Rain And Snow', '406' => 'Shower Snow', '407' => 'Snow Flurry', '408' => 'Light to moderate snow', '409' => 'Moderate to heavy snow', '410' => 'Heavy snow to snowstorm', '499' => 'Snow', '500' => 'Mist', '501' => 'Foggy', '502' => 'Haze', '503' => 'Sand', '504' => 'Dust', '507' => 'Duststorm', '508' => 'Sandstorm', '509' => 'Dense fog', '510' => 'Strong fog', '511' => 'Moderate haze', '512' => 'Heavy haze', '513' => 'Severe haze', '514' => 'Heavy fog', '515' => 'Extra heavy fog', '900' => 'Hot', '901' => 'Cold', '999' => 'Unknown', ); return isset($data[$code]) ? $data[$code] : ''; } function weather_translate_cn($code){ $data = array( '100' => '晴', '101' => '多云', '102' => '少云', '103' => '晴间多云', '104' => '阴', '200' => '有风', '201' => '平静', '202' => '微风', '203' => '和风', '204' => '清风', '205' => '强风/劲风', '206' => '疾风', '207' => '大风', '208' => '烈风', '209' => '风暴', '210' => '狂爆风', '211' => '飓风', '212' => '龙卷风', '213' => '热带风暴', '300' => '阵雨', '301' => '强阵雨', '302' => '雷阵雨', '303' => '强雷阵雨', '304' => '雷阵雨伴有冰雹', '305' => '小雨', '306' => '中雨', '307' => '大雨', '308' => '极端降雨', '309' => '毛毛雨/细雨', '310' => '暴雨', '311' => '大暴雨', '312' => '特大暴雨', '313' => '冻雨', '314' => '小到中雨', '315' => '中到大雨', '316' => '大到暴雨', '317' => '暴雨到大暴雨', '318' => '大暴雨到特大暴雨', '399' => '雨', '400' => '小雪', '401' => '中雪', '402' => '大雪', '403' => '暴雪', '404' => '雨夹雪', '405' => '雨雪天气', '406' => '阵雨夹雪', '407' => '阵雪', '408' => '小到中雪', '409' => '中到大雪', '410' => '大到暴雪', '499' => '雪', '500' => '薄雾', '501' => '雾', '502' => '霾', '503' => '扬沙', '504' => '浮尘', '507' => '沙尘暴', '508' => '强沙尘暴', '509' => '浓雾', '510' => '强浓雾', '511' => '中度霾', '512' => '重度霾', '513' => '严重霾', '514' => '大雾', '515' => '特强浓雾', '900' => '热', '901' => '冷', '999' => '未知', ); return isset($data[$code]) ? $data[$code] : ''; } function weather_translate_ru($code){ $data = array( '100' => 'чинг', '101' => 'облачно', '102' => 'Меньше облако', '103' => 'Ясная и облачная', '104' => 'инь', '200' => 'дует', '201' => 'спокойствие', '202' => 'ветерок', '203' => 'зефир', '204' => 'Свежий ветер', '205' => 'Сильный ветер/сильный ветер', '206' => 'шквал', '207' => 'ветер', '208' => 'шторм', '209' => 'шторм', '210' => 'Сильный ветер', '211' => 'ураган', '212' => 'Торнадо', '213' => 'Тропический шторм', '300' => 'ливень', '301' => 'Сильный душ', '302' => 'Грозовой дождь', '303' => 'Сильный грозовой дождь', '304' => 'Ливень сопровождается градом', '305' => 'дождик', '306' => 'Средний дождь', '307' => 'дождь', '308' => 'Экстремальный дождь', '309' => 'Дождик/мелкий дождь', '310' => 'Проливной дождь', '311' => 'Сильный дождь', '312' => 'Сильный ливень', '313' => 'Ледяной дождь', '314' => 'Немного дождя', '315' => 'Под дождём', '316' => 'Большой до грозы', '317' => 'От грозы до грозы', '318' => 'Сильные ливни, сильные ливни', '399' => 'дождь', '400' => 'Мелкий снежок', '401' => 'средний снег', '402' => 'снегопад', '403' => 'Снежная буря', '404' => 'Дождь и снег', '405' => 'Дождливая и снежная погода', '406' => 'Дождь и снег', '407' => 'снежный', '408' => 'Маленький до снега', '409' => 'Прямо в снег', '410' => 'От большой до снежной бури', '499' => 'снег', '500' => 'дымка', '501' => 'туман', '502' => 'мгла', '503' => 'янша', '504' => 'пыль', '507' => 'Песчаная буря', '508' => 'Сильная песчаная буря', '509' => 'Густой туман', '510' => 'Сильный густой туман', '511' => 'Умеренный туман', '512' => 'Тяжелая смола', '513' => 'Туман', '514' => 'Сильный туман', '515' => 'Густой туман', '900' => 'горячая', '901' => 'холодно', '999' => 'неизвестный', ); return isset($data[$code]) ? $data[$code] : ''; } //输出json function json_result($code, $msg, $data = array()) { $res = array('code' => $code,'msg' => $msg,'data' => $data); $CI =& get_instance(); $clientId = $CI->input->post('clientId',true); if (!empty($clientId)) { if (is_array($res['data']) && !isset($res['data']['status'])) { $res['data']['status'] = 2; }else{ $res['data'] = array('status'=>2); } exit(send_websocket($clientId,$res)); }else{ echo json_encode($res); } } // 获取jwt的token值 function get_jwt_token(){ $CI =& get_instance(); $CI->load->library('Jwt'); $payload=array("iss"=>"chirpstack-application-server","aud"=>"chirpstack-application-server","nbf"=>time()-60, "exp"=>time()+7200,'sub'=>'user','username'=>'admin'); return $CI->jwt->getToken($payload); } //发送命令到server function send_cmd($cmd, $timeout = 30, $ms_timeout = 200) { $CI =& get_instance(); $host = $CI->config->item('cmd_server'); $ip = $host['ip']; $port = $host['port']; $client = @stream_socket_client("tcp://{$ip}:{$port}", $errno, $errstr, 30); if ($client) { fwrite($client, $cmd); stream_set_timeout($client, $timeout, $ms_timeout); $result = fread($client, 8196); fclose($client); return $result; } else { return false; } } /** * 模拟post进行url请求 * @param string $url * @param string $param */ function http_post($url = '', $data = '',$header=array(),$timeout = 30) { $tuCurl = curl_init(); //参数 curl_setopt($tuCurl, CURLOPT_URL,$url); curl_setopt($tuCurl, CURLOPT_POSTFIELDS, $data); curl_setopt($tuCurl, CURLOPT_SSL_VERIFYPEER, false); // curl_setopt($tuCurl, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($tuCurl, CURLOPT_SSLVERSION, 1); curl_setopt($tuCurl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($tuCurl, CURLOPT_TIMEOUT, $timeout); if (!empty($header)) { curl_setopt($tuCurl, CURLOPT_HTTPHEADER, $header); } $tuData = curl_exec($tuCurl); curl_close($tuCurl); return $tuData; } // 文件下载 function file_download($filePath){ $file_name = basename($filePath); //下载文件名 //检查文件是否存在 if (! file_exists ( $filePath )) { exit (json_result('0012','找不到文件',array())); } else { //打开文件 $file = fopen ( $filePath, "r" ); //输入文件标签 Header ( "Content-type: application/octet-stream" ); Header ( "Accept-Ranges: bytes" ); Header ( "Accept-Length: " . filesize ( $filePath) ); Header ( "Content-Disposition: attachment; filename=" . $file_name ); //输出文件内容 //读取文件内容并直接输出到浏览器 echo fread ( $file, filesize ( $filePath ) ); fclose ( $file ); exit (); } } /** * 模拟get进行url请求 * @param string $url */ function http_get($url,$header = array()) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 0); if (!empty($header)) { curl_setopt($ch, CURLOPT_HTTPHEADER, $header); } // curl_setopt($ch, CURLOPT_TIMEOUT_MS, 1); $result = curl_exec($ch); curl_close($ch); return $result; } //截取字符串 function cut_str($string, $length, $append=true) { if(strlen($string) <= $length ) { return $string; } else { $i = 0; while ($i < $length) { $stringTMP = substr($string,$i,1); if ( ord($stringTMP) >=224 ) { $stringTMP = substr($string,$i,3); $i = $i + 3; } elseif( ord($stringTMP) >=192 ) { $stringTMP = substr($string,$i,2); $i = $i + 2; } else { $i = $i + 1; } $stringLast[] = $stringTMP; } $stringLast = implode("",$stringLast); if($append) { $stringLast .= "..."; } return $stringLast; } } //填充数组不存在的键值对 function fillUnsetData($array, $length) { for ($i=1; $i <= $length; $i++) { if (!isset($array[$i])) { $array[$i] = ''; } } return $array; } //查找数组第一个元素的key function findFirstKey($array) { foreach ($array as $k => $v){ return $k; } } function doAsyncRequest($url, $param=array()){ $urlinfo = parse_url($url); $host = $urlinfo['host']; $path = $urlinfo['path']; $query = isset($param)? http_build_query($param) : ''; $port = 80; $errno = 0; $errstr = ''; $timeout = 10; $fp = fsockopen($host, $port, $errno, $errstr, $timeout); $out = "POST ".$path." HTTP/1.1\r\n"; $out .= "host:".$host."\r\n"; $out .= "content-length:".strlen($query)."\r\n"; $out .= "content-type:application/x-www-form-urlencoded\r\n"; $out .= "connection:close\r\n\r\n"; $out .= $query; fputs($fp, $out); fclose($fp); } function send_websocket($clientid,$data = array(),$resType='cmd') { if (!empty($clientid)) { $CI =& get_instance(); $CI->db->insert('message',['client'=>$clientid,'msg'=>json_encode($data),'type'=>'cmd']); } } //token生成算法 function generate_token($username, $password, $client_key) { $CI =& get_instance(); $salt = $CI->config->config['encryption_key']; return md5($username.$password.$client_key.$salt); // return md5($username.$password.date('yyyy').date('mm').$client_key.$salt); } //获取汉字拼音的第一个字母 function get_first_char($str) { $firstchar_ord = ord(strtoupper($str{0})); if (($firstchar_ord >= 65 and $firstchar_ord <= 91) or ($firstchar_ord >= 48 and $firstchar_ord <= 57)) return $str{0}; $s = iconv("UTF-8", "GBK//TRANSLIT//IGNORE", $str); $asc = ord($s{0}) * 256 + ord($s{1}) - 65536; if ($asc >= - 20319 and $asc <= - 20284) return "A"; if ($asc >= - 20283 and $asc <= - 19776) return "B"; if ($asc >= - 19775 and $asc <= - 19219) return "C"; if ($asc >= - 19218 and $asc <= - 18711) return "D"; if ($asc >= - 18710 and $asc <= - 18527) return "E"; if ($asc >= - 18526 and $asc <= - 18240) return "F"; if ($asc >= - 18239 and $asc <= - 17923) return "G"; if ($asc >= - 17922 and $asc <= - 17418) return "H"; if ($asc >= - 17417 and $asc <= - 16475) return "J"; if ($asc >= - 16474 and $asc <= - 16213) return "K"; if ($asc >= - 16212 and $asc <= - 15641) return "L"; if ($asc >= - 15640 and $asc <= - 15166) return "M"; if ($asc >= - 15165 and $asc <= - 14923) return "N"; if ($asc >= - 14922 and $asc <= - 14915) return "O"; if ($asc >= - 14914 and $asc <= - 14631) return "P"; if ($asc >= - 14630 and $asc <= - 14150) return "Q"; if ($asc >= - 14149 and $asc <= - 14091) return "R"; if ($asc >= - 14090 and $asc <= - 13319) return "S"; if ($asc >= - 13318 and $asc <= - 12839) return "T"; if ($asc >= - 12838 and $asc <= - 12557) return "W"; if ($asc >= - 12556 and $asc <= - 11848) return "X"; if ($asc >= - 11847 and $asc <= - 11056) return "Y"; if ($asc >= - 11055 and $asc <= - 10247) return "Z"; return '~'; } //翻译错误 function transfer_error_tips($msg) { if(strpos($msg,'project not existed') !== false) { return '项目不存在'; } else if(strpos($msg,'all of networks in this project are not online') !== false) { return '当前项目下所有网络都不在线'; } else if(strpos($msg,'error check_code') !== false) { return '路灯发生未知错误'; } else if(strpos($msg,'cmd not existed') !== false) { return '未知命令'; } else if(strpos($msg,'address not correct') !== false) { return '无线模块地址不正确'; } else if(strpos($msg,'current address not online') !== false) { return '无线模块不在线'; } else if(strpos($msg,'time out no response') !== false) { return '超时未响应'; } else if(strpos($msg,'PDU error') !== false) { return 'PDU错误'; } else if(strpos($msg,'not online') !== false) { return '网络不在线'; } else if(strpos($msg,'send command timeout') !== false) { return '下发指令超时'; } else if(strpos($msg,'The file you are attempting to upload is larger than the permitted size.') !== false) { return '上传文件过大'; } else if(strpos($msg,'The filetype you are attempting to upload is not allowed.') !== false) { return '上传文件类型错误'; }else if($msg == '') { return '未知错误'; } else { return '未知错误'; } } //俄语翻译错误 function transfer_error_tips_ru($msg) { if(strpos($msg,'project not existed') !== false) { return 'Проект не существует'; } else if(strpos($msg,'all of networks in this project are not online') !== false) { return 'Все сети в рамках текущего проекта не подключены'; } else if(strpos($msg,'error check_code') !== false) { return 'Неизвестная ошибка уличных фонарей'; } else if(strpos($msg,'cmd not existed') !== false) { return 'Неизвестная команда'; } else if(strpos($msg,'address not correct') !== false) { return 'Неверный адрес модуля'; } else if(strpos($msg,'current address not online') !== false) { return 'беспроводной модуль не подключен'; } else if(strpos($msg,'time out no response') !== false) { return 'задержка без ответа'; } else if(strpos($msg,'PDU error') !== false) { return 'ошибка PDU'; } else if(strpos($msg,'not online') !== false) { return 'сеть не работает'; } else if(strpos($msg,'send command timeout') !== false) { return 'время ожидания следующей команды'; } else if(strpos($msg,'The file you are attempting to upload is larger than the permitted size.') !== false) { return 'загружать слишком большой файл'; } else if(strpos($msg,'The filetype you are attempting to upload is not allowed.') !== false) { return 'Ошибка загрузки типа файла'; }else if($msg == '') { return 'Неизвестная ошибка'; } else { return 'Неизвестная ошибка'; } } /** * 把返回的数据集转换成Tree * @param array $list 要转换的数据集 * @param string $pid parent标记字段 * @param string $level level标记字段 * @return array * @author 麦当苗儿 */ function list_to_tree($list, $pk='id', $pid = 'pid', $child = '_child', $root = 0) { // 创建Tree $tree = array(); if(is_array($list)) { // 创建基于主键的数组引用 $refer = array(); foreach ($list as $key => $data) { $refer[$data[$pk]] =& $list[$key]; } foreach ($list as $key => $data) { // 判断是否存在parent $parentId = $data[$pid]; if ($root == $parentId) { $tree[] =& $list[$key]; }else{ if (isset($refer[$parentId])) { $parent =& $refer[$parentId]; $parent[$child][] =& $list[$key]; } } } } return $tree; } function getTree($data, $pId) { $tree = []; foreach($data as $k => $v) { if($v['pid'] == $pId) { $v['subList'] = getTree($data, $v['id']); $tree[] = $v; unset($data[$k]); } } return $tree; } // 编号设置 function set_number($n){ $n = intval($n); $res = $n + 1000000; return substr($res, 1); } ?>