code stringlengths 1 1.05M | repo_name stringlengths 6 83 | path stringlengths 3 242 | language stringclasses 222
values | license stringclasses 20
values | size int64 1 1.05M |
|---|---|---|---|---|---|
/***************************************************************************/
/* */
/* t1afm.h */
/* */
/* AFM support for Type 1 fonts (specification). */
/* */
/* Copyright 1996-2001, 2002, 2006 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
#ifndef __T1AFM_H__
#define __T1AFM_H__
#include <ft2build.h>
#include "t1objs.h"
#include FT_INTERNAL_TYPE1_TYPES_H
FT_BEGIN_HEADER
FT_LOCAL( FT_Error )
T1_Read_Metrics( FT_Face face,
FT_Stream stream );
FT_LOCAL( void )
T1_Done_Metrics( FT_Memory memory,
AFM_FontInfo fi );
FT_LOCAL( void )
T1_Get_Kerning( AFM_FontInfo fi,
FT_UInt glyph1,
FT_UInt glyph2,
FT_Vector* kerning );
FT_LOCAL( FT_Error )
T1_Get_Track_Kerning( FT_Face face,
FT_Fixed ptsize,
FT_Int degree,
FT_Fixed* kerning );
FT_END_HEADER
#endif /* __T1AFM_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/type1/t1afm.h | C | apache-2.0 | 2,015 |
/***************************************************************************/
/* */
/* t1driver.c */
/* */
/* Type 1 driver interface (body). */
/* */
/* Copyright 1996-2004, 2006, 2007, 2009, 2011, 2013 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
#include <ft2build.h>
#include "t1driver.h"
#include "t1gload.h"
#include "t1load.h"
#include "t1errors.h"
#ifndef T1_CONFIG_OPTION_NO_AFM
#include "t1afm.h"
#endif
#include FT_INTERNAL_DEBUG_H
#include FT_INTERNAL_STREAM_H
#include FT_SERVICE_MULTIPLE_MASTERS_H
#include FT_SERVICE_GLYPH_DICT_H
#include FT_SERVICE_XFREE86_NAME_H
#include FT_SERVICE_POSTSCRIPT_NAME_H
#include FT_SERVICE_POSTSCRIPT_CMAPS_H
#include FT_SERVICE_POSTSCRIPT_INFO_H
#include FT_SERVICE_KERNING_H
/*************************************************************************/
/* */
/* The macro FT_COMPONENT is used in trace mode. It is an implicit */
/* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */
/* messages during execution. */
/* */
#undef FT_COMPONENT
#define FT_COMPONENT trace_t1driver
/*
* GLYPH DICT SERVICE
*
*/
static FT_Error
t1_get_glyph_name( T1_Face face,
FT_UInt glyph_index,
FT_Pointer buffer,
FT_UInt buffer_max )
{
FT_STRCPYN( buffer, face->type1.glyph_names[glyph_index], buffer_max );
return FT_Err_Ok;
}
static FT_UInt
t1_get_name_index( T1_Face face,
FT_String* glyph_name )
{
FT_Int i;
for ( i = 0; i < face->type1.num_glyphs; i++ )
{
FT_String* gname = face->type1.glyph_names[i];
if ( !ft_strcmp( glyph_name, gname ) )
return (FT_UInt)i;
}
return 0;
}
static const FT_Service_GlyphDictRec t1_service_glyph_dict =
{
(FT_GlyphDict_GetNameFunc) t1_get_glyph_name,
(FT_GlyphDict_NameIndexFunc)t1_get_name_index
};
/*
* POSTSCRIPT NAME SERVICE
*
*/
static const char*
t1_get_ps_name( T1_Face face )
{
return (const char*) face->type1.font_name;
}
static const FT_Service_PsFontNameRec t1_service_ps_name =
{
(FT_PsName_GetFunc)t1_get_ps_name
};
/*
* MULTIPLE MASTERS SERVICE
*
*/
#ifndef T1_CONFIG_OPTION_NO_MM_SUPPORT
static const FT_Service_MultiMastersRec t1_service_multi_masters =
{
(FT_Get_MM_Func) T1_Get_Multi_Master,
(FT_Set_MM_Design_Func) T1_Set_MM_Design,
(FT_Set_MM_Blend_Func) T1_Set_MM_Blend,
(FT_Get_MM_Var_Func) T1_Get_MM_Var,
(FT_Set_Var_Design_Func)T1_Set_Var_Design
};
#endif
/*
* POSTSCRIPT INFO SERVICE
*
*/
static FT_Error
t1_ps_get_font_info( FT_Face face,
PS_FontInfoRec* afont_info )
{
*afont_info = ((T1_Face)face)->type1.font_info;
return FT_Err_Ok;
}
static FT_Error
t1_ps_get_font_extra( FT_Face face,
PS_FontExtraRec* afont_extra )
{
*afont_extra = ((T1_Face)face)->type1.font_extra;
return FT_Err_Ok;
}
static FT_Int
t1_ps_has_glyph_names( FT_Face face )
{
FT_UNUSED( face );
return 1;
}
static FT_Error
t1_ps_get_font_private( FT_Face face,
PS_PrivateRec* afont_private )
{
*afont_private = ((T1_Face)face)->type1.private_dict;
return FT_Err_Ok;
}
static FT_Long
t1_ps_get_font_value( FT_Face face,
PS_Dict_Keys key,
FT_UInt idx,
void *value,
FT_Long value_len )
{
FT_Long retval = -1;
T1_Face t1face = (T1_Face)face;
T1_Font type1 = &t1face->type1;
switch ( key )
{
case PS_DICT_FONT_TYPE:
retval = sizeof ( type1->font_type );
if ( value && value_len >= retval )
*((FT_Byte *)value) = type1->font_type;
break;
case PS_DICT_FONT_MATRIX:
if ( idx < sizeof ( type1->font_matrix ) /
sizeof ( type1->font_matrix.xx ) )
{
FT_Fixed val = 0;
retval = sizeof ( val );
if ( value && value_len >= retval )
{
switch ( idx )
{
case 0:
val = type1->font_matrix.xx;
break;
case 1:
val = type1->font_matrix.xy;
break;
case 2:
val = type1->font_matrix.yx;
break;
case 3:
val = type1->font_matrix.yy;
break;
}
*((FT_Fixed *)value) = val;
}
}
break;
case PS_DICT_FONT_BBOX:
if ( idx < sizeof ( type1->font_bbox ) /
sizeof ( type1->font_bbox.xMin ) )
{
FT_Fixed val = 0;
retval = sizeof ( val );
if ( value && value_len >= retval )
{
switch ( idx )
{
case 0:
val = type1->font_bbox.xMin;
break;
case 1:
val = type1->font_bbox.yMin;
break;
case 2:
val = type1->font_bbox.xMax;
break;
case 3:
val = type1->font_bbox.yMax;
break;
}
*((FT_Fixed *)value) = val;
}
}
break;
case PS_DICT_PAINT_TYPE:
retval = sizeof ( type1->paint_type );
if ( value && value_len >= retval )
*((FT_Byte *)value) = type1->paint_type;
break;
case PS_DICT_FONT_NAME:
retval = (FT_Long)( ft_strlen( type1->font_name ) + 1 );
if ( value && value_len >= retval )
ft_memcpy( value, (void *)( type1->font_name ), retval );
break;
case PS_DICT_UNIQUE_ID:
retval = sizeof ( type1->private_dict.unique_id );
if ( value && value_len >= retval )
*((FT_Int *)value) = type1->private_dict.unique_id;
break;
case PS_DICT_NUM_CHAR_STRINGS:
retval = sizeof ( type1->num_glyphs );
if ( value && value_len >= retval )
*((FT_Int *)value) = type1->num_glyphs;
break;
case PS_DICT_CHAR_STRING_KEY:
if ( idx < (FT_UInt)type1->num_glyphs )
{
retval = (FT_Long)( ft_strlen( type1->glyph_names[idx] ) + 1 );
if ( value && value_len >= retval )
{
ft_memcpy( value, (void *)( type1->glyph_names[idx] ), retval );
((FT_Char *)value)[retval - 1] = (FT_Char)'\0';
}
}
break;
case PS_DICT_CHAR_STRING:
if ( idx < (FT_UInt)type1->num_glyphs )
{
retval = (FT_Long)( type1->charstrings_len[idx] + 1 );
if ( value && value_len >= retval )
{
ft_memcpy( value, (void *)( type1->charstrings[idx] ),
retval - 1 );
((FT_Char *)value)[retval - 1] = (FT_Char)'\0';
}
}
break;
case PS_DICT_ENCODING_TYPE:
retval = sizeof ( type1->encoding_type );
if ( value && value_len >= retval )
*((T1_EncodingType *)value) = type1->encoding_type;
break;
case PS_DICT_ENCODING_ENTRY:
if ( type1->encoding_type == T1_ENCODING_TYPE_ARRAY &&
idx < (FT_UInt)type1->encoding.num_chars )
{
retval = (FT_Long)( ft_strlen( type1->encoding.char_name[idx] ) + 1 );
if ( value && value_len >= retval )
{
ft_memcpy( value, (void *)( type1->encoding.char_name[idx] ),
retval - 1 );
((FT_Char *)value)[retval - 1] = (FT_Char)'\0';
}
}
break;
case PS_DICT_NUM_SUBRS:
retval = sizeof ( type1->num_subrs );
if ( value && value_len >= retval )
*((FT_Int *)value) = type1->num_subrs;
break;
case PS_DICT_SUBR:
if ( idx < (FT_UInt)type1->num_subrs )
{
retval = (FT_Long)( type1->subrs_len[idx] + 1 );
if ( value && value_len >= retval )
{
ft_memcpy( value, (void *)( type1->subrs[idx] ), retval - 1 );
((FT_Char *)value)[retval - 1] = (FT_Char)'\0';
}
}
break;
case PS_DICT_STD_HW:
retval = sizeof ( type1->private_dict.standard_width[0] );
if ( value && value_len >= retval )
*((FT_UShort *)value) = type1->private_dict.standard_width[0];
break;
case PS_DICT_STD_VW:
retval = sizeof ( type1->private_dict.standard_height[0] );
if ( value && value_len >= retval )
*((FT_UShort *)value) = type1->private_dict.standard_height[0];
break;
case PS_DICT_NUM_BLUE_VALUES:
retval = sizeof ( type1->private_dict.num_blue_values );
if ( value && value_len >= retval )
*((FT_Byte *)value) = type1->private_dict.num_blue_values;
break;
case PS_DICT_BLUE_VALUE:
if ( idx < type1->private_dict.num_blue_values )
{
retval = sizeof ( type1->private_dict.blue_values[idx] );
if ( value && value_len >= retval )
*((FT_Short *)value) = type1->private_dict.blue_values[idx];
}
break;
case PS_DICT_BLUE_SCALE:
retval = sizeof ( type1->private_dict.blue_scale );
if ( value && value_len >= retval )
*((FT_Fixed *)value) = type1->private_dict.blue_scale;
break;
case PS_DICT_BLUE_FUZZ:
retval = sizeof ( type1->private_dict.blue_fuzz );
if ( value && value_len >= retval )
*((FT_Int *)value) = type1->private_dict.blue_fuzz;
break;
case PS_DICT_BLUE_SHIFT:
retval = sizeof ( type1->private_dict.blue_shift );
if ( value && value_len >= retval )
*((FT_Int *)value) = type1->private_dict.blue_shift;
break;
case PS_DICT_NUM_OTHER_BLUES:
retval = sizeof ( type1->private_dict.num_other_blues );
if ( value && value_len >= retval )
*((FT_Byte *)value) = type1->private_dict.num_other_blues;
break;
case PS_DICT_OTHER_BLUE:
if ( idx < type1->private_dict.num_other_blues )
{
retval = sizeof ( type1->private_dict.other_blues[idx] );
if ( value && value_len >= retval )
*((FT_Short *)value) = type1->private_dict.other_blues[idx];
}
break;
case PS_DICT_NUM_FAMILY_BLUES:
retval = sizeof ( type1->private_dict.num_family_blues );
if ( value && value_len >= retval )
*((FT_Byte *)value) = type1->private_dict.num_family_blues;
break;
case PS_DICT_FAMILY_BLUE:
if ( idx < type1->private_dict.num_family_blues )
{
retval = sizeof ( type1->private_dict.family_blues[idx] );
if ( value && value_len >= retval )
*((FT_Short *)value) = type1->private_dict.family_blues[idx];
}
break;
case PS_DICT_NUM_FAMILY_OTHER_BLUES:
retval = sizeof ( type1->private_dict.num_family_other_blues );
if ( value && value_len >= retval )
*((FT_Byte *)value) = type1->private_dict.num_family_other_blues;
break;
case PS_DICT_FAMILY_OTHER_BLUE:
if ( idx < type1->private_dict.num_family_other_blues )
{
retval = sizeof ( type1->private_dict.family_other_blues[idx] );
if ( value && value_len >= retval )
*((FT_Short *)value) = type1->private_dict.family_other_blues[idx];
}
break;
case PS_DICT_NUM_STEM_SNAP_H:
retval = sizeof ( type1->private_dict.num_snap_widths );
if ( value && value_len >= retval )
*((FT_Byte *)value) = type1->private_dict.num_snap_widths;
break;
case PS_DICT_STEM_SNAP_H:
if ( idx < type1->private_dict.num_snap_widths )
{
retval = sizeof ( type1->private_dict.snap_widths[idx] );
if ( value && value_len >= retval )
*((FT_Short *)value) = type1->private_dict.snap_widths[idx];
}
break;
case PS_DICT_NUM_STEM_SNAP_V:
retval = sizeof ( type1->private_dict.num_snap_heights );
if ( value && value_len >= retval )
*((FT_Byte *)value) = type1->private_dict.num_snap_heights;
break;
case PS_DICT_STEM_SNAP_V:
if ( idx < type1->private_dict.num_snap_heights )
{
retval = sizeof ( type1->private_dict.snap_heights[idx] );
if ( value && value_len >= retval )
*((FT_Short *)value) = type1->private_dict.snap_heights[idx];
}
break;
case PS_DICT_RND_STEM_UP:
retval = sizeof ( type1->private_dict.round_stem_up );
if ( value && value_len >= retval )
*((FT_Bool *)value) = type1->private_dict.round_stem_up;
break;
case PS_DICT_FORCE_BOLD:
retval = sizeof ( type1->private_dict.force_bold );
if ( value && value_len >= retval )
*((FT_Bool *)value) = type1->private_dict.force_bold;
break;
case PS_DICT_MIN_FEATURE:
if ( idx < sizeof ( type1->private_dict.min_feature ) /
sizeof ( type1->private_dict.min_feature[0] ) )
{
retval = sizeof ( type1->private_dict.min_feature[idx] );
if ( value && value_len >= retval )
*((FT_Short *)value) = type1->private_dict.min_feature[idx];
}
break;
case PS_DICT_LEN_IV:
retval = sizeof ( type1->private_dict.lenIV );
if ( value && value_len >= retval )
*((FT_Int *)value) = type1->private_dict.lenIV;
break;
case PS_DICT_PASSWORD:
retval = sizeof ( type1->private_dict.password );
if ( value && value_len >= retval )
*((FT_Long *)value) = type1->private_dict.password;
break;
case PS_DICT_LANGUAGE_GROUP:
retval = sizeof ( type1->private_dict.language_group );
if ( value && value_len >= retval )
*((FT_Long *)value) = type1->private_dict.language_group;
break;
case PS_DICT_IS_FIXED_PITCH:
retval = sizeof ( type1->font_info.is_fixed_pitch );
if ( value && value_len >= retval )
*((FT_Bool *)value) = type1->font_info.is_fixed_pitch;
break;
case PS_DICT_UNDERLINE_POSITION:
retval = sizeof ( type1->font_info.underline_position );
if ( value && value_len >= retval )
*((FT_Short *)value) = type1->font_info.underline_position;
break;
case PS_DICT_UNDERLINE_THICKNESS:
retval = sizeof ( type1->font_info.underline_thickness );
if ( value && value_len >= retval )
*((FT_UShort *)value) = type1->font_info.underline_thickness;
break;
case PS_DICT_FS_TYPE:
retval = sizeof ( type1->font_extra.fs_type );
if ( value && value_len >= retval )
*((FT_UShort *)value) = type1->font_extra.fs_type;
break;
case PS_DICT_VERSION:
retval = (FT_Long)( ft_strlen( type1->font_info.version ) + 1 );
if ( value && value_len >= retval )
ft_memcpy( value, (void *)( type1->font_info.version ), retval );
break;
case PS_DICT_NOTICE:
retval = (FT_Long)( ft_strlen( type1->font_info.notice ) + 1 );
if ( value && value_len >= retval )
ft_memcpy( value, (void *)( type1->font_info.notice ), retval );
break;
case PS_DICT_FULL_NAME:
retval = (FT_Long)( ft_strlen( type1->font_info.full_name ) + 1 );
if ( value && value_len >= retval )
ft_memcpy( value, (void *)( type1->font_info.full_name ), retval );
break;
case PS_DICT_FAMILY_NAME:
retval = (FT_Long)( ft_strlen( type1->font_info.family_name ) + 1 );
if ( value && value_len >= retval )
ft_memcpy( value, (void *)( type1->font_info.family_name ), retval );
break;
case PS_DICT_WEIGHT:
retval = (FT_Long)( ft_strlen( type1->font_info.weight ) + 1 );
if ( value && value_len >= retval )
ft_memcpy( value, (void *)( type1->font_info.weight ), retval );
break;
case PS_DICT_ITALIC_ANGLE:
retval = sizeof ( type1->font_info.italic_angle );
if ( value && value_len >= retval )
*((FT_Long *)value) = type1->font_info.italic_angle;
break;
default:
break;
}
return retval;
}
static const FT_Service_PsInfoRec t1_service_ps_info =
{
(PS_GetFontInfoFunc) t1_ps_get_font_info,
(PS_GetFontExtraFunc) t1_ps_get_font_extra,
(PS_HasGlyphNamesFunc) t1_ps_has_glyph_names,
(PS_GetFontPrivateFunc)t1_ps_get_font_private,
(PS_GetFontValueFunc) t1_ps_get_font_value,
};
#ifndef T1_CONFIG_OPTION_NO_AFM
static const FT_Service_KerningRec t1_service_kerning =
{
T1_Get_Track_Kerning,
};
#endif
/*
* SERVICE LIST
*
*/
static const FT_ServiceDescRec t1_services[] =
{
{ FT_SERVICE_ID_POSTSCRIPT_FONT_NAME, &t1_service_ps_name },
{ FT_SERVICE_ID_GLYPH_DICT, &t1_service_glyph_dict },
{ FT_SERVICE_ID_XF86_NAME, FT_XF86_FORMAT_TYPE_1 },
{ FT_SERVICE_ID_POSTSCRIPT_INFO, &t1_service_ps_info },
#ifndef T1_CONFIG_OPTION_NO_AFM
{ FT_SERVICE_ID_KERNING, &t1_service_kerning },
#endif
#ifndef T1_CONFIG_OPTION_NO_MM_SUPPORT
{ FT_SERVICE_ID_MULTI_MASTERS, &t1_service_multi_masters },
#endif
{ NULL, NULL }
};
FT_CALLBACK_DEF( FT_Module_Interface )
Get_Interface( FT_Module module,
const FT_String* t1_interface )
{
FT_UNUSED( module );
return ft_service_list_lookup( t1_services, t1_interface );
}
#ifndef T1_CONFIG_OPTION_NO_AFM
/*************************************************************************/
/* */
/* <Function> */
/* Get_Kerning */
/* */
/* <Description> */
/* A driver method used to return the kerning vector between two */
/* glyphs of the same face. */
/* */
/* <Input> */
/* face :: A handle to the source face object. */
/* */
/* left_glyph :: The index of the left glyph in the kern pair. */
/* */
/* right_glyph :: The index of the right glyph in the kern pair. */
/* */
/* <Output> */
/* kerning :: The kerning vector. This is in font units for */
/* scalable formats, and in pixels for fixed-sizes */
/* formats. */
/* */
/* <Return> */
/* FreeType error code. 0 means success. */
/* */
/* <Note> */
/* Only horizontal layouts (left-to-right & right-to-left) are */
/* supported by this function. Other layouts, or more sophisticated */
/* kernings are out of scope of this method (the basic driver */
/* interface is meant to be simple). */
/* */
/* They can be implemented by format-specific interfaces. */
/* */
static FT_Error
Get_Kerning( FT_Face t1face, /* T1_Face */
FT_UInt left_glyph,
FT_UInt right_glyph,
FT_Vector* kerning )
{
T1_Face face = (T1_Face)t1face;
kerning->x = 0;
kerning->y = 0;
if ( face->afm_data )
T1_Get_Kerning( (AFM_FontInfo)face->afm_data,
left_glyph,
right_glyph,
kerning );
return FT_Err_Ok;
}
#endif /* T1_CONFIG_OPTION_NO_AFM */
FT_CALLBACK_TABLE_DEF
const FT_Driver_ClassRec t1_driver_class =
{
{
FT_MODULE_FONT_DRIVER |
FT_MODULE_DRIVER_SCALABLE |
FT_MODULE_DRIVER_HAS_HINTER,
sizeof ( FT_DriverRec ),
"type1",
0x10000L,
0x20000L,
0, /* format interface */
T1_Driver_Init,
T1_Driver_Done,
Get_Interface,
},
sizeof ( T1_FaceRec ),
sizeof ( T1_SizeRec ),
sizeof ( T1_GlyphSlotRec ),
T1_Face_Init,
T1_Face_Done,
T1_Size_Init,
T1_Size_Done,
T1_GlyphSlot_Init,
T1_GlyphSlot_Done,
T1_Load_Glyph,
#ifdef T1_CONFIG_OPTION_NO_AFM
0, /* FT_Face_GetKerningFunc */
0, /* FT_Face_AttachFunc */
#else
Get_Kerning,
T1_Read_Metrics,
#endif
T1_Get_Advances,
T1_Size_Request,
0 /* FT_Size_SelectFunc */
};
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/type1/t1driver.c | C | apache-2.0 | 22,352 |
/***************************************************************************/
/* */
/* t1driver.h */
/* */
/* High-level Type 1 driver interface (specification). */
/* */
/* Copyright 1996-2001, 2002 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
#ifndef __T1DRIVER_H__
#define __T1DRIVER_H__
#include <ft2build.h>
#include FT_INTERNAL_DRIVER_H
FT_BEGIN_HEADER
#ifdef FT_CONFIG_OPTION_PIC
#error "this module does not support PIC yet"
#endif
FT_EXPORT_VAR( const FT_Driver_ClassRec ) t1_driver_class;
FT_END_HEADER
#endif /* __T1DRIVER_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/type1/t1driver.h | C | apache-2.0 | 1,571 |
/***************************************************************************/
/* */
/* t1errors.h */
/* */
/* Type 1 error codes (specification only). */
/* */
/* Copyright 2001, 2012 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
/*************************************************************************/
/* */
/* This file is used to define the Type 1 error enumeration constants. */
/* */
/*************************************************************************/
#ifndef __T1ERRORS_H__
#define __T1ERRORS_H__
#include FT_MODULE_ERRORS_H
#undef __FTERRORS_H__
#undef FT_ERR_PREFIX
#define FT_ERR_PREFIX T1_Err_
#define FT_ERR_BASE FT_Mod_Err_Type1
#include FT_ERRORS_H
#endif /* __T1ERRORS_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/type1/t1errors.h | C | apache-2.0 | 1,896 |
/***************************************************************************/
/* */
/* t1gload.c */
/* */
/* Type 1 Glyph Loader (body). */
/* */
/* Copyright 1996-2006, 2008-2010, 2013, 2014 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
#include <ft2build.h>
#include "t1gload.h"
#include FT_INTERNAL_CALC_H
#include FT_INTERNAL_DEBUG_H
#include FT_INTERNAL_STREAM_H
#include FT_OUTLINE_H
#include FT_INTERNAL_POSTSCRIPT_AUX_H
#include "t1errors.h"
/*************************************************************************/
/* */
/* The macro FT_COMPONENT is used in trace mode. It is an implicit */
/* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */
/* messages during execution. */
/* */
#undef FT_COMPONENT
#define FT_COMPONENT trace_t1gload
/*************************************************************************/
/*************************************************************************/
/*************************************************************************/
/********** *********/
/********** COMPUTE THE MAXIMUM ADVANCE WIDTH *********/
/********** *********/
/********** The following code is in charge of computing *********/
/********** the maximum advance width of the font. It *********/
/********** quickly processes each glyph charstring to *********/
/********** extract the value from either a `sbw' or `seac' *********/
/********** operator. *********/
/********** *********/
/*************************************************************************/
/*************************************************************************/
/*************************************************************************/
FT_LOCAL_DEF( FT_Error )
T1_Parse_Glyph_And_Get_Char_String( T1_Decoder decoder,
FT_UInt glyph_index,
FT_Data* char_string )
{
T1_Face face = (T1_Face)decoder->builder.face;
T1_Font type1 = &face->type1;
FT_Error error = FT_Err_Ok;
#ifdef FT_CONFIG_OPTION_INCREMENTAL
FT_Incremental_InterfaceRec *inc =
face->root.internal->incremental_interface;
#endif
decoder->font_matrix = type1->font_matrix;
decoder->font_offset = type1->font_offset;
#ifdef FT_CONFIG_OPTION_INCREMENTAL
/* For incremental fonts get the character data using the */
/* callback function. */
if ( inc )
error = inc->funcs->get_glyph_data( inc->object,
glyph_index, char_string );
else
#endif /* FT_CONFIG_OPTION_INCREMENTAL */
/* For ordinary fonts get the character data stored in the face record. */
{
char_string->pointer = type1->charstrings[glyph_index];
char_string->length = (FT_Int)type1->charstrings_len[glyph_index];
}
if ( !error )
error = decoder->funcs.parse_charstrings(
decoder, (FT_Byte*)char_string->pointer,
char_string->length );
#ifdef FT_CONFIG_OPTION_INCREMENTAL
/* Incremental fonts can optionally override the metrics. */
if ( !error && inc && inc->funcs->get_glyph_metrics )
{
FT_Incremental_MetricsRec metrics;
metrics.bearing_x = FIXED_TO_INT( decoder->builder.left_bearing.x );
metrics.bearing_y = 0;
metrics.advance = FIXED_TO_INT( decoder->builder.advance.x );
metrics.advance_v = FIXED_TO_INT( decoder->builder.advance.y );
error = inc->funcs->get_glyph_metrics( inc->object,
glyph_index, FALSE, &metrics );
decoder->builder.left_bearing.x = INT_TO_FIXED( metrics.bearing_x );
decoder->builder.advance.x = INT_TO_FIXED( metrics.advance );
decoder->builder.advance.y = INT_TO_FIXED( metrics.advance_v );
}
#endif /* FT_CONFIG_OPTION_INCREMENTAL */
return error;
}
FT_CALLBACK_DEF( FT_Error )
T1_Parse_Glyph( T1_Decoder decoder,
FT_UInt glyph_index )
{
FT_Data glyph_data;
FT_Error error = T1_Parse_Glyph_And_Get_Char_String(
decoder, glyph_index, &glyph_data );
#ifdef FT_CONFIG_OPTION_INCREMENTAL
if ( !error )
{
T1_Face face = (T1_Face)decoder->builder.face;
if ( face->root.internal->incremental_interface )
face->root.internal->incremental_interface->funcs->free_glyph_data(
face->root.internal->incremental_interface->object,
&glyph_data );
}
#endif /* FT_CONFIG_OPTION_INCREMENTAL */
return error;
}
FT_LOCAL_DEF( FT_Error )
T1_Compute_Max_Advance( T1_Face face,
FT_Pos* max_advance )
{
FT_Error error;
T1_DecoderRec decoder;
FT_Int glyph_index;
T1_Font type1 = &face->type1;
PSAux_Service psaux = (PSAux_Service)face->psaux;
FT_ASSERT( ( face->len_buildchar == 0 ) == ( face->buildchar == NULL ) );
*max_advance = 0;
/* initialize load decoder */
error = psaux->t1_decoder_funcs->init( &decoder,
(FT_Face)face,
0, /* size */
0, /* glyph slot */
(FT_Byte**)type1->glyph_names,
face->blend,
0,
FT_RENDER_MODE_NORMAL,
T1_Parse_Glyph );
if ( error )
return error;
decoder.builder.metrics_only = 1;
decoder.builder.load_points = 0;
decoder.num_subrs = type1->num_subrs;
decoder.subrs = type1->subrs;
decoder.subrs_len = type1->subrs_len;
decoder.buildchar = face->buildchar;
decoder.len_buildchar = face->len_buildchar;
*max_advance = 0;
/* for each glyph, parse the glyph charstring and extract */
/* the advance width */
for ( glyph_index = 0; glyph_index < type1->num_glyphs; glyph_index++ )
{
/* now get load the unscaled outline */
(void)T1_Parse_Glyph( &decoder, glyph_index );
if ( glyph_index == 0 || decoder.builder.advance.x > *max_advance )
*max_advance = decoder.builder.advance.x;
/* ignore the error if one occurred - skip to next glyph */
}
psaux->t1_decoder_funcs->done( &decoder );
return FT_Err_Ok;
}
FT_LOCAL_DEF( FT_Error )
T1_Get_Advances( FT_Face t1face, /* T1_Face */
FT_UInt first,
FT_UInt count,
FT_Int32 load_flags,
FT_Fixed* advances )
{
T1_Face face = (T1_Face)t1face;
T1_DecoderRec decoder;
T1_Font type1 = &face->type1;
PSAux_Service psaux = (PSAux_Service)face->psaux;
FT_UInt nn;
FT_Error error;
if ( load_flags & FT_LOAD_VERTICAL_LAYOUT )
{
for ( nn = 0; nn < count; nn++ )
advances[nn] = 0;
return FT_Err_Ok;
}
error = psaux->t1_decoder_funcs->init( &decoder,
(FT_Face)face,
0, /* size */
0, /* glyph slot */
(FT_Byte**)type1->glyph_names,
face->blend,
0,
FT_RENDER_MODE_NORMAL,
T1_Parse_Glyph );
if ( error )
return error;
decoder.builder.metrics_only = 1;
decoder.builder.load_points = 0;
decoder.num_subrs = type1->num_subrs;
decoder.subrs = type1->subrs;
decoder.subrs_len = type1->subrs_len;
decoder.buildchar = face->buildchar;
decoder.len_buildchar = face->len_buildchar;
for ( nn = 0; nn < count; nn++ )
{
error = T1_Parse_Glyph( &decoder, first + nn );
if ( !error )
advances[nn] = FIXED_TO_INT( decoder.builder.advance.x );
else
advances[nn] = 0;
}
return FT_Err_Ok;
}
FT_LOCAL_DEF( FT_Error )
T1_Load_Glyph( FT_GlyphSlot t1glyph, /* T1_GlyphSlot */
FT_Size t1size, /* T1_Size */
FT_UInt glyph_index,
FT_Int32 load_flags )
{
T1_GlyphSlot glyph = (T1_GlyphSlot)t1glyph;
FT_Error error;
T1_DecoderRec decoder;
T1_Face face = (T1_Face)t1glyph->face;
FT_Bool hinting;
T1_Font type1 = &face->type1;
PSAux_Service psaux = (PSAux_Service)face->psaux;
const T1_Decoder_Funcs decoder_funcs = psaux->t1_decoder_funcs;
FT_Matrix font_matrix;
FT_Vector font_offset;
FT_Data glyph_data;
FT_Bool must_finish_decoder = FALSE;
#ifdef FT_CONFIG_OPTION_INCREMENTAL
FT_Bool glyph_data_loaded = 0;
#endif
#ifdef FT_CONFIG_OPTION_INCREMENTAL
if ( glyph_index >= (FT_UInt)face->root.num_glyphs &&
!face->root.internal->incremental_interface )
#else
if ( glyph_index >= (FT_UInt)face->root.num_glyphs )
#endif /* FT_CONFIG_OPTION_INCREMENTAL */
{
error = FT_THROW( Invalid_Argument );
goto Exit;
}
FT_TRACE1(( "T1_Load_Glyph: glyph index %d\n", glyph_index ));
FT_ASSERT( ( face->len_buildchar == 0 ) == ( face->buildchar == NULL ) );
if ( load_flags & FT_LOAD_NO_RECURSE )
load_flags |= FT_LOAD_NO_SCALE | FT_LOAD_NO_HINTING;
if ( t1size )
{
glyph->x_scale = t1size->metrics.x_scale;
glyph->y_scale = t1size->metrics.y_scale;
}
else
{
glyph->x_scale = 0x10000L;
glyph->y_scale = 0x10000L;
}
t1glyph->outline.n_points = 0;
t1glyph->outline.n_contours = 0;
hinting = FT_BOOL( ( load_flags & FT_LOAD_NO_SCALE ) == 0 &&
( load_flags & FT_LOAD_NO_HINTING ) == 0 );
t1glyph->format = FT_GLYPH_FORMAT_OUTLINE;
error = decoder_funcs->init( &decoder,
t1glyph->face,
t1size,
t1glyph,
(FT_Byte**)type1->glyph_names,
face->blend,
FT_BOOL( hinting ),
FT_LOAD_TARGET_MODE( load_flags ),
T1_Parse_Glyph );
if ( error )
goto Exit;
must_finish_decoder = TRUE;
decoder.builder.no_recurse = FT_BOOL(
( load_flags & FT_LOAD_NO_RECURSE ) != 0 );
decoder.num_subrs = type1->num_subrs;
decoder.subrs = type1->subrs;
decoder.subrs_len = type1->subrs_len;
decoder.buildchar = face->buildchar;
decoder.len_buildchar = face->len_buildchar;
/* now load the unscaled outline */
error = T1_Parse_Glyph_And_Get_Char_String( &decoder, glyph_index,
&glyph_data );
if ( error )
goto Exit;
#ifdef FT_CONFIG_OPTION_INCREMENTAL
glyph_data_loaded = 1;
#endif
font_matrix = decoder.font_matrix;
font_offset = decoder.font_offset;
/* save new glyph tables */
decoder_funcs->done( &decoder );
must_finish_decoder = FALSE;
/* now, set the metrics -- this is rather simple, as */
/* the left side bearing is the xMin, and the top side */
/* bearing the yMax */
if ( !error )
{
t1glyph->outline.flags &= FT_OUTLINE_OWNER;
t1glyph->outline.flags |= FT_OUTLINE_REVERSE_FILL;
/* for composite glyphs, return only left side bearing and */
/* advance width */
if ( load_flags & FT_LOAD_NO_RECURSE )
{
FT_Slot_Internal internal = t1glyph->internal;
t1glyph->metrics.horiBearingX =
FIXED_TO_INT( decoder.builder.left_bearing.x );
t1glyph->metrics.horiAdvance =
FIXED_TO_INT( decoder.builder.advance.x );
internal->glyph_matrix = font_matrix;
internal->glyph_delta = font_offset;
internal->glyph_transformed = 1;
}
else
{
FT_BBox cbox;
FT_Glyph_Metrics* metrics = &t1glyph->metrics;
FT_Vector advance;
/* copy the _unscaled_ advance width */
metrics->horiAdvance =
FIXED_TO_INT( decoder.builder.advance.x );
t1glyph->linearHoriAdvance =
FIXED_TO_INT( decoder.builder.advance.x );
t1glyph->internal->glyph_transformed = 0;
if ( load_flags & FT_LOAD_VERTICAL_LAYOUT )
{
/* make up vertical ones */
metrics->vertAdvance = ( face->type1.font_bbox.yMax -
face->type1.font_bbox.yMin ) >> 16;
t1glyph->linearVertAdvance = metrics->vertAdvance;
}
else
{
metrics->vertAdvance =
FIXED_TO_INT( decoder.builder.advance.y );
t1glyph->linearVertAdvance =
FIXED_TO_INT( decoder.builder.advance.y );
}
t1glyph->format = FT_GLYPH_FORMAT_OUTLINE;
if ( t1size && t1size->metrics.y_ppem < 24 )
t1glyph->outline.flags |= FT_OUTLINE_HIGH_PRECISION;
#if 1
/* apply the font matrix, if any */
if ( font_matrix.xx != 0x10000L || font_matrix.yy != font_matrix.xx ||
font_matrix.xy != 0 || font_matrix.yx != 0 )
FT_Outline_Transform( &t1glyph->outline, &font_matrix );
if ( font_offset.x || font_offset.y )
FT_Outline_Translate( &t1glyph->outline,
font_offset.x,
font_offset.y );
advance.x = metrics->horiAdvance;
advance.y = 0;
FT_Vector_Transform( &advance, &font_matrix );
metrics->horiAdvance = advance.x + font_offset.x;
advance.x = 0;
advance.y = metrics->vertAdvance;
FT_Vector_Transform( &advance, &font_matrix );
metrics->vertAdvance = advance.y + font_offset.y;
#endif
if ( ( load_flags & FT_LOAD_NO_SCALE ) == 0 )
{
/* scale the outline and the metrics */
FT_Int n;
FT_Outline* cur = decoder.builder.base;
FT_Vector* vec = cur->points;
FT_Fixed x_scale = glyph->x_scale;
FT_Fixed y_scale = glyph->y_scale;
/* First of all, scale the points, if we are not hinting */
if ( !hinting || ! decoder.builder.hints_funcs )
for ( n = cur->n_points; n > 0; n--, vec++ )
{
vec->x = FT_MulFix( vec->x, x_scale );
vec->y = FT_MulFix( vec->y, y_scale );
}
/* Then scale the metrics */
metrics->horiAdvance = FT_MulFix( metrics->horiAdvance, x_scale );
metrics->vertAdvance = FT_MulFix( metrics->vertAdvance, y_scale );
}
/* compute the other metrics */
FT_Outline_Get_CBox( &t1glyph->outline, &cbox );
metrics->width = cbox.xMax - cbox.xMin;
metrics->height = cbox.yMax - cbox.yMin;
metrics->horiBearingX = cbox.xMin;
metrics->horiBearingY = cbox.yMax;
if ( load_flags & FT_LOAD_VERTICAL_LAYOUT )
{
/* make up vertical ones */
ft_synthesize_vertical_metrics( metrics,
metrics->vertAdvance );
}
}
/* Set control data to the glyph charstrings. Note that this is */
/* _not_ zero-terminated. */
t1glyph->control_data = (FT_Byte*)glyph_data.pointer;
t1glyph->control_len = glyph_data.length;
}
Exit:
#ifdef FT_CONFIG_OPTION_INCREMENTAL
if ( glyph_data_loaded && face->root.internal->incremental_interface )
{
face->root.internal->incremental_interface->funcs->free_glyph_data(
face->root.internal->incremental_interface->object,
&glyph_data );
/* Set the control data to null - it is no longer available if */
/* loaded incrementally. */
t1glyph->control_data = 0;
t1glyph->control_len = 0;
}
#endif
if ( must_finish_decoder )
decoder_funcs->done( &decoder );
return error;
}
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/type1/t1gload.c | C | apache-2.0 | 18,200 |
/***************************************************************************/
/* */
/* t1gload.h */
/* */
/* Type 1 Glyph Loader (specification). */
/* */
/* Copyright 1996-2001, 2002, 2003, 2008, 2011 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
#ifndef __T1GLOAD_H__
#define __T1GLOAD_H__
#include <ft2build.h>
#include "t1objs.h"
FT_BEGIN_HEADER
FT_LOCAL( FT_Error )
T1_Compute_Max_Advance( T1_Face face,
FT_Pos* max_advance );
FT_LOCAL( FT_Error )
T1_Get_Advances( FT_Face face,
FT_UInt first,
FT_UInt count,
FT_Int32 load_flags,
FT_Fixed* advances );
FT_LOCAL( FT_Error )
T1_Load_Glyph( FT_GlyphSlot glyph,
FT_Size size,
FT_UInt glyph_index,
FT_Int32 load_flags );
FT_END_HEADER
#endif /* __T1GLOAD_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/type1/t1gload.h | C | apache-2.0 | 1,934 |
/***************************************************************************/
/* */
/* t1load.c */
/* */
/* Type 1 font loader (body). */
/* */
/* Copyright 1996-2014 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
/*************************************************************************/
/* */
/* This is the new and improved Type 1 data loader for FreeType 2. The */
/* old loader has several problems: it is slow, complex, difficult to */
/* maintain, and contains incredible hacks to make it accept some */
/* ill-formed Type 1 fonts without hiccup-ing. Moreover, about 5% of */
/* the Type 1 fonts on my machine still aren't loaded correctly by it. */
/* */
/* This version is much simpler, much faster and also easier to read and */
/* maintain by a great order of magnitude. The idea behind it is to */
/* _not_ try to read the Type 1 token stream with a state machine (i.e. */
/* a Postscript-like interpreter) but rather to perform simple pattern */
/* matching. */
/* */
/* Indeed, nearly all data definitions follow a simple pattern like */
/* */
/* ... /Field <data> ... */
/* */
/* where <data> can be a number, a boolean, a string, or an array of */
/* numbers. There are a few exceptions, namely the encoding, font name, */
/* charstrings, and subrs; they are handled with a special pattern */
/* matching routine. */
/* */
/* All other common cases are handled very simply. The matching rules */
/* are defined in the file `t1tokens.h' through the use of several */
/* macros calls PARSE_XXX. This file is included twice here; the first */
/* time to generate parsing callback functions, the second time to */
/* generate a table of keywords (with pointers to the associated */
/* callback functions). */
/* */
/* The function `parse_dict' simply scans *linearly* a given dictionary */
/* (either the top-level or private one) and calls the appropriate */
/* callback when it encounters an immediate keyword. */
/* */
/* This is by far the fastest way one can find to parse and read all */
/* data. */
/* */
/* This led to tremendous code size reduction. Note that later, the */
/* glyph loader will also be _greatly_ simplified, and the automatic */
/* hinter will replace the clumsy `t1hinter'. */
/* */
/*************************************************************************/
#include <ft2build.h>
#include FT_INTERNAL_DEBUG_H
#include FT_CONFIG_CONFIG_H
#include FT_MULTIPLE_MASTERS_H
#include FT_INTERNAL_TYPE1_TYPES_H
#include FT_INTERNAL_CALC_H
#include "t1load.h"
#include "t1errors.h"
#ifdef FT_CONFIG_OPTION_INCREMENTAL
#define IS_INCREMENTAL (FT_Bool)( face->root.internal->incremental_interface != 0 )
#else
#define IS_INCREMENTAL 0
#endif
/*************************************************************************/
/* */
/* The macro FT_COMPONENT is used in trace mode. It is an implicit */
/* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */
/* messages during execution. */
/* */
#undef FT_COMPONENT
#define FT_COMPONENT trace_t1load
#ifndef T1_CONFIG_OPTION_NO_MM_SUPPORT
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** MULTIPLE MASTERS SUPPORT *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
static FT_Error
t1_allocate_blend( T1_Face face,
FT_UInt num_designs,
FT_UInt num_axis )
{
PS_Blend blend;
FT_Memory memory = face->root.memory;
FT_Error error = FT_Err_Ok;
blend = face->blend;
if ( !blend )
{
if ( FT_NEW( blend ) )
goto Exit;
blend->num_default_design_vector = 0;
face->blend = blend;
}
/* allocate design data if needed */
if ( num_designs > 0 )
{
if ( blend->num_designs == 0 )
{
FT_UInt nn;
/* allocate the blend `private' and `font_info' dictionaries */
if ( FT_NEW_ARRAY( blend->font_infos[1], num_designs ) ||
FT_NEW_ARRAY( blend->privates [1], num_designs ) ||
FT_NEW_ARRAY( blend->bboxes [1], num_designs ) ||
FT_NEW_ARRAY( blend->weight_vector, num_designs * 2 ) )
goto Exit;
blend->default_weight_vector = blend->weight_vector + num_designs;
blend->font_infos[0] = &face->type1.font_info;
blend->privates [0] = &face->type1.private_dict;
blend->bboxes [0] = &face->type1.font_bbox;
for ( nn = 2; nn <= num_designs; nn++ )
{
blend->font_infos[nn] = blend->font_infos[nn - 1] + 1;
blend->privates [nn] = blend->privates [nn - 1] + 1;
blend->bboxes [nn] = blend->bboxes [nn - 1] + 1;
}
blend->num_designs = num_designs;
}
else if ( blend->num_designs != num_designs )
goto Fail;
}
/* allocate axis data if needed */
if ( num_axis > 0 )
{
if ( blend->num_axis != 0 && blend->num_axis != num_axis )
goto Fail;
blend->num_axis = num_axis;
}
/* allocate the blend design pos table if needed */
num_designs = blend->num_designs;
num_axis = blend->num_axis;
if ( num_designs && num_axis && blend->design_pos[0] == 0 )
{
FT_UInt n;
if ( FT_NEW_ARRAY( blend->design_pos[0], num_designs * num_axis ) )
goto Exit;
for ( n = 1; n < num_designs; n++ )
blend->design_pos[n] = blend->design_pos[0] + num_axis * n;
}
Exit:
return error;
Fail:
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
FT_LOCAL_DEF( FT_Error )
T1_Get_Multi_Master( T1_Face face,
FT_Multi_Master* master )
{
PS_Blend blend = face->blend;
FT_UInt n;
FT_Error error;
error = FT_THROW( Invalid_Argument );
if ( blend )
{
master->num_axis = blend->num_axis;
master->num_designs = blend->num_designs;
for ( n = 0; n < blend->num_axis; n++ )
{
FT_MM_Axis* axis = master->axis + n;
PS_DesignMap map = blend->design_map + n;
axis->name = blend->axis_names[n];
axis->minimum = map->design_points[0];
axis->maximum = map->design_points[map->num_points - 1];
}
error = FT_Err_Ok;
}
return error;
}
/*************************************************************************/
/* */
/* Given a normalized (blend) coordinate, figure out the design */
/* coordinate appropriate for that value. */
/* */
FT_LOCAL_DEF( FT_Fixed )
mm_axis_unmap( PS_DesignMap axismap,
FT_Fixed ncv )
{
int j;
if ( ncv <= axismap->blend_points[0] )
return INT_TO_FIXED( axismap->design_points[0] );
for ( j = 1; j < axismap->num_points; ++j )
{
if ( ncv <= axismap->blend_points[j] )
return INT_TO_FIXED( axismap->design_points[j - 1] ) +
( axismap->design_points[j] - axismap->design_points[j - 1] ) *
FT_DivFix( ncv - axismap->blend_points[j - 1],
axismap->blend_points[j] -
axismap->blend_points[j - 1] );
}
return INT_TO_FIXED( axismap->design_points[axismap->num_points - 1] );
}
/*************************************************************************/
/* */
/* Given a vector of weights, one for each design, figure out the */
/* normalized axis coordinates which gave rise to those weights. */
/* */
FT_LOCAL_DEF( void )
mm_weights_unmap( FT_Fixed* weights,
FT_Fixed* axiscoords,
FT_UInt axis_count )
{
FT_ASSERT( axis_count <= T1_MAX_MM_AXIS );
if ( axis_count == 1 )
axiscoords[0] = weights[1];
else if ( axis_count == 2 )
{
axiscoords[0] = weights[3] + weights[1];
axiscoords[1] = weights[3] + weights[2];
}
else if ( axis_count == 3 )
{
axiscoords[0] = weights[7] + weights[5] + weights[3] + weights[1];
axiscoords[1] = weights[7] + weights[6] + weights[3] + weights[2];
axiscoords[2] = weights[7] + weights[6] + weights[5] + weights[4];
}
else
{
axiscoords[0] = weights[15] + weights[13] + weights[11] + weights[9] +
weights[7] + weights[5] + weights[3] + weights[1];
axiscoords[1] = weights[15] + weights[14] + weights[11] + weights[10] +
weights[7] + weights[6] + weights[3] + weights[2];
axiscoords[2] = weights[15] + weights[14] + weights[13] + weights[12] +
weights[7] + weights[6] + weights[5] + weights[4];
axiscoords[3] = weights[15] + weights[14] + weights[13] + weights[12] +
weights[11] + weights[10] + weights[9] + weights[8];
}
}
/*************************************************************************/
/* */
/* Just a wrapper around T1_Get_Multi_Master to support the different */
/* arguments needed by the GX var distortable fonts. */
/* */
FT_LOCAL_DEF( FT_Error )
T1_Get_MM_Var( T1_Face face,
FT_MM_Var* *master )
{
FT_Memory memory = face->root.memory;
FT_MM_Var *mmvar = NULL;
FT_Multi_Master mmaster;
FT_Error error;
FT_UInt i;
FT_Fixed axiscoords[T1_MAX_MM_AXIS];
PS_Blend blend = face->blend;
error = T1_Get_Multi_Master( face, &mmaster );
if ( error )
goto Exit;
if ( FT_ALLOC( mmvar,
sizeof ( FT_MM_Var ) +
mmaster.num_axis * sizeof ( FT_Var_Axis ) ) )
goto Exit;
mmvar->num_axis = mmaster.num_axis;
mmvar->num_designs = mmaster.num_designs;
mmvar->num_namedstyles = ~0U; /* Does not apply */
mmvar->axis = (FT_Var_Axis*)&mmvar[1];
/* Point to axes after MM_Var struct */
mmvar->namedstyle = NULL;
for ( i = 0 ; i < mmaster.num_axis; ++i )
{
mmvar->axis[i].name = mmaster.axis[i].name;
mmvar->axis[i].minimum = INT_TO_FIXED( mmaster.axis[i].minimum);
mmvar->axis[i].maximum = INT_TO_FIXED( mmaster.axis[i].maximum);
mmvar->axis[i].def = ( mmvar->axis[i].minimum +
mmvar->axis[i].maximum ) / 2;
/* Does not apply. But this value is in range */
mmvar->axis[i].strid = ~0U; /* Does not apply */
mmvar->axis[i].tag = ~0U; /* Does not apply */
if ( ft_strcmp( mmvar->axis[i].name, "Weight" ) == 0 )
mmvar->axis[i].tag = FT_MAKE_TAG( 'w', 'g', 'h', 't' );
else if ( ft_strcmp( mmvar->axis[i].name, "Width" ) == 0 )
mmvar->axis[i].tag = FT_MAKE_TAG( 'w', 'd', 't', 'h' );
else if ( ft_strcmp( mmvar->axis[i].name, "OpticalSize" ) == 0 )
mmvar->axis[i].tag = FT_MAKE_TAG( 'o', 'p', 's', 'z' );
}
if ( blend->num_designs == ( 1U << blend->num_axis ) )
{
mm_weights_unmap( blend->default_weight_vector,
axiscoords,
blend->num_axis );
for ( i = 0; i < mmaster.num_axis; ++i )
mmvar->axis[i].def = mm_axis_unmap( &blend->design_map[i],
axiscoords[i] );
}
*master = mmvar;
Exit:
return error;
}
FT_LOCAL_DEF( FT_Error )
T1_Set_MM_Blend( T1_Face face,
FT_UInt num_coords,
FT_Fixed* coords )
{
PS_Blend blend = face->blend;
FT_Error error;
FT_UInt n, m;
error = FT_ERR( Invalid_Argument );
if ( blend && blend->num_axis == num_coords )
{
/* recompute the weight vector from the blend coordinates */
for ( n = 0; n < blend->num_designs; n++ )
{
FT_Fixed result = 0x10000L; /* 1.0 fixed */
for ( m = 0; m < blend->num_axis; m++ )
{
FT_Fixed factor;
/* get current blend axis position */
factor = coords[m];
if ( factor < 0 )
factor = 0;
if ( factor > 0x10000L )
factor = 0x10000L;
if ( ( n & ( 1 << m ) ) == 0 )
factor = 0x10000L - factor;
result = FT_MulFix( result, factor );
}
blend->weight_vector[n] = result;
}
error = FT_Err_Ok;
}
return error;
}
FT_LOCAL_DEF( FT_Error )
T1_Set_MM_Design( T1_Face face,
FT_UInt num_coords,
FT_Long* coords )
{
PS_Blend blend = face->blend;
FT_Error error;
FT_UInt n, p;
error = FT_ERR( Invalid_Argument );
if ( blend && blend->num_axis == num_coords )
{
/* compute the blend coordinates through the blend design map */
FT_Fixed final_blends[T1_MAX_MM_DESIGNS];
for ( n = 0; n < blend->num_axis; n++ )
{
FT_Long design = coords[n];
FT_Fixed the_blend;
PS_DesignMap map = blend->design_map + n;
FT_Long* designs = map->design_points;
FT_Fixed* blends = map->blend_points;
FT_Int before = -1, after = -1;
for ( p = 0; p < (FT_UInt)map->num_points; p++ )
{
FT_Long p_design = designs[p];
/* exact match? */
if ( design == p_design )
{
the_blend = blends[p];
goto Found;
}
if ( design < p_design )
{
after = p;
break;
}
before = p;
}
/* now interpolate if necessary */
if ( before < 0 )
the_blend = blends[0];
else if ( after < 0 )
the_blend = blends[map->num_points - 1];
else
the_blend = FT_MulDiv( design - designs[before],
blends [after] - blends [before],
designs[after] - designs[before] );
Found:
final_blends[n] = the_blend;
}
error = T1_Set_MM_Blend( face, num_coords, final_blends );
}
return error;
}
/*************************************************************************/
/* */
/* Just a wrapper around T1_Set_MM_Design to support the different */
/* arguments needed by the GX var distortable fonts. */
/* */
FT_LOCAL_DEF( FT_Error )
T1_Set_Var_Design( T1_Face face,
FT_UInt num_coords,
FT_Fixed* coords )
{
FT_Long lcoords[4]; /* maximum axis count is 4 */
FT_UInt i;
FT_Error error;
error = FT_ERR( Invalid_Argument );
if ( num_coords <= 4 && num_coords > 0 )
{
for ( i = 0; i < num_coords; ++i )
lcoords[i] = FIXED_TO_INT( coords[i] );
error = T1_Set_MM_Design( face, num_coords, lcoords );
}
return error;
}
FT_LOCAL_DEF( void )
T1_Done_Blend( T1_Face face )
{
FT_Memory memory = face->root.memory;
PS_Blend blend = face->blend;
if ( blend )
{
FT_UInt num_designs = blend->num_designs;
FT_UInt num_axis = blend->num_axis;
FT_UInt n;
/* release design pos table */
FT_FREE( blend->design_pos[0] );
for ( n = 1; n < num_designs; n++ )
blend->design_pos[n] = NULL;
/* release blend `private' and `font info' dictionaries */
FT_FREE( blend->privates[1] );
FT_FREE( blend->font_infos[1] );
FT_FREE( blend->bboxes[1] );
for ( n = 0; n < num_designs; n++ )
{
blend->privates [n] = NULL;
blend->font_infos[n] = NULL;
blend->bboxes [n] = NULL;
}
/* release weight vectors */
FT_FREE( blend->weight_vector );
blend->default_weight_vector = NULL;
/* release axis names */
for ( n = 0; n < num_axis; n++ )
FT_FREE( blend->axis_names[n] );
/* release design map */
for ( n = 0; n < num_axis; n++ )
{
PS_DesignMap dmap = blend->design_map + n;
FT_FREE( dmap->design_points );
dmap->num_points = 0;
}
FT_FREE( face->blend );
}
}
static void
parse_blend_axis_types( T1_Face face,
T1_Loader loader )
{
T1_TokenRec axis_tokens[T1_MAX_MM_AXIS];
FT_Int n, num_axis;
FT_Error error = FT_Err_Ok;
PS_Blend blend;
FT_Memory memory;
/* take an array of objects */
T1_ToTokenArray( &loader->parser, axis_tokens,
T1_MAX_MM_AXIS, &num_axis );
if ( num_axis < 0 )
{
error = FT_ERR( Ignore );
goto Exit;
}
if ( num_axis == 0 || num_axis > T1_MAX_MM_AXIS )
{
FT_ERROR(( "parse_blend_axis_types: incorrect number of axes: %d\n",
num_axis ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
/* allocate blend if necessary */
error = t1_allocate_blend( face, 0, (FT_UInt)num_axis );
if ( error )
goto Exit;
blend = face->blend;
memory = face->root.memory;
/* each token is an immediate containing the name of the axis */
for ( n = 0; n < num_axis; n++ )
{
T1_Token token = axis_tokens + n;
FT_Byte* name;
FT_PtrDist len;
/* skip first slash, if any */
if ( token->start[0] == '/' )
token->start++;
len = token->limit - token->start;
if ( len == 0 )
{
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
if ( FT_ALLOC( blend->axis_names[n], (FT_Long)( len + 1 ) ) )
goto Exit;
name = (FT_Byte*)blend->axis_names[n];
FT_MEM_COPY( name, token->start, len );
name[len] = '\0';
}
Exit:
loader->parser.root.error = error;
}
static void
parse_blend_design_positions( T1_Face face,
T1_Loader loader )
{
T1_TokenRec design_tokens[T1_MAX_MM_DESIGNS];
FT_Int num_designs;
FT_Int num_axis;
T1_Parser parser = &loader->parser;
FT_Error error = FT_Err_Ok;
PS_Blend blend;
/* get the array of design tokens -- compute number of designs */
T1_ToTokenArray( parser, design_tokens,
T1_MAX_MM_DESIGNS, &num_designs );
if ( num_designs < 0 )
{
error = FT_ERR( Ignore );
goto Exit;
}
if ( num_designs == 0 || num_designs > T1_MAX_MM_DESIGNS )
{
FT_ERROR(( "parse_blend_design_positions:"
" incorrect number of designs: %d\n",
num_designs ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
{
FT_Byte* old_cursor = parser->root.cursor;
FT_Byte* old_limit = parser->root.limit;
FT_Int n;
blend = face->blend;
num_axis = 0; /* make compiler happy */
for ( n = 0; n < num_designs; n++ )
{
T1_TokenRec axis_tokens[T1_MAX_MM_AXIS];
T1_Token token;
FT_Int axis, n_axis;
/* read axis/coordinates tokens */
token = design_tokens + n;
parser->root.cursor = token->start;
parser->root.limit = token->limit;
T1_ToTokenArray( parser, axis_tokens, T1_MAX_MM_AXIS, &n_axis );
if ( n == 0 )
{
if ( n_axis <= 0 || n_axis > T1_MAX_MM_AXIS )
{
FT_ERROR(( "parse_blend_design_positions:"
" invalid number of axes: %d\n",
n_axis ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
num_axis = n_axis;
error = t1_allocate_blend( face, num_designs, num_axis );
if ( error )
goto Exit;
blend = face->blend;
}
else if ( n_axis != num_axis )
{
FT_ERROR(( "parse_blend_design_positions: incorrect table\n" ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
/* now read each axis token into the design position */
for ( axis = 0; axis < n_axis; axis++ )
{
T1_Token token2 = axis_tokens + axis;
parser->root.cursor = token2->start;
parser->root.limit = token2->limit;
blend->design_pos[n][axis] = T1_ToFixed( parser, 0 );
}
}
loader->parser.root.cursor = old_cursor;
loader->parser.root.limit = old_limit;
}
Exit:
loader->parser.root.error = error;
}
static void
parse_blend_design_map( T1_Face face,
T1_Loader loader )
{
FT_Error error = FT_Err_Ok;
T1_Parser parser = &loader->parser;
PS_Blend blend;
T1_TokenRec axis_tokens[T1_MAX_MM_AXIS];
FT_Int n, num_axis;
FT_Byte* old_cursor;
FT_Byte* old_limit;
FT_Memory memory = face->root.memory;
T1_ToTokenArray( parser, axis_tokens,
T1_MAX_MM_AXIS, &num_axis );
if ( num_axis < 0 )
{
error = FT_ERR( Ignore );
goto Exit;
}
if ( num_axis == 0 || num_axis > T1_MAX_MM_AXIS )
{
FT_ERROR(( "parse_blend_design_map: incorrect number of axes: %d\n",
num_axis ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
old_cursor = parser->root.cursor;
old_limit = parser->root.limit;
error = t1_allocate_blend( face, 0, num_axis );
if ( error )
goto Exit;
blend = face->blend;
/* now read each axis design map */
for ( n = 0; n < num_axis; n++ )
{
PS_DesignMap map = blend->design_map + n;
T1_Token axis_token;
T1_TokenRec point_tokens[T1_MAX_MM_MAP_POINTS];
FT_Int p, num_points;
axis_token = axis_tokens + n;
parser->root.cursor = axis_token->start;
parser->root.limit = axis_token->limit;
T1_ToTokenArray( parser, point_tokens,
T1_MAX_MM_MAP_POINTS, &num_points );
if ( num_points <= 0 || num_points > T1_MAX_MM_MAP_POINTS )
{
FT_ERROR(( "parse_blend_design_map: incorrect table\n" ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
/* allocate design map data */
if ( FT_NEW_ARRAY( map->design_points, num_points * 2 ) )
goto Exit;
map->blend_points = map->design_points + num_points;
map->num_points = (FT_Byte)num_points;
for ( p = 0; p < num_points; p++ )
{
T1_Token point_token;
point_token = point_tokens + p;
/* don't include delimiting brackets */
parser->root.cursor = point_token->start + 1;
parser->root.limit = point_token->limit - 1;
map->design_points[p] = T1_ToInt( parser );
map->blend_points [p] = T1_ToFixed( parser, 0 );
}
}
parser->root.cursor = old_cursor;
parser->root.limit = old_limit;
Exit:
parser->root.error = error;
}
static void
parse_weight_vector( T1_Face face,
T1_Loader loader )
{
T1_TokenRec design_tokens[T1_MAX_MM_DESIGNS];
FT_Int num_designs;
FT_Error error = FT_Err_Ok;
T1_Parser parser = &loader->parser;
PS_Blend blend = face->blend;
T1_Token token;
FT_Int n;
FT_Byte* old_cursor;
FT_Byte* old_limit;
T1_ToTokenArray( parser, design_tokens,
T1_MAX_MM_DESIGNS, &num_designs );
if ( num_designs < 0 )
{
error = FT_ERR( Ignore );
goto Exit;
}
if ( num_designs == 0 || num_designs > T1_MAX_MM_DESIGNS )
{
FT_ERROR(( "parse_weight_vector:"
" incorrect number of designs: %d\n",
num_designs ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
if ( !blend || !blend->num_designs )
{
error = t1_allocate_blend( face, num_designs, 0 );
if ( error )
goto Exit;
blend = face->blend;
}
else if ( blend->num_designs != (FT_UInt)num_designs )
{
FT_ERROR(( "parse_weight_vector:"
" /BlendDesignPosition and /WeightVector have\n"
" "
" different number of elements\n" ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
old_cursor = parser->root.cursor;
old_limit = parser->root.limit;
for ( n = 0; n < num_designs; n++ )
{
token = design_tokens + n;
parser->root.cursor = token->start;
parser->root.limit = token->limit;
blend->default_weight_vector[n] =
blend->weight_vector[n] = T1_ToFixed( parser, 0 );
}
parser->root.cursor = old_cursor;
parser->root.limit = old_limit;
Exit:
parser->root.error = error;
}
/* e.g., /BuildCharArray [0 0 0 0 0 0 0 0] def */
/* we're only interested in the number of array elements */
static void
parse_buildchar( T1_Face face,
T1_Loader loader )
{
face->len_buildchar = T1_ToFixedArray( &loader->parser, 0, NULL, 0 );
return;
}
#endif /* !T1_CONFIG_OPTION_NO_MM_SUPPORT */
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** TYPE 1 SYMBOL PARSING *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
static FT_Error
t1_load_keyword( T1_Face face,
T1_Loader loader,
const T1_Field field )
{
FT_Error error;
void* dummy_object;
void** objects;
FT_UInt max_objects;
PS_Blend blend = face->blend;
if ( blend && blend->num_designs == 0 )
blend = NULL;
/* if the keyword has a dedicated callback, call it */
if ( field->type == T1_FIELD_TYPE_CALLBACK )
{
field->reader( (FT_Face)face, loader );
error = loader->parser.root.error;
goto Exit;
}
/* now, the keyword is either a simple field, or a table of fields; */
/* we are now going to take care of it */
switch ( field->location )
{
case T1_FIELD_LOCATION_FONT_INFO:
dummy_object = &face->type1.font_info;
objects = &dummy_object;
max_objects = 0;
if ( blend )
{
objects = (void**)blend->font_infos;
max_objects = blend->num_designs;
}
break;
case T1_FIELD_LOCATION_FONT_EXTRA:
dummy_object = &face->type1.font_extra;
objects = &dummy_object;
max_objects = 0;
break;
case T1_FIELD_LOCATION_PRIVATE:
dummy_object = &face->type1.private_dict;
objects = &dummy_object;
max_objects = 0;
if ( blend )
{
objects = (void**)blend->privates;
max_objects = blend->num_designs;
}
break;
case T1_FIELD_LOCATION_BBOX:
dummy_object = &face->type1.font_bbox;
objects = &dummy_object;
max_objects = 0;
if ( blend )
{
objects = (void**)blend->bboxes;
max_objects = blend->num_designs;
}
break;
case T1_FIELD_LOCATION_LOADER:
dummy_object = loader;
objects = &dummy_object;
max_objects = 0;
break;
case T1_FIELD_LOCATION_FACE:
dummy_object = face;
objects = &dummy_object;
max_objects = 0;
break;
#ifndef T1_CONFIG_OPTION_NO_MM_SUPPORT
case T1_FIELD_LOCATION_BLEND:
dummy_object = face->blend;
objects = &dummy_object;
max_objects = 0;
break;
#endif
default:
dummy_object = &face->type1;
objects = &dummy_object;
max_objects = 0;
}
if ( *objects )
{
if ( field->type == T1_FIELD_TYPE_INTEGER_ARRAY ||
field->type == T1_FIELD_TYPE_FIXED_ARRAY )
error = T1_Load_Field_Table( &loader->parser, field,
objects, max_objects, 0 );
else
error = T1_Load_Field( &loader->parser, field,
objects, max_objects, 0 );
}
else
{
FT_TRACE1(( "t1_load_keyword: ignoring keyword `%s'"
" which is not valid at this point\n"
" (probably due to missing keywords)\n",
field->ident ));
error = FT_Err_Ok;
}
Exit:
return error;
}
static void
parse_private( T1_Face face,
T1_Loader loader )
{
FT_UNUSED( face );
loader->keywords_encountered |= T1_PRIVATE;
}
static int
read_binary_data( T1_Parser parser,
FT_Long* size,
FT_Byte** base,
FT_Bool incremental )
{
FT_Byte* cur;
FT_Byte* limit = parser->root.limit;
/* the binary data has one of the following formats */
/* */
/* `size' [white*] RD white ....... ND */
/* `size' [white*] -| white ....... |- */
/* */
T1_Skip_Spaces( parser );
cur = parser->root.cursor;
if ( cur < limit && ft_isdigit( *cur ) )
{
FT_Long s = T1_ToInt( parser );
T1_Skip_PS_Token( parser ); /* `RD' or `-|' or something else */
/* there is only one whitespace char after the */
/* `RD' or `-|' token */
*base = parser->root.cursor + 1;
if ( s >= 0 && s < limit - *base )
{
parser->root.cursor += s + 1;
*size = s;
return !parser->root.error;
}
}
if( !incremental )
{
FT_ERROR(( "read_binary_data: invalid size field\n" ));
parser->root.error = FT_THROW( Invalid_File_Format );
}
return 0;
}
/* We now define the routines to handle the `/Encoding', `/Subrs', */
/* and `/CharStrings' dictionaries. */
static void
t1_parse_font_matrix( T1_Face face,
T1_Loader loader )
{
T1_Parser parser = &loader->parser;
FT_Matrix* matrix = &face->type1.font_matrix;
FT_Vector* offset = &face->type1.font_offset;
FT_Face root = (FT_Face)&face->root;
FT_Fixed temp[6];
FT_Fixed temp_scale;
FT_Int result;
result = T1_ToFixedArray( parser, 6, temp, 3 );
if ( result < 6 )
{
parser->root.error = FT_THROW( Invalid_File_Format );
return;
}
temp_scale = FT_ABS( temp[3] );
if ( temp_scale == 0 )
{
FT_ERROR(( "t1_parse_font_matrix: invalid font matrix\n" ));
parser->root.error = FT_THROW( Invalid_File_Format );
return;
}
/* Set Units per EM based on FontMatrix values. We set the value to */
/* 1000 / temp_scale, because temp_scale was already multiplied by */
/* 1000 (in t1_tofixed, from psobjs.c). */
root->units_per_EM = (FT_UShort)FT_DivFix( 1000, temp_scale );
/* we need to scale the values by 1.0/temp_scale */
if ( temp_scale != 0x10000L )
{
temp[0] = FT_DivFix( temp[0], temp_scale );
temp[1] = FT_DivFix( temp[1], temp_scale );
temp[2] = FT_DivFix( temp[2], temp_scale );
temp[4] = FT_DivFix( temp[4], temp_scale );
temp[5] = FT_DivFix( temp[5], temp_scale );
temp[3] = temp[3] < 0 ? -0x10000L : 0x10000L;
}
matrix->xx = temp[0];
matrix->yx = temp[1];
matrix->xy = temp[2];
matrix->yy = temp[3];
/* note that the offsets must be expressed in integer font units */
offset->x = temp[4] >> 16;
offset->y = temp[5] >> 16;
}
static void
parse_encoding( T1_Face face,
T1_Loader loader )
{
T1_Parser parser = &loader->parser;
FT_Byte* cur;
FT_Byte* limit = parser->root.limit;
PSAux_Service psaux = (PSAux_Service)face->psaux;
T1_Skip_Spaces( parser );
cur = parser->root.cursor;
if ( cur >= limit )
{
FT_ERROR(( "parse_encoding: out of bounds\n" ));
parser->root.error = FT_THROW( Invalid_File_Format );
return;
}
/* if we have a number or `[', the encoding is an array, */
/* and we must load it now */
if ( ft_isdigit( *cur ) || *cur == '[' )
{
T1_Encoding encode = &face->type1.encoding;
FT_Int count, n;
PS_Table char_table = &loader->encoding_table;
FT_Memory memory = parser->root.memory;
FT_Error error = FT_Err_Ok;
FT_Bool only_immediates = 0;
/* read the number of entries in the encoding; should be 256 */
if ( *cur == '[' )
{
count = 256;
only_immediates = 1;
parser->root.cursor++;
}
else
count = (FT_Int)T1_ToInt( parser );
T1_Skip_Spaces( parser );
if ( parser->root.cursor >= limit )
return;
/* we use a T1_Table to store our charnames */
loader->num_chars = encode->num_chars = count;
if ( FT_NEW_ARRAY( encode->char_index, count ) ||
FT_NEW_ARRAY( encode->char_name, count ) ||
FT_SET_ERROR( psaux->ps_table_funcs->init(
char_table, count, memory ) ) )
{
parser->root.error = error;
return;
}
/* We need to `zero' out encoding_table.elements */
for ( n = 0; n < count; n++ )
{
char* notdef = (char *)".notdef";
T1_Add_Table( char_table, n, notdef, 8 );
}
/* Now we need to read records of the form */
/* */
/* ... charcode /charname ... */
/* */
/* for each entry in our table. */
/* */
/* We simply look for a number followed by an immediate */
/* name. Note that this ignores correctly the sequence */
/* that is often seen in type1 fonts: */
/* */
/* 0 1 255 { 1 index exch /.notdef put } for dup */
/* */
/* used to clean the encoding array before anything else. */
/* */
/* Alternatively, if the array is directly given as */
/* */
/* /Encoding [ ... ] */
/* */
/* we only read immediates. */
n = 0;
T1_Skip_Spaces( parser );
while ( parser->root.cursor < limit )
{
cur = parser->root.cursor;
/* we stop when we encounter a `def' or `]' */
if ( *cur == 'd' && cur + 3 < limit )
{
if ( cur[1] == 'e' &&
cur[2] == 'f' &&
IS_PS_DELIM( cur[3] ) )
{
FT_TRACE6(( "encoding end\n" ));
cur += 3;
break;
}
}
if ( *cur == ']' )
{
FT_TRACE6(( "encoding end\n" ));
cur++;
break;
}
/* check whether we've found an entry */
if ( ft_isdigit( *cur ) || only_immediates )
{
FT_Int charcode;
if ( only_immediates )
charcode = n;
else
{
charcode = (FT_Int)T1_ToInt( parser );
T1_Skip_Spaces( parser );
/* protect against invalid charcode */
if ( cur == parser->root.cursor )
{
parser->root.error = FT_THROW( Unknown_File_Format );
return;
}
}
cur = parser->root.cursor;
if ( cur + 2 < limit && *cur == '/' && n < count )
{
FT_PtrDist len;
cur++;
parser->root.cursor = cur;
T1_Skip_PS_Token( parser );
if ( parser->root.cursor >= limit )
return;
if ( parser->root.error )
return;
len = parser->root.cursor - cur;
parser->root.error = T1_Add_Table( char_table, charcode,
cur, len + 1 );
if ( parser->root.error )
return;
char_table->elements[charcode][len] = '\0';
n++;
}
else if ( only_immediates )
{
/* Since the current position is not updated for */
/* immediates-only mode we would get an infinite loop if */
/* we don't do anything here. */
/* */
/* This encoding array is not valid according to the type1 */
/* specification (it might be an encoding for a CID type1 */
/* font, however), so we conclude that this font is NOT a */
/* type1 font. */
parser->root.error = FT_THROW( Unknown_File_Format );
return;
}
}
else
{
T1_Skip_PS_Token( parser );
if ( parser->root.error )
return;
}
T1_Skip_Spaces( parser );
}
face->type1.encoding_type = T1_ENCODING_TYPE_ARRAY;
parser->root.cursor = cur;
}
/* Otherwise, we should have either `StandardEncoding', */
/* `ExpertEncoding', or `ISOLatin1Encoding' */
else
{
if ( cur + 17 < limit &&
ft_strncmp( (const char*)cur, "StandardEncoding", 16 ) == 0 )
face->type1.encoding_type = T1_ENCODING_TYPE_STANDARD;
else if ( cur + 15 < limit &&
ft_strncmp( (const char*)cur, "ExpertEncoding", 14 ) == 0 )
face->type1.encoding_type = T1_ENCODING_TYPE_EXPERT;
else if ( cur + 18 < limit &&
ft_strncmp( (const char*)cur, "ISOLatin1Encoding", 17 ) == 0 )
face->type1.encoding_type = T1_ENCODING_TYPE_ISOLATIN1;
else
parser->root.error = FT_ERR( Ignore );
}
}
static void
parse_subrs( T1_Face face,
T1_Loader loader )
{
T1_Parser parser = &loader->parser;
PS_Table table = &loader->subrs;
FT_Memory memory = parser->root.memory;
FT_Error error;
FT_Int num_subrs;
PSAux_Service psaux = (PSAux_Service)face->psaux;
T1_Skip_Spaces( parser );
/* test for empty array */
if ( parser->root.cursor < parser->root.limit &&
*parser->root.cursor == '[' )
{
T1_Skip_PS_Token( parser );
T1_Skip_Spaces ( parser );
if ( parser->root.cursor >= parser->root.limit ||
*parser->root.cursor != ']' )
parser->root.error = FT_THROW( Invalid_File_Format );
return;
}
num_subrs = (FT_Int)T1_ToInt( parser );
/* position the parser right before the `dup' of the first subr */
T1_Skip_PS_Token( parser ); /* `array' */
if ( parser->root.error )
return;
T1_Skip_Spaces( parser );
/* initialize subrs array -- with synthetic fonts it is possible */
/* we get here twice */
if ( !loader->num_subrs )
{
error = psaux->ps_table_funcs->init( table, num_subrs, memory );
if ( error )
goto Fail;
}
/* the format is simple: */
/* */
/* `index' + binary data */
/* */
for (;;)
{
FT_Long idx, size;
FT_Byte* base;
/* If we are out of data, or if the next token isn't `dup', */
/* we are done. */
if ( parser->root.cursor + 4 >= parser->root.limit ||
ft_strncmp( (char*)parser->root.cursor, "dup", 3 ) != 0 )
break;
T1_Skip_PS_Token( parser ); /* `dup' */
idx = T1_ToInt( parser );
if ( !read_binary_data( parser, &size, &base, IS_INCREMENTAL ) )
return;
/* The binary string is followed by one token, e.g. `NP' */
/* (bound to `noaccess put') or by two separate tokens: */
/* `noaccess' & `put'. We position the parser right */
/* before the next `dup', if any. */
T1_Skip_PS_Token( parser ); /* `NP' or `|' or `noaccess' */
if ( parser->root.error )
return;
T1_Skip_Spaces ( parser );
if ( parser->root.cursor + 4 < parser->root.limit &&
ft_strncmp( (char*)parser->root.cursor, "put", 3 ) == 0 )
{
T1_Skip_PS_Token( parser ); /* skip `put' */
T1_Skip_Spaces ( parser );
}
/* with synthetic fonts it is possible we get here twice */
if ( loader->num_subrs )
continue;
/* some fonts use a value of -1 for lenIV to indicate that */
/* the charstrings are unencoded */
/* */
/* thanks to Tom Kacvinsky for pointing this out */
/* */
if ( face->type1.private_dict.lenIV >= 0 )
{
FT_Byte* temp;
/* some fonts define empty subr records -- this is not totally */
/* compliant to the specification (which says they should at */
/* least contain a `return'), but we support them anyway */
if ( size < face->type1.private_dict.lenIV )
{
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
/* t1_decrypt() shouldn't write to base -- make temporary copy */
if ( FT_ALLOC( temp, size ) )
goto Fail;
FT_MEM_COPY( temp, base, size );
psaux->t1_decrypt( temp, size, 4330 );
size -= face->type1.private_dict.lenIV;
error = T1_Add_Table( table, (FT_Int)idx,
temp + face->type1.private_dict.lenIV, size );
FT_FREE( temp );
}
else
error = T1_Add_Table( table, (FT_Int)idx, base, size );
if ( error )
goto Fail;
}
if ( !loader->num_subrs )
loader->num_subrs = num_subrs;
return;
Fail:
parser->root.error = error;
}
#define TABLE_EXTEND 5
static void
parse_charstrings( T1_Face face,
T1_Loader loader )
{
T1_Parser parser = &loader->parser;
PS_Table code_table = &loader->charstrings;
PS_Table name_table = &loader->glyph_names;
PS_Table swap_table = &loader->swap_table;
FT_Memory memory = parser->root.memory;
FT_Error error;
PSAux_Service psaux = (PSAux_Service)face->psaux;
FT_Byte* cur;
FT_Byte* limit = parser->root.limit;
FT_Int n, num_glyphs;
FT_UInt notdef_index = 0;
FT_Byte notdef_found = 0;
num_glyphs = (FT_Int)T1_ToInt( parser );
if ( num_glyphs < 0 )
{
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
/* some fonts like Optima-Oblique not only define the /CharStrings */
/* array but access it also */
if ( num_glyphs == 0 || parser->root.error )
return;
/* initialize tables, leaving space for addition of .notdef, */
/* if necessary, and a few other glyphs to handle buggy */
/* fonts which have more glyphs than specified. */
/* for some non-standard fonts like `Optima' which provides */
/* different outlines depending on the resolution it is */
/* possible to get here twice */
if ( !loader->num_glyphs )
{
error = psaux->ps_table_funcs->init(
code_table, num_glyphs + 1 + TABLE_EXTEND, memory );
if ( error )
goto Fail;
error = psaux->ps_table_funcs->init(
name_table, num_glyphs + 1 + TABLE_EXTEND, memory );
if ( error )
goto Fail;
/* Initialize table for swapping index notdef_index and */
/* index 0 names and codes (if necessary). */
error = psaux->ps_table_funcs->init( swap_table, 4, memory );
if ( error )
goto Fail;
}
n = 0;
for (;;)
{
FT_Long size;
FT_Byte* base;
/* the format is simple: */
/* `/glyphname' + binary data */
T1_Skip_Spaces( parser );
cur = parser->root.cursor;
if ( cur >= limit )
break;
/* we stop when we find a `def' or `end' keyword */
if ( cur + 3 < limit && IS_PS_DELIM( cur[3] ) )
{
if ( cur[0] == 'd' &&
cur[1] == 'e' &&
cur[2] == 'f' )
{
/* There are fonts which have this: */
/* */
/* /CharStrings 118 dict def */
/* Private begin */
/* CharStrings begin */
/* ... */
/* */
/* To catch this we ignore `def' if */
/* no charstring has actually been */
/* seen. */
if ( n )
break;
}
if ( cur[0] == 'e' &&
cur[1] == 'n' &&
cur[2] == 'd' )
break;
}
T1_Skip_PS_Token( parser );
if ( parser->root.error )
return;
if ( *cur == '/' )
{
FT_PtrDist len;
if ( cur + 1 >= limit )
{
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
cur++; /* skip `/' */
len = parser->root.cursor - cur;
if ( !read_binary_data( parser, &size, &base, IS_INCREMENTAL ) )
return;
/* for some non-standard fonts like `Optima' which provides */
/* different outlines depending on the resolution it is */
/* possible to get here twice */
if ( loader->num_glyphs )
continue;
error = T1_Add_Table( name_table, n, cur, len + 1 );
if ( error )
goto Fail;
/* add a trailing zero to the name table */
name_table->elements[n][len] = '\0';
/* record index of /.notdef */
if ( *cur == '.' &&
ft_strcmp( ".notdef",
(const char*)(name_table->elements[n]) ) == 0 )
{
notdef_index = n;
notdef_found = 1;
}
if ( face->type1.private_dict.lenIV >= 0 &&
n < num_glyphs + TABLE_EXTEND )
{
FT_Byte* temp;
if ( size <= face->type1.private_dict.lenIV )
{
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
/* t1_decrypt() shouldn't write to base -- make temporary copy */
if ( FT_ALLOC( temp, size ) )
goto Fail;
FT_MEM_COPY( temp, base, size );
psaux->t1_decrypt( temp, size, 4330 );
size -= face->type1.private_dict.lenIV;
error = T1_Add_Table( code_table, n,
temp + face->type1.private_dict.lenIV, size );
FT_FREE( temp );
}
else
error = T1_Add_Table( code_table, n, base, size );
if ( error )
goto Fail;
n++;
}
}
loader->num_glyphs = n;
/* if /.notdef is found but does not occupy index 0, do our magic. */
if ( notdef_found &&
ft_strcmp( ".notdef", (const char*)name_table->elements[0] ) )
{
/* Swap glyph in index 0 with /.notdef glyph. First, add index 0 */
/* name and code entries to swap_table. Then place notdef_index */
/* name and code entries into swap_table. Then swap name and code */
/* entries at indices notdef_index and 0 using values stored in */
/* swap_table. */
/* Index 0 name */
error = T1_Add_Table( swap_table, 0,
name_table->elements[0],
name_table->lengths [0] );
if ( error )
goto Fail;
/* Index 0 code */
error = T1_Add_Table( swap_table, 1,
code_table->elements[0],
code_table->lengths [0] );
if ( error )
goto Fail;
/* Index notdef_index name */
error = T1_Add_Table( swap_table, 2,
name_table->elements[notdef_index],
name_table->lengths [notdef_index] );
if ( error )
goto Fail;
/* Index notdef_index code */
error = T1_Add_Table( swap_table, 3,
code_table->elements[notdef_index],
code_table->lengths [notdef_index] );
if ( error )
goto Fail;
error = T1_Add_Table( name_table, notdef_index,
swap_table->elements[0],
swap_table->lengths [0] );
if ( error )
goto Fail;
error = T1_Add_Table( code_table, notdef_index,
swap_table->elements[1],
swap_table->lengths [1] );
if ( error )
goto Fail;
error = T1_Add_Table( name_table, 0,
swap_table->elements[2],
swap_table->lengths [2] );
if ( error )
goto Fail;
error = T1_Add_Table( code_table, 0,
swap_table->elements[3],
swap_table->lengths [3] );
if ( error )
goto Fail;
}
else if ( !notdef_found )
{
/* notdef_index is already 0, or /.notdef is undefined in */
/* charstrings dictionary. Worry about /.notdef undefined. */
/* We take index 0 and add it to the end of the table(s) */
/* and add our own /.notdef glyph to index 0. */
/* 0 333 hsbw endchar */
FT_Byte notdef_glyph[] = { 0x8B, 0xF7, 0xE1, 0x0D, 0x0E };
char* notdef_name = (char *)".notdef";
error = T1_Add_Table( swap_table, 0,
name_table->elements[0],
name_table->lengths [0] );
if ( error )
goto Fail;
error = T1_Add_Table( swap_table, 1,
code_table->elements[0],
code_table->lengths [0] );
if ( error )
goto Fail;
error = T1_Add_Table( name_table, 0, notdef_name, 8 );
if ( error )
goto Fail;
error = T1_Add_Table( code_table, 0, notdef_glyph, 5 );
if ( error )
goto Fail;
error = T1_Add_Table( name_table, n,
swap_table->elements[0],
swap_table->lengths [0] );
if ( error )
goto Fail;
error = T1_Add_Table( code_table, n,
swap_table->elements[1],
swap_table->lengths [1] );
if ( error )
goto Fail;
/* we added a glyph. */
loader->num_glyphs += 1;
}
return;
Fail:
parser->root.error = error;
}
/*************************************************************************/
/* */
/* Define the token field static variables. This is a set of */
/* T1_FieldRec variables. */
/* */
/*************************************************************************/
static
const T1_FieldRec t1_keywords[] =
{
#include "t1tokens.h"
/* now add the special functions... */
T1_FIELD_CALLBACK( "FontMatrix", t1_parse_font_matrix,
T1_FIELD_DICT_FONTDICT )
T1_FIELD_CALLBACK( "Encoding", parse_encoding,
T1_FIELD_DICT_FONTDICT )
T1_FIELD_CALLBACK( "Subrs", parse_subrs,
T1_FIELD_DICT_PRIVATE )
T1_FIELD_CALLBACK( "CharStrings", parse_charstrings,
T1_FIELD_DICT_PRIVATE )
T1_FIELD_CALLBACK( "Private", parse_private,
T1_FIELD_DICT_FONTDICT )
#ifndef T1_CONFIG_OPTION_NO_MM_SUPPORT
T1_FIELD_CALLBACK( "BlendDesignPositions", parse_blend_design_positions,
T1_FIELD_DICT_FONTDICT )
T1_FIELD_CALLBACK( "BlendDesignMap", parse_blend_design_map,
T1_FIELD_DICT_FONTDICT )
T1_FIELD_CALLBACK( "BlendAxisTypes", parse_blend_axis_types,
T1_FIELD_DICT_FONTDICT )
T1_FIELD_CALLBACK( "WeightVector", parse_weight_vector,
T1_FIELD_DICT_FONTDICT )
T1_FIELD_CALLBACK( "BuildCharArray", parse_buildchar,
T1_FIELD_DICT_PRIVATE )
#endif
{ 0, T1_FIELD_LOCATION_CID_INFO, T1_FIELD_TYPE_NONE, 0, 0, 0, 0, 0, 0 }
};
#define T1_FIELD_COUNT \
( sizeof ( t1_keywords ) / sizeof ( t1_keywords[0] ) )
static FT_Error
parse_dict( T1_Face face,
T1_Loader loader,
FT_Byte* base,
FT_Long size )
{
T1_Parser parser = &loader->parser;
FT_Byte *limit, *start_binary = NULL;
FT_Bool have_integer = 0;
parser->root.cursor = base;
parser->root.limit = base + size;
parser->root.error = FT_Err_Ok;
limit = parser->root.limit;
T1_Skip_Spaces( parser );
while ( parser->root.cursor < limit )
{
FT_Byte* cur;
cur = parser->root.cursor;
/* look for `eexec' */
if ( IS_PS_TOKEN( cur, limit, "eexec" ) )
break;
/* look for `closefile' which ends the eexec section */
else if ( IS_PS_TOKEN( cur, limit, "closefile" ) )
break;
/* in a synthetic font the base font starts after a */
/* `FontDictionary' token that is placed after a Private dict */
else if ( IS_PS_TOKEN( cur, limit, "FontDirectory" ) )
{
if ( loader->keywords_encountered & T1_PRIVATE )
loader->keywords_encountered |=
T1_FONTDIR_AFTER_PRIVATE;
parser->root.cursor += 13;
}
/* check whether we have an integer */
else if ( ft_isdigit( *cur ) )
{
start_binary = cur;
T1_Skip_PS_Token( parser );
if ( parser->root.error )
goto Exit;
have_integer = 1;
}
/* in valid Type 1 fonts we don't see `RD' or `-|' directly */
/* since those tokens are handled by parse_subrs and */
/* parse_charstrings */
else if ( *cur == 'R' && cur + 6 < limit && *(cur + 1) == 'D' &&
have_integer )
{
FT_Long s;
FT_Byte* b;
parser->root.cursor = start_binary;
if ( !read_binary_data( parser, &s, &b, IS_INCREMENTAL ) )
return FT_THROW( Invalid_File_Format );
have_integer = 0;
}
else if ( *cur == '-' && cur + 6 < limit && *(cur + 1) == '|' &&
have_integer )
{
FT_Long s;
FT_Byte* b;
parser->root.cursor = start_binary;
if ( !read_binary_data( parser, &s, &b, IS_INCREMENTAL ) )
return FT_THROW( Invalid_File_Format );
have_integer = 0;
}
/* look for immediates */
else if ( *cur == '/' && cur + 2 < limit )
{
FT_PtrDist len;
cur++;
parser->root.cursor = cur;
T1_Skip_PS_Token( parser );
if ( parser->root.error )
goto Exit;
len = parser->root.cursor - cur;
if ( len > 0 && len < 22 && parser->root.cursor < limit )
{
/* now compare the immediate name to the keyword table */
T1_Field keyword = (T1_Field)t1_keywords;
for (;;)
{
FT_Byte* name;
name = (FT_Byte*)keyword->ident;
if ( !name )
break;
if ( cur[0] == name[0] &&
len == (FT_PtrDist)ft_strlen( (const char *)name ) &&
ft_memcmp( cur, name, len ) == 0 )
{
/* We found it -- run the parsing callback! */
/* We record every instance of every field */
/* (until we reach the base font of a */
/* synthetic font) to deal adequately with */
/* multiple master fonts; this is also */
/* necessary because later PostScript */
/* definitions override earlier ones. */
/* Once we encounter `FontDirectory' after */
/* `/Private', we know that this is a synthetic */
/* font; except for `/CharStrings' we are not */
/* interested in anything that follows this */
/* `FontDirectory'. */
/* MM fonts have more than one /Private token at */
/* the top level; let's hope that all the junk */
/* that follows the first /Private token is not */
/* interesting to us. */
/* According to Adobe Tech Note #5175 (CID-Keyed */
/* Font Installation for ATM Software) a `begin' */
/* must be followed by exactly one `end', and */
/* `begin' -- `end' pairs must be accurately */
/* paired. We could use this to distinguish */
/* between the global Private and the Private */
/* dict that is a member of the Blend dict. */
const FT_UInt dict =
( loader->keywords_encountered & T1_PRIVATE )
? T1_FIELD_DICT_PRIVATE
: T1_FIELD_DICT_FONTDICT;
if ( !( dict & keyword->dict ) )
{
FT_TRACE1(( "parse_dict: found `%s' but ignoring it"
" since it is in the wrong dictionary\n",
keyword->ident ));
break;
}
if ( !( loader->keywords_encountered &
T1_FONTDIR_AFTER_PRIVATE ) ||
ft_strcmp( (const char*)name, "CharStrings" ) == 0 )
{
parser->root.error = t1_load_keyword( face,
loader,
keyword );
if ( parser->root.error != FT_Err_Ok )
{
if ( FT_ERR_EQ( parser->root.error, Ignore ) )
parser->root.error = FT_Err_Ok;
else
return parser->root.error;
}
}
break;
}
keyword++;
}
}
have_integer = 0;
}
else
{
T1_Skip_PS_Token( parser );
if ( parser->root.error )
goto Exit;
have_integer = 0;
}
T1_Skip_Spaces( parser );
}
Exit:
return parser->root.error;
}
static void
t1_init_loader( T1_Loader loader,
T1_Face face )
{
FT_UNUSED( face );
FT_MEM_ZERO( loader, sizeof ( *loader ) );
loader->num_glyphs = 0;
loader->num_chars = 0;
/* initialize the tables -- simply set their `init' field to 0 */
loader->encoding_table.init = 0;
loader->charstrings.init = 0;
loader->glyph_names.init = 0;
loader->subrs.init = 0;
loader->swap_table.init = 0;
loader->fontdata = 0;
loader->keywords_encountered = 0;
}
static void
t1_done_loader( T1_Loader loader )
{
T1_Parser parser = &loader->parser;
/* finalize tables */
T1_Release_Table( &loader->encoding_table );
T1_Release_Table( &loader->charstrings );
T1_Release_Table( &loader->glyph_names );
T1_Release_Table( &loader->swap_table );
T1_Release_Table( &loader->subrs );
/* finalize parser */
T1_Finalize_Parser( parser );
}
FT_LOCAL_DEF( FT_Error )
T1_Open_Face( T1_Face face )
{
T1_LoaderRec loader;
T1_Parser parser;
T1_Font type1 = &face->type1;
PS_Private priv = &type1->private_dict;
FT_Error error;
PSAux_Service psaux = (PSAux_Service)face->psaux;
t1_init_loader( &loader, face );
/* default values */
face->ndv_idx = -1;
face->cdv_idx = -1;
face->len_buildchar = 0;
priv->blue_shift = 7;
priv->blue_fuzz = 1;
priv->lenIV = 4;
priv->expansion_factor = (FT_Fixed)( 0.06 * 0x10000L );
priv->blue_scale = (FT_Fixed)( 0.039625 * 0x10000L * 1000 );
parser = &loader.parser;
error = T1_New_Parser( parser,
face->root.stream,
face->root.memory,
psaux );
if ( error )
goto Exit;
error = parse_dict( face, &loader,
parser->base_dict, parser->base_len );
if ( error )
goto Exit;
error = T1_Get_Private_Dict( parser, psaux );
if ( error )
goto Exit;
error = parse_dict( face, &loader,
parser->private_dict, parser->private_len );
if ( error )
goto Exit;
/* ensure even-ness of `num_blue_values' */
priv->num_blue_values &= ~1;
#ifndef T1_CONFIG_OPTION_NO_MM_SUPPORT
if ( face->blend &&
face->blend->num_default_design_vector != 0 &&
face->blend->num_default_design_vector != face->blend->num_axis )
{
/* we don't use it currently so just warn, reset, and ignore */
FT_ERROR(( "T1_Open_Face(): /DesignVector contains %u entries "
"while there are %u axes.\n",
face->blend->num_default_design_vector,
face->blend->num_axis ));
face->blend->num_default_design_vector = 0;
}
/* the following can happen for MM instances; we then treat the */
/* font as a normal PS font */
if ( face->blend &&
( !face->blend->num_designs || !face->blend->num_axis ) )
T1_Done_Blend( face );
/* another safety check */
if ( face->blend )
{
FT_UInt i;
for ( i = 0; i < face->blend->num_axis; i++ )
if ( !face->blend->design_map[i].num_points )
{
T1_Done_Blend( face );
break;
}
}
if ( face->blend )
{
if ( face->len_buildchar > 0 )
{
FT_Memory memory = face->root.memory;
if ( FT_NEW_ARRAY( face->buildchar, face->len_buildchar ) )
{
FT_ERROR(( "T1_Open_Face: cannot allocate BuildCharArray\n" ));
face->len_buildchar = 0;
goto Exit;
}
}
}
else
face->len_buildchar = 0;
#endif /* !T1_CONFIG_OPTION_NO_MM_SUPPORT */
/* now, propagate the subrs, charstrings, and glyphnames tables */
/* to the Type1 data */
type1->num_glyphs = loader.num_glyphs;
if ( loader.subrs.init )
{
loader.subrs.init = 0;
type1->num_subrs = loader.num_subrs;
type1->subrs_block = loader.subrs.block;
type1->subrs = loader.subrs.elements;
type1->subrs_len = loader.subrs.lengths;
}
if ( !IS_INCREMENTAL )
if ( !loader.charstrings.init )
{
FT_ERROR(( "T1_Open_Face: no `/CharStrings' array in face\n" ));
error = FT_THROW( Invalid_File_Format );
}
loader.charstrings.init = 0;
type1->charstrings_block = loader.charstrings.block;
type1->charstrings = loader.charstrings.elements;
type1->charstrings_len = loader.charstrings.lengths;
/* we copy the glyph names `block' and `elements' fields; */
/* the `lengths' field must be released later */
type1->glyph_names_block = loader.glyph_names.block;
type1->glyph_names = (FT_String**)loader.glyph_names.elements;
loader.glyph_names.block = 0;
loader.glyph_names.elements = 0;
/* we must now build type1.encoding when we have a custom array */
if ( type1->encoding_type == T1_ENCODING_TYPE_ARRAY )
{
FT_Int charcode, idx, min_char, max_char;
FT_Byte* glyph_name;
/* OK, we do the following: for each element in the encoding */
/* table, look up the index of the glyph having the same name */
/* the index is then stored in type1.encoding.char_index, and */
/* the name to type1.encoding.char_name */
min_char = 0;
max_char = 0;
charcode = 0;
for ( ; charcode < loader.encoding_table.max_elems; charcode++ )
{
FT_Byte* char_name;
type1->encoding.char_index[charcode] = 0;
type1->encoding.char_name [charcode] = (char *)".notdef";
char_name = loader.encoding_table.elements[charcode];
if ( char_name )
for ( idx = 0; idx < type1->num_glyphs; idx++ )
{
glyph_name = (FT_Byte*)type1->glyph_names[idx];
if ( ft_strcmp( (const char*)char_name,
(const char*)glyph_name ) == 0 )
{
type1->encoding.char_index[charcode] = (FT_UShort)idx;
type1->encoding.char_name [charcode] = (char*)glyph_name;
/* Change min/max encoded char only if glyph name is */
/* not /.notdef */
if ( ft_strcmp( (const char*)".notdef",
(const char*)glyph_name ) != 0 )
{
if ( charcode < min_char )
min_char = charcode;
if ( charcode >= max_char )
max_char = charcode + 1;
}
break;
}
}
}
type1->encoding.code_first = min_char;
type1->encoding.code_last = max_char;
type1->encoding.num_chars = loader.num_chars;
}
Exit:
t1_done_loader( &loader );
return error;
}
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/type1/t1load.c | C | apache-2.0 | 71,179 |
/***************************************************************************/
/* */
/* t1load.h */
/* */
/* Type 1 font loader (specification). */
/* */
/* Copyright 1996-2001, 2002, 2004, 2006, 2007 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
#ifndef __T1LOAD_H__
#define __T1LOAD_H__
#include <ft2build.h>
#include FT_INTERNAL_STREAM_H
#include FT_INTERNAL_POSTSCRIPT_AUX_H
#include FT_MULTIPLE_MASTERS_H
#include "t1parse.h"
FT_BEGIN_HEADER
typedef struct T1_Loader_
{
T1_ParserRec parser; /* parser used to read the stream */
FT_Int num_chars; /* number of characters in encoding */
PS_TableRec encoding_table; /* PS_Table used to store the */
/* encoding character names */
FT_Int num_glyphs;
PS_TableRec glyph_names;
PS_TableRec charstrings;
PS_TableRec swap_table; /* For moving .notdef glyph to index 0. */
FT_Int num_subrs;
PS_TableRec subrs;
FT_Bool fontdata;
FT_UInt keywords_encountered; /* T1_LOADER_ENCOUNTERED_XXX */
} T1_LoaderRec, *T1_Loader;
/* treatment of some keywords differs depending on whether */
/* they precede or follow certain other keywords */
#define T1_PRIVATE ( 1 << 0 )
#define T1_FONTDIR_AFTER_PRIVATE ( 1 << 1 )
FT_LOCAL( FT_Error )
T1_Open_Face( T1_Face face );
#ifndef T1_CONFIG_OPTION_NO_MM_SUPPORT
FT_LOCAL( FT_Error )
T1_Get_Multi_Master( T1_Face face,
FT_Multi_Master* master );
FT_LOCAL_DEF( FT_Error )
T1_Get_MM_Var( T1_Face face,
FT_MM_Var* *master );
FT_LOCAL( FT_Error )
T1_Set_MM_Blend( T1_Face face,
FT_UInt num_coords,
FT_Fixed* coords );
FT_LOCAL( FT_Error )
T1_Set_MM_Design( T1_Face face,
FT_UInt num_coords,
FT_Long* coords );
FT_LOCAL_DEF( FT_Error )
T1_Set_Var_Design( T1_Face face,
FT_UInt num_coords,
FT_Fixed* coords );
FT_LOCAL( void )
T1_Done_Blend( T1_Face face );
#endif /* !T1_CONFIG_OPTION_NO_MM_SUPPORT */
FT_END_HEADER
#endif /* __T1LOAD_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/type1/t1load.h | C | apache-2.0 | 3,279 |
/***************************************************************************/
/* */
/* t1objs.c */
/* */
/* Type 1 objects manager (body). */
/* */
/* Copyright 1996-2009, 2011, 2013 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
#include <ft2build.h>
#include FT_INTERNAL_CALC_H
#include FT_INTERNAL_DEBUG_H
#include FT_INTERNAL_STREAM_H
#include FT_TRUETYPE_IDS_H
#include "t1gload.h"
#include "t1load.h"
#include "t1errors.h"
#ifndef T1_CONFIG_OPTION_NO_AFM
#include "t1afm.h"
#endif
#include FT_SERVICE_POSTSCRIPT_CMAPS_H
#include FT_INTERNAL_POSTSCRIPT_AUX_H
/*************************************************************************/
/* */
/* The macro FT_COMPONENT is used in trace mode. It is an implicit */
/* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */
/* messages during execution. */
/* */
#undef FT_COMPONENT
#define FT_COMPONENT trace_t1objs
/*************************************************************************/
/* */
/* SIZE FUNCTIONS */
/* */
/* note that we store the global hints in the size's "internal" root */
/* field */
/* */
/*************************************************************************/
static PSH_Globals_Funcs
T1_Size_Get_Globals_Funcs( T1_Size size )
{
T1_Face face = (T1_Face)size->root.face;
PSHinter_Service pshinter = (PSHinter_Service)face->pshinter;
FT_Module module;
module = FT_Get_Module( size->root.face->driver->root.library,
"pshinter" );
return ( module && pshinter && pshinter->get_globals_funcs )
? pshinter->get_globals_funcs( module )
: 0 ;
}
FT_LOCAL_DEF( void )
T1_Size_Done( FT_Size t1size ) /* T1_Size */
{
T1_Size size = (T1_Size)t1size;
if ( size->root.internal )
{
PSH_Globals_Funcs funcs;
funcs = T1_Size_Get_Globals_Funcs( size );
if ( funcs )
funcs->destroy( (PSH_Globals)size->root.internal );
size->root.internal = 0;
}
}
FT_LOCAL_DEF( FT_Error )
T1_Size_Init( FT_Size t1size ) /* T1_Size */
{
T1_Size size = (T1_Size)t1size;
FT_Error error = FT_Err_Ok;
PSH_Globals_Funcs funcs = T1_Size_Get_Globals_Funcs( size );
if ( funcs )
{
PSH_Globals globals;
T1_Face face = (T1_Face)size->root.face;
error = funcs->create( size->root.face->memory,
&face->type1.private_dict, &globals );
if ( !error )
size->root.internal = (FT_Size_Internal)(void*)globals;
}
return error;
}
FT_LOCAL_DEF( FT_Error )
T1_Size_Request( FT_Size t1size, /* T1_Size */
FT_Size_Request req )
{
T1_Size size = (T1_Size)t1size;
PSH_Globals_Funcs funcs = T1_Size_Get_Globals_Funcs( size );
FT_Request_Metrics( size->root.face, req );
if ( funcs )
funcs->set_scale( (PSH_Globals)size->root.internal,
size->root.metrics.x_scale,
size->root.metrics.y_scale,
0, 0 );
return FT_Err_Ok;
}
/*************************************************************************/
/* */
/* SLOT FUNCTIONS */
/* */
/*************************************************************************/
FT_LOCAL_DEF( void )
T1_GlyphSlot_Done( FT_GlyphSlot slot )
{
slot->internal->glyph_hints = 0;
}
FT_LOCAL_DEF( FT_Error )
T1_GlyphSlot_Init( FT_GlyphSlot slot )
{
T1_Face face;
PSHinter_Service pshinter;
face = (T1_Face)slot->face;
pshinter = (PSHinter_Service)face->pshinter;
if ( pshinter )
{
FT_Module module;
module = FT_Get_Module( slot->face->driver->root.library,
"pshinter" );
if ( module )
{
T1_Hints_Funcs funcs;
funcs = pshinter->get_t1_funcs( module );
slot->internal->glyph_hints = (void*)funcs;
}
}
return 0;
}
/*************************************************************************/
/* */
/* FACE FUNCTIONS */
/* */
/*************************************************************************/
/*************************************************************************/
/* */
/* <Function> */
/* T1_Face_Done */
/* */
/* <Description> */
/* The face object destructor. */
/* */
/* <Input> */
/* face :: A typeless pointer to the face object to destroy. */
/* */
FT_LOCAL_DEF( void )
T1_Face_Done( FT_Face t1face ) /* T1_Face */
{
T1_Face face = (T1_Face)t1face;
FT_Memory memory;
T1_Font type1;
if ( !face )
return;
memory = face->root.memory;
type1 = &face->type1;
#ifndef T1_CONFIG_OPTION_NO_MM_SUPPORT
/* release multiple masters information */
FT_ASSERT( ( face->len_buildchar == 0 ) == ( face->buildchar == NULL ) );
if ( face->buildchar )
{
FT_FREE( face->buildchar );
face->buildchar = NULL;
face->len_buildchar = 0;
}
T1_Done_Blend( face );
face->blend = 0;
#endif
/* release font info strings */
{
PS_FontInfo info = &type1->font_info;
FT_FREE( info->version );
FT_FREE( info->notice );
FT_FREE( info->full_name );
FT_FREE( info->family_name );
FT_FREE( info->weight );
}
/* release top dictionary */
FT_FREE( type1->charstrings_len );
FT_FREE( type1->charstrings );
FT_FREE( type1->glyph_names );
FT_FREE( type1->subrs );
FT_FREE( type1->subrs_len );
FT_FREE( type1->subrs_block );
FT_FREE( type1->charstrings_block );
FT_FREE( type1->glyph_names_block );
FT_FREE( type1->encoding.char_index );
FT_FREE( type1->encoding.char_name );
FT_FREE( type1->font_name );
#ifndef T1_CONFIG_OPTION_NO_AFM
/* release afm data if present */
if ( face->afm_data )
T1_Done_Metrics( memory, (AFM_FontInfo)face->afm_data );
#endif
/* release unicode map, if any */
#if 0
FT_FREE( face->unicode_map_rec.maps );
face->unicode_map_rec.num_maps = 0;
face->unicode_map = NULL;
#endif
face->root.family_name = NULL;
face->root.style_name = NULL;
}
/*************************************************************************/
/* */
/* <Function> */
/* T1_Face_Init */
/* */
/* <Description> */
/* The face object constructor. */
/* */
/* <Input> */
/* stream :: input stream where to load font data. */
/* */
/* face_index :: The index of the font face in the resource. */
/* */
/* num_params :: Number of additional generic parameters. Ignored. */
/* */
/* params :: Additional generic parameters. Ignored. */
/* */
/* <InOut> */
/* face :: The face record to build. */
/* */
/* <Return> */
/* FreeType error code. 0 means success. */
/* */
FT_LOCAL_DEF( FT_Error )
T1_Face_Init( FT_Stream stream,
FT_Face t1face, /* T1_Face */
FT_Int face_index,
FT_Int num_params,
FT_Parameter* params )
{
T1_Face face = (T1_Face)t1face;
FT_Error error;
FT_Service_PsCMaps psnames;
PSAux_Service psaux;
T1_Font type1 = &face->type1;
PS_FontInfo info = &type1->font_info;
FT_UNUSED( num_params );
FT_UNUSED( params );
FT_UNUSED( stream );
face->root.num_faces = 1;
FT_FACE_FIND_GLOBAL_SERVICE( face, psnames, POSTSCRIPT_CMAPS );
face->psnames = psnames;
face->psaux = FT_Get_Module_Interface( FT_FACE_LIBRARY( face ),
"psaux" );
psaux = (PSAux_Service)face->psaux;
if ( !psaux )
{
FT_ERROR(( "T1_Face_Init: cannot access `psaux' module\n" ));
error = FT_THROW( Missing_Module );
goto Exit;
}
face->pshinter = FT_Get_Module_Interface( FT_FACE_LIBRARY( face ),
"pshinter" );
FT_TRACE2(( "Type 1 driver\n" ));
/* open the tokenizer; this will also check the font format */
error = T1_Open_Face( face );
if ( error )
goto Exit;
/* if we just wanted to check the format, leave successfully now */
if ( face_index < 0 )
goto Exit;
/* check the face index */
if ( face_index > 0 )
{
FT_ERROR(( "T1_Face_Init: invalid face index\n" ));
error = FT_THROW( Invalid_Argument );
goto Exit;
}
/* now load the font program into the face object */
/* initialize the face object fields */
/* set up root face fields */
{
FT_Face root = (FT_Face)&face->root;
root->num_glyphs = type1->num_glyphs;
root->face_index = 0;
root->face_flags |= FT_FACE_FLAG_SCALABLE |
FT_FACE_FLAG_HORIZONTAL |
FT_FACE_FLAG_GLYPH_NAMES |
FT_FACE_FLAG_HINTER;
if ( info->is_fixed_pitch )
root->face_flags |= FT_FACE_FLAG_FIXED_WIDTH;
if ( face->blend )
root->face_flags |= FT_FACE_FLAG_MULTIPLE_MASTERS;
/* XXX: TODO -- add kerning with .afm support */
/* The following code to extract the family and the style is very */
/* simplistic and might get some things wrong. For a full-featured */
/* algorithm you might have a look at the whitepaper given at */
/* */
/* http://blogs.msdn.com/text/archive/2007/04/23/wpf-font-selection-model.aspx */
/* get style name -- be careful, some broken fonts only */
/* have a `/FontName' dictionary entry! */
root->family_name = info->family_name;
root->style_name = NULL;
if ( root->family_name )
{
char* full = info->full_name;
char* family = root->family_name;
if ( full )
{
FT_Bool the_same = TRUE;
while ( *full )
{
if ( *full == *family )
{
family++;
full++;
}
else
{
if ( *full == ' ' || *full == '-' )
full++;
else if ( *family == ' ' || *family == '-' )
family++;
else
{
the_same = FALSE;
if ( !*family )
root->style_name = full;
break;
}
}
}
if ( the_same )
root->style_name = (char *)"Regular";
}
}
else
{
/* do we have a `/FontName'? */
if ( type1->font_name )
root->family_name = type1->font_name;
}
if ( !root->style_name )
{
if ( info->weight )
root->style_name = info->weight;
else
/* assume `Regular' style because we don't know better */
root->style_name = (char *)"Regular";
}
/* compute style flags */
root->style_flags = 0;
if ( info->italic_angle )
root->style_flags |= FT_STYLE_FLAG_ITALIC;
if ( info->weight )
{
if ( !ft_strcmp( info->weight, "Bold" ) ||
!ft_strcmp( info->weight, "Black" ) )
root->style_flags |= FT_STYLE_FLAG_BOLD;
}
/* no embedded bitmap support */
root->num_fixed_sizes = 0;
root->available_sizes = 0;
root->bbox.xMin = type1->font_bbox.xMin >> 16;
root->bbox.yMin = type1->font_bbox.yMin >> 16;
/* no `U' suffix here to 0xFFFF! */
root->bbox.xMax = ( type1->font_bbox.xMax + 0xFFFF ) >> 16;
root->bbox.yMax = ( type1->font_bbox.yMax + 0xFFFF ) >> 16;
/* Set units_per_EM if we didn't set it in t1_parse_font_matrix. */
if ( !root->units_per_EM )
root->units_per_EM = 1000;
root->ascender = (FT_Short)( root->bbox.yMax );
root->descender = (FT_Short)( root->bbox.yMin );
root->height = (FT_Short)( ( root->units_per_EM * 12 ) / 10 );
if ( root->height < root->ascender - root->descender )
root->height = (FT_Short)( root->ascender - root->descender );
/* now compute the maximum advance width */
root->max_advance_width =
(FT_Short)( root->bbox.xMax );
{
FT_Pos max_advance;
error = T1_Compute_Max_Advance( face, &max_advance );
/* in case of error, keep the standard width */
if ( !error )
root->max_advance_width = (FT_Short)FIXED_TO_INT( max_advance );
else
error = FT_Err_Ok; /* clear error */
}
root->max_advance_height = root->height;
root->underline_position = (FT_Short)info->underline_position;
root->underline_thickness = (FT_Short)info->underline_thickness;
}
{
FT_Face root = &face->root;
if ( psnames )
{
FT_CharMapRec charmap;
T1_CMap_Classes cmap_classes = psaux->t1_cmap_classes;
FT_CMap_Class clazz;
charmap.face = root;
/* first of all, try to synthesize a Unicode charmap */
charmap.platform_id = TT_PLATFORM_MICROSOFT;
charmap.encoding_id = TT_MS_ID_UNICODE_CS;
charmap.encoding = FT_ENCODING_UNICODE;
error = FT_CMap_New( cmap_classes->unicode, NULL, &charmap, NULL );
if ( error &&
FT_ERR_NEQ( error, No_Unicode_Glyph_Name ) )
goto Exit;
error = FT_Err_Ok;
/* now, generate an Adobe Standard encoding when appropriate */
charmap.platform_id = TT_PLATFORM_ADOBE;
clazz = NULL;
switch ( type1->encoding_type )
{
case T1_ENCODING_TYPE_STANDARD:
charmap.encoding = FT_ENCODING_ADOBE_STANDARD;
charmap.encoding_id = TT_ADOBE_ID_STANDARD;
clazz = cmap_classes->standard;
break;
case T1_ENCODING_TYPE_EXPERT:
charmap.encoding = FT_ENCODING_ADOBE_EXPERT;
charmap.encoding_id = TT_ADOBE_ID_EXPERT;
clazz = cmap_classes->expert;
break;
case T1_ENCODING_TYPE_ARRAY:
charmap.encoding = FT_ENCODING_ADOBE_CUSTOM;
charmap.encoding_id = TT_ADOBE_ID_CUSTOM;
clazz = cmap_classes->custom;
break;
case T1_ENCODING_TYPE_ISOLATIN1:
charmap.encoding = FT_ENCODING_ADOBE_LATIN_1;
charmap.encoding_id = TT_ADOBE_ID_LATIN_1;
clazz = cmap_classes->unicode;
break;
default:
;
}
if ( clazz )
error = FT_CMap_New( clazz, NULL, &charmap, NULL );
#if 0
/* Select default charmap */
if (root->num_charmaps)
root->charmap = root->charmaps[0];
#endif
}
}
Exit:
return error;
}
/*************************************************************************/
/* */
/* <Function> */
/* T1_Driver_Init */
/* */
/* <Description> */
/* Initializes a given Type 1 driver object. */
/* */
/* <Input> */
/* driver :: A handle to the target driver object. */
/* */
/* <Return> */
/* FreeType error code. 0 means success. */
/* */
FT_LOCAL_DEF( FT_Error )
T1_Driver_Init( FT_Module driver )
{
FT_UNUSED( driver );
return FT_Err_Ok;
}
/*************************************************************************/
/* */
/* <Function> */
/* T1_Driver_Done */
/* */
/* <Description> */
/* Finalizes a given Type 1 driver. */
/* */
/* <Input> */
/* driver :: A handle to the target Type 1 driver. */
/* */
FT_LOCAL_DEF( void )
T1_Driver_Done( FT_Module driver )
{
FT_UNUSED( driver );
}
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/type1/t1objs.c | C | apache-2.0 | 20,893 |
/***************************************************************************/
/* */
/* t1objs.h */
/* */
/* Type 1 objects manager (specification). */
/* */
/* Copyright 1996-2001, 2002, 2006, 2011 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
#ifndef __T1OBJS_H__
#define __T1OBJS_H__
#include <ft2build.h>
#include FT_INTERNAL_OBJECTS_H
#include FT_CONFIG_CONFIG_H
#include FT_INTERNAL_TYPE1_TYPES_H
FT_BEGIN_HEADER
/* The following structures must be defined by the hinter */
typedef struct T1_Size_Hints_ T1_Size_Hints;
typedef struct T1_Glyph_Hints_ T1_Glyph_Hints;
/*************************************************************************/
/* */
/* <Type> */
/* T1_Size */
/* */
/* <Description> */
/* A handle to a Type 1 size object. */
/* */
typedef struct T1_SizeRec_* T1_Size;
/*************************************************************************/
/* */
/* <Type> */
/* T1_GlyphSlot */
/* */
/* <Description> */
/* A handle to a Type 1 glyph slot object. */
/* */
typedef struct T1_GlyphSlotRec_* T1_GlyphSlot;
/*************************************************************************/
/* */
/* <Type> */
/* T1_CharMap */
/* */
/* <Description> */
/* A handle to a Type 1 character mapping object. */
/* */
/* <Note> */
/* The Type 1 format doesn't use a charmap but an encoding table. */
/* The driver is responsible for making up charmap objects */
/* corresponding to these tables. */
/* */
typedef struct T1_CharMapRec_* T1_CharMap;
/*************************************************************************/
/* */
/* HERE BEGINS THE TYPE1 SPECIFIC STUFF */
/* */
/*************************************************************************/
/*************************************************************************/
/* */
/* <Type> */
/* T1_SizeRec */
/* */
/* <Description> */
/* Type 1 size record. */
/* */
typedef struct T1_SizeRec_
{
FT_SizeRec root;
} T1_SizeRec;
FT_LOCAL( void )
T1_Size_Done( FT_Size size );
FT_LOCAL( FT_Error )
T1_Size_Request( FT_Size size,
FT_Size_Request req );
FT_LOCAL( FT_Error )
T1_Size_Init( FT_Size size );
/*************************************************************************/
/* */
/* <Type> */
/* T1_GlyphSlotRec */
/* */
/* <Description> */
/* Type 1 glyph slot record. */
/* */
typedef struct T1_GlyphSlotRec_
{
FT_GlyphSlotRec root;
FT_Bool hint;
FT_Bool scaled;
FT_Int max_points;
FT_Int max_contours;
FT_Fixed x_scale;
FT_Fixed y_scale;
} T1_GlyphSlotRec;
FT_LOCAL( FT_Error )
T1_Face_Init( FT_Stream stream,
FT_Face face,
FT_Int face_index,
FT_Int num_params,
FT_Parameter* params );
FT_LOCAL( void )
T1_Face_Done( FT_Face face );
FT_LOCAL( FT_Error )
T1_GlyphSlot_Init( FT_GlyphSlot slot );
FT_LOCAL( void )
T1_GlyphSlot_Done( FT_GlyphSlot slot );
FT_LOCAL( FT_Error )
T1_Driver_Init( FT_Module driver );
FT_LOCAL( void )
T1_Driver_Done( FT_Module driver );
FT_END_HEADER
#endif /* __T1OBJS_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/type1/t1objs.h | C | apache-2.0 | 6,797 |
/***************************************************************************/
/* */
/* t1parse.c */
/* */
/* Type 1 parser (body). */
/* */
/* Copyright 1996-2005, 2008, 2009, 2012-2014 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
/*************************************************************************/
/* */
/* The Type 1 parser is in charge of the following: */
/* */
/* - provide an implementation of a growing sequence of objects called */
/* a `T1_Table' (used to build various tables needed by the loader). */
/* */
/* - opening .pfb and .pfa files to extract their top-level and private */
/* dictionaries. */
/* */
/* - read numbers, arrays & strings from any dictionary. */
/* */
/* See `t1load.c' to see how data is loaded from the font file. */
/* */
/*************************************************************************/
#include <ft2build.h>
#include FT_INTERNAL_DEBUG_H
#include FT_INTERNAL_STREAM_H
#include FT_INTERNAL_POSTSCRIPT_AUX_H
#include "t1parse.h"
#include "t1errors.h"
/*************************************************************************/
/* */
/* The macro FT_COMPONENT is used in trace mode. It is an implicit */
/* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */
/* messages during execution. */
/* */
#undef FT_COMPONENT
#define FT_COMPONENT trace_t1parse
/*************************************************************************/
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** INPUT STREAM PARSER *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/*************************************************************************/
/* see Adobe Technical Note 5040.Download_Fonts.pdf */
static FT_Error
read_pfb_tag( FT_Stream stream,
FT_UShort *atag,
FT_ULong *asize )
{
FT_Error error;
FT_UShort tag;
FT_ULong size;
*atag = 0;
*asize = 0;
if ( !FT_READ_USHORT( tag ) )
{
if ( tag == 0x8001U || tag == 0x8002U )
{
if ( !FT_READ_ULONG_LE( size ) )
*asize = size;
}
*atag = tag;
}
return error;
}
static FT_Error
check_type1_format( FT_Stream stream,
const char* header_string,
size_t header_length )
{
FT_Error error;
FT_UShort tag;
FT_ULong dummy;
if ( FT_STREAM_SEEK( 0 ) )
goto Exit;
error = read_pfb_tag( stream, &tag, &dummy );
if ( error )
goto Exit;
/* We assume that the first segment in a PFB is always encoded as */
/* text. This might be wrong (and the specification doesn't insist */
/* on that), but we have never seen a counterexample. */
if ( tag != 0x8001U && FT_STREAM_SEEK( 0 ) )
goto Exit;
if ( !FT_FRAME_ENTER( header_length ) )
{
error = FT_Err_Ok;
if ( ft_memcmp( stream->cursor, header_string, header_length ) != 0 )
error = FT_THROW( Unknown_File_Format );
FT_FRAME_EXIT();
}
Exit:
return error;
}
FT_LOCAL_DEF( FT_Error )
T1_New_Parser( T1_Parser parser,
FT_Stream stream,
FT_Memory memory,
PSAux_Service psaux )
{
FT_Error error;
FT_UShort tag;
FT_ULong size;
psaux->ps_parser_funcs->init( &parser->root, 0, 0, memory );
parser->stream = stream;
parser->base_len = 0;
parser->base_dict = 0;
parser->private_len = 0;
parser->private_dict = 0;
parser->in_pfb = 0;
parser->in_memory = 0;
parser->single_block = 0;
/* check the header format */
error = check_type1_format( stream, "%!PS-AdobeFont", 14 );
if ( error )
{
if ( FT_ERR_NEQ( error, Unknown_File_Format ) )
goto Exit;
error = check_type1_format( stream, "%!FontType", 10 );
if ( error )
{
FT_TRACE2(( " not a Type 1 font\n" ));
goto Exit;
}
}
/******************************************************************/
/* */
/* Here a short summary of what is going on: */
/* */
/* When creating a new Type 1 parser, we try to locate and load */
/* the base dictionary if this is possible (i.e., for PFB */
/* files). Otherwise, we load the whole font into memory. */
/* */
/* When `loading' the base dictionary, we only setup pointers */
/* in the case of a memory-based stream. Otherwise, we */
/* allocate and load the base dictionary in it. */
/* */
/* parser->in_pfb is set if we are in a binary (`.pfb') font. */
/* parser->in_memory is set if we have a memory stream. */
/* */
/* try to compute the size of the base dictionary; */
/* look for a Postscript binary file tag, i.e., 0x8001 */
if ( FT_STREAM_SEEK( 0L ) )
goto Exit;
error = read_pfb_tag( stream, &tag, &size );
if ( error )
goto Exit;
if ( tag != 0x8001U )
{
/* assume that this is a PFA file for now; an error will */
/* be produced later when more things are checked */
if ( FT_STREAM_SEEK( 0L ) )
goto Exit;
size = stream->size;
}
else
parser->in_pfb = 1;
/* now, try to load `size' bytes of the `base' dictionary we */
/* found previously */
/* if it is a memory-based resource, set up pointers */
if ( !stream->read )
{
parser->base_dict = (FT_Byte*)stream->base + stream->pos;
parser->base_len = size;
parser->in_memory = 1;
/* check that the `size' field is valid */
if ( FT_STREAM_SKIP( size ) )
goto Exit;
}
else
{
/* read segment in memory -- this is clumsy, but so does the format */
if ( FT_ALLOC( parser->base_dict, size ) ||
FT_STREAM_READ( parser->base_dict, size ) )
goto Exit;
parser->base_len = size;
}
parser->root.base = parser->base_dict;
parser->root.cursor = parser->base_dict;
parser->root.limit = parser->root.cursor + parser->base_len;
Exit:
if ( error && !parser->in_memory )
FT_FREE( parser->base_dict );
return error;
}
FT_LOCAL_DEF( void )
T1_Finalize_Parser( T1_Parser parser )
{
FT_Memory memory = parser->root.memory;
/* always free the private dictionary */
FT_FREE( parser->private_dict );
/* free the base dictionary only when we have a disk stream */
if ( !parser->in_memory )
FT_FREE( parser->base_dict );
parser->root.funcs.done( &parser->root );
}
FT_LOCAL_DEF( FT_Error )
T1_Get_Private_Dict( T1_Parser parser,
PSAux_Service psaux )
{
FT_Stream stream = parser->stream;
FT_Memory memory = parser->root.memory;
FT_Error error = FT_Err_Ok;
FT_ULong size;
if ( parser->in_pfb )
{
/* in the case of the PFB format, the private dictionary can be */
/* made of several segments. We thus first read the number of */
/* segments to compute the total size of the private dictionary */
/* then re-read them into memory. */
FT_Long start_pos = FT_STREAM_POS();
FT_UShort tag;
parser->private_len = 0;
for (;;)
{
error = read_pfb_tag( stream, &tag, &size );
if ( error )
goto Fail;
if ( tag != 0x8002U )
break;
parser->private_len += size;
if ( FT_STREAM_SKIP( size ) )
goto Fail;
}
/* Check that we have a private dictionary there */
/* and allocate private dictionary buffer */
if ( parser->private_len == 0 )
{
FT_ERROR(( "T1_Get_Private_Dict:"
" invalid private dictionary section\n" ));
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
if ( FT_STREAM_SEEK( start_pos ) ||
FT_ALLOC( parser->private_dict, parser->private_len ) )
goto Fail;
parser->private_len = 0;
for (;;)
{
error = read_pfb_tag( stream, &tag, &size );
if ( error || tag != 0x8002U )
{
error = FT_Err_Ok;
break;
}
if ( FT_STREAM_READ( parser->private_dict + parser->private_len,
size ) )
goto Fail;
parser->private_len += size;
}
}
else
{
/* We have already `loaded' the whole PFA font file into memory; */
/* if this is a memory resource, allocate a new block to hold */
/* the private dict. Otherwise, simply overwrite into the base */
/* dictionary block in the heap. */
/* first of all, look at the `eexec' keyword */
FT_Byte* cur = parser->base_dict;
FT_Byte* limit = cur + parser->base_len;
FT_Byte c;
FT_Pointer pos_lf;
FT_Bool test_cr;
Again:
for (;;)
{
c = cur[0];
if ( c == 'e' && cur + 9 < limit ) /* 9 = 5 letters for `eexec' + */
/* whitespace + 4 chars */
{
if ( cur[1] == 'e' &&
cur[2] == 'x' &&
cur[3] == 'e' &&
cur[4] == 'c' )
break;
}
cur++;
if ( cur >= limit )
{
FT_ERROR(( "T1_Get_Private_Dict:"
" could not find `eexec' keyword\n" ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
}
/* check whether `eexec' was real -- it could be in a comment */
/* or string (as e.g. in u003043t.gsf from ghostscript) */
parser->root.cursor = parser->base_dict;
/* set limit to `eexec' + whitespace + 4 characters */
parser->root.limit = cur + 10;
cur = parser->root.cursor;
limit = parser->root.limit;
while ( cur < limit )
{
if ( *cur == 'e' && ft_strncmp( (char*)cur, "eexec", 5 ) == 0 )
goto Found;
T1_Skip_PS_Token( parser );
if ( parser->root.error )
break;
T1_Skip_Spaces ( parser );
cur = parser->root.cursor;
}
/* we haven't found the correct `eexec'; go back and continue */
/* searching */
cur = limit;
limit = parser->base_dict + parser->base_len;
goto Again;
/* now determine where to write the _encrypted_ binary private */
/* dictionary. We overwrite the base dictionary for disk-based */
/* resources and allocate a new block otherwise */
Found:
parser->root.limit = parser->base_dict + parser->base_len;
T1_Skip_PS_Token( parser );
cur = parser->root.cursor;
limit = parser->root.limit;
/* According to the Type 1 spec, the first cipher byte must not be */
/* an ASCII whitespace character code (blank, tab, carriage return */
/* or line feed). We have seen Type 1 fonts with two line feed */
/* characters... So skip now all whitespace character codes. */
/* */
/* On the other hand, Adobe's Type 1 parser handles fonts just */
/* fine that are violating this limitation, so we add a heuristic */
/* test to stop at \r only if it is not used for EOL. */
pos_lf = ft_memchr( cur, '\n', limit - cur );
test_cr = FT_BOOL( !pos_lf ||
pos_lf > ft_memchr( cur, '\r', limit - cur ) );
while ( cur < limit &&
( *cur == ' ' ||
*cur == '\t' ||
(test_cr && *cur == '\r' ) ||
*cur == '\n' ) )
++cur;
if ( cur >= limit )
{
FT_ERROR(( "T1_Get_Private_Dict:"
" `eexec' not properly terminated\n" ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
size = (FT_ULong)( parser->base_len - ( cur - parser->base_dict ) );
if ( parser->in_memory )
{
/* note that we allocate one more byte to put a terminating `0' */
if ( FT_ALLOC( parser->private_dict, size + 1 ) )
goto Fail;
parser->private_len = size;
}
else
{
parser->single_block = 1;
parser->private_dict = parser->base_dict;
parser->private_len = size;
parser->base_dict = 0;
parser->base_len = 0;
}
/* now determine whether the private dictionary is encoded in binary */
/* or hexadecimal ASCII format -- decode it accordingly */
/* we need to access the next 4 bytes (after the final whitespace */
/* following the `eexec' keyword); if they all are hexadecimal */
/* digits, then we have a case of ASCII storage */
if ( cur + 3 < limit &&
ft_isxdigit( cur[0] ) && ft_isxdigit( cur[1] ) &&
ft_isxdigit( cur[2] ) && ft_isxdigit( cur[3] ) )
{
/* ASCII hexadecimal encoding */
FT_Long len;
parser->root.cursor = cur;
(void)psaux->ps_parser_funcs->to_bytes( &parser->root,
parser->private_dict,
parser->private_len,
&len,
0 );
parser->private_len = len;
/* put a safeguard */
parser->private_dict[len] = '\0';
}
else
/* binary encoding -- copy the private dict */
FT_MEM_MOVE( parser->private_dict, cur, size );
}
/* we now decrypt the encoded binary private dictionary */
psaux->t1_decrypt( parser->private_dict, parser->private_len, 55665U );
if ( parser->private_len < 4 )
{
FT_ERROR(( "T1_Get_Private_Dict:"
" invalid private dictionary section\n" ));
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
/* replace the four random bytes at the beginning with whitespace */
parser->private_dict[0] = ' ';
parser->private_dict[1] = ' ';
parser->private_dict[2] = ' ';
parser->private_dict[3] = ' ';
parser->root.base = parser->private_dict;
parser->root.cursor = parser->private_dict;
parser->root.limit = parser->root.cursor + parser->private_len;
Fail:
Exit:
return error;
}
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/type1/t1parse.c | C | apache-2.0 | 17,322 |
/***************************************************************************/
/* */
/* t1parse.h */
/* */
/* Type 1 parser (specification). */
/* */
/* Copyright 1996-2001, 2002, 2003, 2008 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
#ifndef __T1PARSE_H__
#define __T1PARSE_H__
#include <ft2build.h>
#include FT_INTERNAL_TYPE1_TYPES_H
#include FT_INTERNAL_STREAM_H
FT_BEGIN_HEADER
/*************************************************************************/
/* */
/* <Struct> */
/* T1_ParserRec */
/* */
/* <Description> */
/* A PS_ParserRec is an object used to parse a Type 1 fonts very */
/* quickly. */
/* */
/* <Fields> */
/* root :: The root parser. */
/* */
/* stream :: The current input stream. */
/* */
/* base_dict :: A pointer to the top-level dictionary. */
/* */
/* base_len :: The length in bytes of the top dictionary. */
/* */
/* private_dict :: A pointer to the private dictionary. */
/* */
/* private_len :: The length in bytes of the private dictionary. */
/* */
/* in_pfb :: A boolean. Indicates that we are handling a PFB */
/* file. */
/* */
/* in_memory :: A boolean. Indicates a memory-based stream. */
/* */
/* single_block :: A boolean. Indicates that the private dictionary */
/* is stored in lieu of the base dictionary. */
/* */
typedef struct T1_ParserRec_
{
PS_ParserRec root;
FT_Stream stream;
FT_Byte* base_dict;
FT_ULong base_len;
FT_Byte* private_dict;
FT_ULong private_len;
FT_Bool in_pfb;
FT_Bool in_memory;
FT_Bool single_block;
} T1_ParserRec, *T1_Parser;
#define T1_Add_Table( p, i, o, l ) (p)->funcs.add( (p), i, o, l )
#define T1_Done_Table( p ) \
do \
{ \
if ( (p)->funcs.done ) \
(p)->funcs.done( p ); \
} while ( 0 )
#define T1_Release_Table( p ) \
do \
{ \
if ( (p)->funcs.release ) \
(p)->funcs.release( p ); \
} while ( 0 )
#define T1_Skip_Spaces( p ) (p)->root.funcs.skip_spaces( &(p)->root )
#define T1_Skip_PS_Token( p ) (p)->root.funcs.skip_PS_token( &(p)->root )
#define T1_ToInt( p ) (p)->root.funcs.to_int( &(p)->root )
#define T1_ToFixed( p, t ) (p)->root.funcs.to_fixed( &(p)->root, t )
#define T1_ToCoordArray( p, m, c ) \
(p)->root.funcs.to_coord_array( &(p)->root, m, c )
#define T1_ToFixedArray( p, m, f, t ) \
(p)->root.funcs.to_fixed_array( &(p)->root, m, f, t )
#define T1_ToToken( p, t ) \
(p)->root.funcs.to_token( &(p)->root, t )
#define T1_ToTokenArray( p, t, m, c ) \
(p)->root.funcs.to_token_array( &(p)->root, t, m, c )
#define T1_Load_Field( p, f, o, m, pf ) \
(p)->root.funcs.load_field( &(p)->root, f, o, m, pf )
#define T1_Load_Field_Table( p, f, o, m, pf ) \
(p)->root.funcs.load_field_table( &(p)->root, f, o, m, pf )
FT_LOCAL( FT_Error )
T1_New_Parser( T1_Parser parser,
FT_Stream stream,
FT_Memory memory,
PSAux_Service psaux );
FT_LOCAL( FT_Error )
T1_Get_Private_Dict( T1_Parser parser,
PSAux_Service psaux );
FT_LOCAL( void )
T1_Finalize_Parser( T1_Parser parser );
FT_END_HEADER
#endif /* __T1PARSE_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/type1/t1parse.h | C | apache-2.0 | 6,055 |
/***************************************************************************/
/* */
/* t1tokens.h */
/* */
/* Type 1 tokenizer (specification). */
/* */
/* Copyright 1996-2001, 2002, 2003, 2004, 2006, 2008, 2009 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
#undef FT_STRUCTURE
#define FT_STRUCTURE PS_FontInfoRec
#undef T1CODE
#define T1CODE T1_FIELD_LOCATION_FONT_INFO
T1_FIELD_STRING( "version", version,
T1_FIELD_DICT_FONTDICT )
T1_FIELD_STRING( "Notice", notice,
T1_FIELD_DICT_FONTDICT )
T1_FIELD_STRING( "FullName", full_name,
T1_FIELD_DICT_FONTDICT )
T1_FIELD_STRING( "FamilyName", family_name,
T1_FIELD_DICT_FONTDICT )
T1_FIELD_STRING( "Weight", weight,
T1_FIELD_DICT_FONTDICT )
/* we use pointers to detect modifications made by synthetic fonts */
T1_FIELD_NUM ( "ItalicAngle", italic_angle,
T1_FIELD_DICT_FONTDICT )
T1_FIELD_BOOL ( "isFixedPitch", is_fixed_pitch,
T1_FIELD_DICT_FONTDICT )
T1_FIELD_NUM ( "UnderlinePosition", underline_position,
T1_FIELD_DICT_FONTDICT )
T1_FIELD_NUM ( "UnderlineThickness", underline_thickness,
T1_FIELD_DICT_FONTDICT )
#undef FT_STRUCTURE
#define FT_STRUCTURE PS_FontExtraRec
#undef T1CODE
#define T1CODE T1_FIELD_LOCATION_FONT_EXTRA
T1_FIELD_NUM ( "FSType", fs_type,
T1_FIELD_DICT_FONTDICT )
#undef FT_STRUCTURE
#define FT_STRUCTURE PS_PrivateRec
#undef T1CODE
#define T1CODE T1_FIELD_LOCATION_PRIVATE
T1_FIELD_NUM ( "UniqueID", unique_id,
T1_FIELD_DICT_FONTDICT | T1_FIELD_DICT_PRIVATE )
T1_FIELD_NUM ( "lenIV", lenIV,
T1_FIELD_DICT_PRIVATE )
T1_FIELD_NUM ( "LanguageGroup", language_group,
T1_FIELD_DICT_PRIVATE )
T1_FIELD_NUM ( "password", password,
T1_FIELD_DICT_PRIVATE )
T1_FIELD_FIXED_1000( "BlueScale", blue_scale,
T1_FIELD_DICT_PRIVATE )
T1_FIELD_NUM ( "BlueShift", blue_shift,
T1_FIELD_DICT_PRIVATE )
T1_FIELD_NUM ( "BlueFuzz", blue_fuzz,
T1_FIELD_DICT_PRIVATE )
T1_FIELD_NUM_TABLE ( "BlueValues", blue_values, 14,
T1_FIELD_DICT_PRIVATE )
T1_FIELD_NUM_TABLE ( "OtherBlues", other_blues, 10,
T1_FIELD_DICT_PRIVATE )
T1_FIELD_NUM_TABLE ( "FamilyBlues", family_blues, 14,
T1_FIELD_DICT_PRIVATE )
T1_FIELD_NUM_TABLE ( "FamilyOtherBlues", family_other_blues, 10,
T1_FIELD_DICT_PRIVATE )
T1_FIELD_NUM_TABLE2( "StdHW", standard_width, 1,
T1_FIELD_DICT_PRIVATE )
T1_FIELD_NUM_TABLE2( "StdVW", standard_height, 1,
T1_FIELD_DICT_PRIVATE )
T1_FIELD_NUM_TABLE2( "MinFeature", min_feature, 2,
T1_FIELD_DICT_PRIVATE )
T1_FIELD_NUM_TABLE ( "StemSnapH", snap_widths, 12,
T1_FIELD_DICT_PRIVATE )
T1_FIELD_NUM_TABLE ( "StemSnapV", snap_heights, 12,
T1_FIELD_DICT_PRIVATE )
T1_FIELD_FIXED ( "ExpansionFactor", expansion_factor,
T1_FIELD_DICT_PRIVATE )
T1_FIELD_BOOL ( "ForceBold", force_bold,
T1_FIELD_DICT_PRIVATE )
#undef FT_STRUCTURE
#define FT_STRUCTURE T1_FontRec
#undef T1CODE
#define T1CODE T1_FIELD_LOCATION_FONT_DICT
T1_FIELD_KEY ( "FontName", font_name, T1_FIELD_DICT_FONTDICT )
T1_FIELD_NUM ( "PaintType", paint_type, T1_FIELD_DICT_FONTDICT )
T1_FIELD_NUM ( "FontType", font_type, T1_FIELD_DICT_FONTDICT )
T1_FIELD_FIXED( "StrokeWidth", stroke_width, T1_FIELD_DICT_FONTDICT )
#undef FT_STRUCTURE
#define FT_STRUCTURE FT_BBox
#undef T1CODE
#define T1CODE T1_FIELD_LOCATION_BBOX
T1_FIELD_BBOX( "FontBBox", xMin, T1_FIELD_DICT_FONTDICT )
#ifndef T1_CONFIG_OPTION_NO_MM_SUPPORT
#undef FT_STRUCTURE
#define FT_STRUCTURE T1_FaceRec
#undef T1CODE
#define T1CODE T1_FIELD_LOCATION_FACE
T1_FIELD_NUM( "NDV", ndv_idx, T1_FIELD_DICT_PRIVATE )
T1_FIELD_NUM( "CDV", cdv_idx, T1_FIELD_DICT_PRIVATE )
#undef FT_STRUCTURE
#define FT_STRUCTURE PS_BlendRec
#undef T1CODE
#define T1CODE T1_FIELD_LOCATION_BLEND
T1_FIELD_NUM_TABLE( "DesignVector", default_design_vector,
T1_MAX_MM_DESIGNS, T1_FIELD_DICT_FONTDICT )
#endif /* T1_CONFIG_OPTION_NO_MM_SUPPORT */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/type1/t1tokens.h | C | apache-2.0 | 5,795 |
/***************************************************************************/
/* */
/* type1.c */
/* */
/* FreeType Type 1 driver component (body only). */
/* */
/* Copyright 1996-2001 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
#define FT_MAKE_OPTION_SINGLE_OBJECT
#include <ft2build.h>
#include "t1parse.c"
#include "t1load.c"
#include "t1objs.c"
#include "t1driver.c"
#include "t1gload.c"
#ifndef T1_CONFIG_OPTION_NO_AFM
#include "t1afm.c"
#endif
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/type1/type1.c | C | apache-2.0 | 1,485 |
#
# FreeType 2 Type42 module definition
#
# Copyright 2002, 2006 by
# David Turner, Robert Wilhelm, and Werner Lemberg.
#
# This file is part of the FreeType project, and may only be used, modified,
# and distributed under the terms of the FreeType project license,
# LICENSE.TXT. By continuing to use, modify, or distribute this file you
# indicate that you have read the license and understand and accept it
# fully.
FTMODULE_H_COMMANDS += TYPE42_DRIVER
define TYPE42_DRIVER
$(OPEN_DRIVER) FT_Driver_ClassRec, t42_driver_class $(CLOSE_DRIVER)
$(ECHO_DRIVER)type42 $(ECHO_DRIVER_DESC)Type 42 font files with no known extension$(ECHO_DRIVER_DONE)
endef
# EOF
| YifuLiu/AliOS-Things | components/freetype/src/type42/module.mk | Makefile | apache-2.0 | 669 |
#
# FreeType 2 Type42 driver configuration rules
#
# Copyright 2002, 2003, 2008 by
# David Turner, Robert Wilhelm, and Werner Lemberg.
#
# This file is part of the FreeType project, and may only be used, modified,
# and distributed under the terms of the FreeType project license,
# LICENSE.TXT. By continuing to use, modify, or distribute this file you
# indicate that you have read the license and understand and accept it
# fully.
# Type42 driver directory
#
T42_DIR := $(SRC_DIR)/type42
# compilation flags for the driver
#
T42_COMPILE := $(FT_COMPILE) $I$(subst /,$(COMPILER_SEP),$(T42_DIR))
# Type42 driver source
#
T42_DRV_SRC := $(T42_DIR)/t42objs.c \
$(T42_DIR)/t42parse.c \
$(T42_DIR)/t42drivr.c
# Type42 driver headers
#
T42_DRV_H := $(T42_DRV_SRC:%.c=%.h) \
$(T42_DIR)/t42error.h \
$(T42_DIR)/t42types.h
# Type42 driver object(s)
#
# T42_DRV_OBJ_M is used during `multi' builds
# T42_DRV_OBJ_S is used during `single' builds
#
T42_DRV_OBJ_M := $(T42_DRV_SRC:$(T42_DIR)/%.c=$(OBJ_DIR)/%.$O)
T42_DRV_OBJ_S := $(OBJ_DIR)/type42.$O
# Type42 driver source file for single build
#
T42_DRV_SRC_S := $(T42_DIR)/type42.c
# Type42 driver - single object
#
$(T42_DRV_OBJ_S): $(T42_DRV_SRC_S) $(T42_DRV_SRC) $(FREETYPE_H) $(T42_DRV_H)
$(T42_COMPILE) $T$(subst /,$(COMPILER_SEP),$@ $(T42_DRV_SRC_S))
# Type42 driver - multiple objects
#
$(OBJ_DIR)/%.$O: $(T42_DIR)/%.c $(FREETYPE_H) $(T42_DRV_H)
$(T42_COMPILE) $T$(subst /,$(COMPILER_SEP),$@ $<)
# update main driver object lists
#
DRV_OBJS_S += $(T42_DRV_OBJ_S)
DRV_OBJS_M += $(T42_DRV_OBJ_M)
# EOF
| YifuLiu/AliOS-Things | components/freetype/src/type42/rules.mk | Makefile | apache-2.0 | 1,634 |
/***************************************************************************/
/* */
/* t42drivr.c */
/* */
/* High-level Type 42 driver interface (body). */
/* */
/* Copyright 2002-2004, 2006, 2007, 2009, 2011, 2013 by */
/* Roberto Alameda. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
/*************************************************************************/
/* */
/* This driver implements Type42 fonts as described in the */
/* Technical Note #5012 from Adobe, with these limitations: */
/* */
/* 1) CID Fonts are not currently supported. */
/* 2) Incremental fonts making use of the GlyphDirectory keyword */
/* will be loaded, but the rendering will be using the TrueType */
/* tables. */
/* 3) As for Type1 fonts, CDevProc is not supported. */
/* 4) The Metrics dictionary is not supported. */
/* 5) AFM metrics are not supported. */
/* */
/* In other words, this driver supports Type42 fonts derived from */
/* TrueType fonts in a non-CID manner, as done by usual conversion */
/* programs. */
/* */
/*************************************************************************/
#include "t42drivr.h"
#include "t42objs.h"
#include "t42error.h"
#include FT_INTERNAL_DEBUG_H
#include FT_SERVICE_XFREE86_NAME_H
#include FT_SERVICE_GLYPH_DICT_H
#include FT_SERVICE_POSTSCRIPT_NAME_H
#include FT_SERVICE_POSTSCRIPT_INFO_H
#undef FT_COMPONENT
#define FT_COMPONENT trace_t42
/*
*
* GLYPH DICT SERVICE
*
*/
static FT_Error
t42_get_glyph_name( T42_Face face,
FT_UInt glyph_index,
FT_Pointer buffer,
FT_UInt buffer_max )
{
FT_STRCPYN( buffer, face->type1.glyph_names[glyph_index], buffer_max );
return FT_Err_Ok;
}
static FT_UInt
t42_get_name_index( T42_Face face,
FT_String* glyph_name )
{
FT_Int i;
for ( i = 0; i < face->type1.num_glyphs; i++ )
{
FT_String* gname = face->type1.glyph_names[i];
if ( glyph_name[0] == gname[0] && !ft_strcmp( glyph_name, gname ) )
return (FT_UInt)ft_atol( (const char *)face->type1.charstrings[i] );
}
return 0;
}
static const FT_Service_GlyphDictRec t42_service_glyph_dict =
{
(FT_GlyphDict_GetNameFunc) t42_get_glyph_name,
(FT_GlyphDict_NameIndexFunc)t42_get_name_index
};
/*
*
* POSTSCRIPT NAME SERVICE
*
*/
static const char*
t42_get_ps_font_name( T42_Face face )
{
return (const char*)face->type1.font_name;
}
static const FT_Service_PsFontNameRec t42_service_ps_font_name =
{
(FT_PsName_GetFunc)t42_get_ps_font_name
};
/*
*
* POSTSCRIPT INFO SERVICE
*
*/
static FT_Error
t42_ps_get_font_info( FT_Face face,
PS_FontInfoRec* afont_info )
{
*afont_info = ((T42_Face)face)->type1.font_info;
return FT_Err_Ok;
}
static FT_Error
t42_ps_get_font_extra( FT_Face face,
PS_FontExtraRec* afont_extra )
{
*afont_extra = ((T42_Face)face)->type1.font_extra;
return FT_Err_Ok;
}
static FT_Int
t42_ps_has_glyph_names( FT_Face face )
{
FT_UNUSED( face );
return 1;
}
static FT_Error
t42_ps_get_font_private( FT_Face face,
PS_PrivateRec* afont_private )
{
*afont_private = ((T42_Face)face)->type1.private_dict;
return FT_Err_Ok;
}
static const FT_Service_PsInfoRec t42_service_ps_info =
{
(PS_GetFontInfoFunc) t42_ps_get_font_info,
(PS_GetFontExtraFunc) t42_ps_get_font_extra,
(PS_HasGlyphNamesFunc) t42_ps_has_glyph_names,
(PS_GetFontPrivateFunc)t42_ps_get_font_private,
(PS_GetFontValueFunc) NULL /* not implemented */
};
/*
*
* SERVICE LIST
*
*/
static const FT_ServiceDescRec t42_services[] =
{
{ FT_SERVICE_ID_GLYPH_DICT, &t42_service_glyph_dict },
{ FT_SERVICE_ID_POSTSCRIPT_FONT_NAME, &t42_service_ps_font_name },
{ FT_SERVICE_ID_POSTSCRIPT_INFO, &t42_service_ps_info },
{ FT_SERVICE_ID_XF86_NAME, FT_XF86_FORMAT_TYPE_42 },
{ NULL, NULL }
};
FT_CALLBACK_DEF( FT_Module_Interface )
T42_Get_Interface( FT_Module module,
const FT_String* t42_interface )
{
FT_UNUSED( module );
return ft_service_list_lookup( t42_services, t42_interface );
}
const FT_Driver_ClassRec t42_driver_class =
{
{
FT_MODULE_FONT_DRIVER |
FT_MODULE_DRIVER_SCALABLE |
#ifdef TT_USE_BYTECODE_INTERPRETER
FT_MODULE_DRIVER_HAS_HINTER,
#else
0,
#endif
sizeof ( T42_DriverRec ),
"type42",
0x10000L,
0x20000L,
0, /* format interface */
T42_Driver_Init,
T42_Driver_Done,
T42_Get_Interface,
},
sizeof ( T42_FaceRec ),
sizeof ( T42_SizeRec ),
sizeof ( T42_GlyphSlotRec ),
T42_Face_Init,
T42_Face_Done,
T42_Size_Init,
T42_Size_Done,
T42_GlyphSlot_Init,
T42_GlyphSlot_Done,
T42_GlyphSlot_Load,
0, /* FT_Face_GetKerningFunc */
0, /* FT_Face_AttachFunc */
0, /* FT_Face_GetAdvancesFunc */
T42_Size_Request,
T42_Size_Select
};
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/type42/t42drivr.c | C | apache-2.0 | 6,840 |
/***************************************************************************/
/* */
/* t42drivr.h */
/* */
/* High-level Type 42 driver interface (specification). */
/* */
/* Copyright 2002 by Roberto Alameda. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
#ifndef __T42DRIVR_H__
#define __T42DRIVR_H__
#include <ft2build.h>
#include FT_INTERNAL_DRIVER_H
FT_BEGIN_HEADER
#ifdef FT_CONFIG_OPTION_PIC
#error "this module does not support PIC yet"
#endif
FT_EXPORT_VAR( const FT_Driver_ClassRec ) t42_driver_class;
FT_END_HEADER
#endif /* __T42DRIVR_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/type42/t42drivr.h | C | apache-2.0 | 1,495 |
/***************************************************************************/
/* */
/* t42error.h */
/* */
/* Type 42 error codes (specification only). */
/* */
/* Copyright 2002, 2003, 2012 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
/*************************************************************************/
/* */
/* This file is used to define the Type 42 error enumeration constants. */
/* */
/*************************************************************************/
#ifndef __T42ERROR_H__
#define __T42ERROR_H__
#include FT_MODULE_ERRORS_H
#undef __FTERRORS_H__
#undef FT_ERR_PREFIX
#define FT_ERR_PREFIX T42_Err_
#define FT_ERR_BASE FT_Mod_Err_Type42
#include FT_ERRORS_H
#endif /* __T42ERROR_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/type42/t42error.h | C | apache-2.0 | 1,898 |
/***************************************************************************/
/* */
/* t42objs.c */
/* */
/* Type 42 objects manager (body). */
/* */
/* Copyright 2002-2009, 2011, 2013 */
/* by Roberto Alameda. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
#include "t42objs.h"
#include "t42parse.h"
#include "t42error.h"
#include FT_INTERNAL_DEBUG_H
#include FT_LIST_H
#include FT_TRUETYPE_IDS_H
#undef FT_COMPONENT
#define FT_COMPONENT trace_t42
static FT_Error
T42_Open_Face( T42_Face face )
{
T42_LoaderRec loader;
T42_Parser parser;
T1_Font type1 = &face->type1;
FT_Memory memory = face->root.memory;
FT_Error error;
PSAux_Service psaux = (PSAux_Service)face->psaux;
t42_loader_init( &loader, face );
parser = &loader.parser;
if ( FT_ALLOC( face->ttf_data, 12 ) )
goto Exit;
error = t42_parser_init( parser,
face->root.stream,
memory,
psaux);
if ( error )
goto Exit;
error = t42_parse_dict( face, &loader,
parser->base_dict, parser->base_len );
if ( error )
goto Exit;
if ( type1->font_type != 42 )
{
FT_ERROR(( "T42_Open_Face: cannot handle FontType %d\n",
type1->font_type ));
error = FT_THROW( Unknown_File_Format );
goto Exit;
}
/* now, propagate the charstrings and glyphnames tables */
/* to the Type1 data */
type1->num_glyphs = loader.num_glyphs;
if ( !loader.charstrings.init )
{
FT_ERROR(( "T42_Open_Face: no charstrings array in face\n" ));
error = FT_THROW( Invalid_File_Format );
}
loader.charstrings.init = 0;
type1->charstrings_block = loader.charstrings.block;
type1->charstrings = loader.charstrings.elements;
type1->charstrings_len = loader.charstrings.lengths;
/* we copy the glyph names `block' and `elements' fields; */
/* the `lengths' field must be released later */
type1->glyph_names_block = loader.glyph_names.block;
type1->glyph_names = (FT_String**)loader.glyph_names.elements;
loader.glyph_names.block = 0;
loader.glyph_names.elements = 0;
/* we must now build type1.encoding when we have a custom array */
if ( type1->encoding_type == T1_ENCODING_TYPE_ARRAY )
{
FT_Int charcode, idx, min_char, max_char;
FT_Byte* glyph_name;
/* OK, we do the following: for each element in the encoding */
/* table, look up the index of the glyph having the same name */
/* as defined in the CharStrings array. */
/* The index is then stored in type1.encoding.char_index, and */
/* the name in type1.encoding.char_name */
min_char = 0;
max_char = 0;
charcode = 0;
for ( ; charcode < loader.encoding_table.max_elems; charcode++ )
{
FT_Byte* char_name;
type1->encoding.char_index[charcode] = 0;
type1->encoding.char_name [charcode] = (char *)".notdef";
char_name = loader.encoding_table.elements[charcode];
if ( char_name )
for ( idx = 0; idx < type1->num_glyphs; idx++ )
{
glyph_name = (FT_Byte*)type1->glyph_names[idx];
if ( ft_strcmp( (const char*)char_name,
(const char*)glyph_name ) == 0 )
{
type1->encoding.char_index[charcode] = (FT_UShort)idx;
type1->encoding.char_name [charcode] = (char*)glyph_name;
/* Change min/max encoded char only if glyph name is */
/* not /.notdef */
if ( ft_strcmp( (const char*)".notdef",
(const char*)glyph_name ) != 0 )
{
if ( charcode < min_char )
min_char = charcode;
if ( charcode >= max_char )
max_char = charcode + 1;
}
break;
}
}
}
type1->encoding.code_first = min_char;
type1->encoding.code_last = max_char;
type1->encoding.num_chars = loader.num_chars;
}
Exit:
t42_loader_done( &loader );
return error;
}
/***************** Driver Functions *************/
FT_LOCAL_DEF( FT_Error )
T42_Face_Init( FT_Stream stream,
FT_Face t42face, /* T42_Face */
FT_Int face_index,
FT_Int num_params,
FT_Parameter* params )
{
T42_Face face = (T42_Face)t42face;
FT_Error error;
FT_Service_PsCMaps psnames;
PSAux_Service psaux;
FT_Face root = (FT_Face)&face->root;
T1_Font type1 = &face->type1;
PS_FontInfo info = &type1->font_info;
FT_UNUSED( num_params );
FT_UNUSED( params );
FT_UNUSED( stream );
face->ttf_face = NULL;
face->root.num_faces = 1;
FT_FACE_FIND_GLOBAL_SERVICE( face, psnames, POSTSCRIPT_CMAPS );
face->psnames = psnames;
face->psaux = FT_Get_Module_Interface( FT_FACE_LIBRARY( face ),
"psaux" );
psaux = (PSAux_Service)face->psaux;
if ( !psaux )
{
FT_ERROR(( "T42_Face_Init: cannot access `psaux' module\n" ));
error = FT_THROW( Missing_Module );
goto Exit;
}
FT_TRACE2(( "Type 42 driver\n" ));
/* open the tokenizer, this will also check the font format */
error = T42_Open_Face( face );
if ( error )
goto Exit;
/* if we just wanted to check the format, leave successfully now */
if ( face_index < 0 )
goto Exit;
/* check the face index */
if ( face_index > 0 )
{
FT_ERROR(( "T42_Face_Init: invalid face index\n" ));
error = FT_THROW( Invalid_Argument );
goto Exit;
}
/* Now load the font program into the face object */
/* Init the face object fields */
/* Now set up root face fields */
root->num_glyphs = type1->num_glyphs;
root->num_charmaps = 0;
root->face_index = 0;
root->face_flags |= FT_FACE_FLAG_SCALABLE |
FT_FACE_FLAG_HORIZONTAL |
FT_FACE_FLAG_GLYPH_NAMES;
if ( info->is_fixed_pitch )
root->face_flags |= FT_FACE_FLAG_FIXED_WIDTH;
/* We only set this flag if we have the patented bytecode interpreter. */
/* There are no known `tricky' Type42 fonts that could be loaded with */
/* the unpatented interpreter. */
#ifdef TT_CONFIG_OPTION_BYTECODE_INTERPRETER
root->face_flags |= FT_FACE_FLAG_HINTER;
#endif
/* XXX: TODO -- add kerning with .afm support */
/* get style name -- be careful, some broken fonts only */
/* have a `/FontName' dictionary entry! */
root->family_name = info->family_name;
/* assume "Regular" style if we don't know better */
root->style_name = (char *)"Regular";
if ( root->family_name )
{
char* full = info->full_name;
char* family = root->family_name;
if ( full )
{
while ( *full )
{
if ( *full == *family )
{
family++;
full++;
}
else
{
if ( *full == ' ' || *full == '-' )
full++;
else if ( *family == ' ' || *family == '-' )
family++;
else
{
if ( !*family )
root->style_name = full;
break;
}
}
}
}
}
else
{
/* do we have a `/FontName'? */
if ( type1->font_name )
root->family_name = type1->font_name;
}
/* no embedded bitmap support */
root->num_fixed_sizes = 0;
root->available_sizes = 0;
/* Load the TTF font embedded in the T42 font */
{
FT_Open_Args args;
args.flags = FT_OPEN_MEMORY;
args.memory_base = face->ttf_data;
args.memory_size = face->ttf_size;
if ( num_params )
{
args.flags |= FT_OPEN_PARAMS;
args.num_params = num_params;
args.params = params;
}
error = FT_Open_Face( FT_FACE_LIBRARY( face ),
&args, 0, &face->ttf_face );
}
if ( error )
goto Exit;
FT_Done_Size( face->ttf_face->size );
/* Ignore info in FontInfo dictionary and use the info from the */
/* loaded TTF font. The PostScript interpreter also ignores it. */
root->bbox = face->ttf_face->bbox;
root->units_per_EM = face->ttf_face->units_per_EM;
root->ascender = face->ttf_face->ascender;
root->descender = face->ttf_face->descender;
root->height = face->ttf_face->height;
root->max_advance_width = face->ttf_face->max_advance_width;
root->max_advance_height = face->ttf_face->max_advance_height;
root->underline_position = (FT_Short)info->underline_position;
root->underline_thickness = (FT_Short)info->underline_thickness;
/* compute style flags */
root->style_flags = 0;
if ( info->italic_angle )
root->style_flags |= FT_STYLE_FLAG_ITALIC;
if ( face->ttf_face->style_flags & FT_STYLE_FLAG_BOLD )
root->style_flags |= FT_STYLE_FLAG_BOLD;
if ( face->ttf_face->face_flags & FT_FACE_FLAG_VERTICAL )
root->face_flags |= FT_FACE_FLAG_VERTICAL;
{
if ( psnames )
{
FT_CharMapRec charmap;
T1_CMap_Classes cmap_classes = psaux->t1_cmap_classes;
FT_CMap_Class clazz;
charmap.face = root;
/* first of all, try to synthesize a Unicode charmap */
charmap.platform_id = TT_PLATFORM_MICROSOFT;
charmap.encoding_id = TT_MS_ID_UNICODE_CS;
charmap.encoding = FT_ENCODING_UNICODE;
error = FT_CMap_New( cmap_classes->unicode, NULL, &charmap, NULL );
if ( error &&
FT_ERR_NEQ( error, No_Unicode_Glyph_Name ) )
goto Exit;
error = FT_Err_Ok;
/* now, generate an Adobe Standard encoding when appropriate */
charmap.platform_id = TT_PLATFORM_ADOBE;
clazz = NULL;
switch ( type1->encoding_type )
{
case T1_ENCODING_TYPE_STANDARD:
charmap.encoding = FT_ENCODING_ADOBE_STANDARD;
charmap.encoding_id = TT_ADOBE_ID_STANDARD;
clazz = cmap_classes->standard;
break;
case T1_ENCODING_TYPE_EXPERT:
charmap.encoding = FT_ENCODING_ADOBE_EXPERT;
charmap.encoding_id = TT_ADOBE_ID_EXPERT;
clazz = cmap_classes->expert;
break;
case T1_ENCODING_TYPE_ARRAY:
charmap.encoding = FT_ENCODING_ADOBE_CUSTOM;
charmap.encoding_id = TT_ADOBE_ID_CUSTOM;
clazz = cmap_classes->custom;
break;
case T1_ENCODING_TYPE_ISOLATIN1:
charmap.encoding = FT_ENCODING_ADOBE_LATIN_1;
charmap.encoding_id = TT_ADOBE_ID_LATIN_1;
clazz = cmap_classes->unicode;
break;
default:
;
}
if ( clazz )
error = FT_CMap_New( clazz, NULL, &charmap, NULL );
#if 0
/* Select default charmap */
if ( root->num_charmaps )
root->charmap = root->charmaps[0];
#endif
}
}
Exit:
return error;
}
FT_LOCAL_DEF( void )
T42_Face_Done( FT_Face t42face )
{
T42_Face face = (T42_Face)t42face;
T1_Font type1;
PS_FontInfo info;
FT_Memory memory;
if ( !face )
return;
type1 = &face->type1;
info = &type1->font_info;
memory = face->root.memory;
/* delete internal ttf face prior to freeing face->ttf_data */
if ( face->ttf_face )
FT_Done_Face( face->ttf_face );
/* release font info strings */
FT_FREE( info->version );
FT_FREE( info->notice );
FT_FREE( info->full_name );
FT_FREE( info->family_name );
FT_FREE( info->weight );
/* release top dictionary */
FT_FREE( type1->charstrings_len );
FT_FREE( type1->charstrings );
FT_FREE( type1->glyph_names );
FT_FREE( type1->charstrings_block );
FT_FREE( type1->glyph_names_block );
FT_FREE( type1->encoding.char_index );
FT_FREE( type1->encoding.char_name );
FT_FREE( type1->font_name );
FT_FREE( face->ttf_data );
#if 0
/* release afm data if present */
if ( face->afm_data )
T1_Done_AFM( memory, (T1_AFM*)face->afm_data );
#endif
/* release unicode map, if any */
FT_FREE( face->unicode_map.maps );
face->unicode_map.num_maps = 0;
face->root.family_name = 0;
face->root.style_name = 0;
}
/*************************************************************************/
/* */
/* <Function> */
/* T42_Driver_Init */
/* */
/* <Description> */
/* Initializes a given Type 42 driver object. */
/* */
/* <Input> */
/* driver :: A handle to the target driver object. */
/* */
/* <Return> */
/* FreeType error code. 0 means success. */
/* */
FT_LOCAL_DEF( FT_Error )
T42_Driver_Init( FT_Module module ) /* T42_Driver */
{
T42_Driver driver = (T42_Driver)module;
FT_Module ttmodule;
ttmodule = FT_Get_Module( module->library, "truetype" );
if ( !ttmodule )
{
FT_ERROR(( "T42_Driver_Init: cannot access `truetype' module\n" ));
return FT_THROW( Missing_Module );
}
driver->ttclazz = (FT_Driver_Class)ttmodule->clazz;
return FT_Err_Ok;
}
FT_LOCAL_DEF( void )
T42_Driver_Done( FT_Module module )
{
FT_UNUSED( module );
}
FT_LOCAL_DEF( FT_Error )
T42_Size_Init( FT_Size size ) /* T42_Size */
{
T42_Size t42size = (T42_Size)size;
FT_Face face = size->face;
T42_Face t42face = (T42_Face)face;
FT_Size ttsize;
FT_Error error;
error = FT_New_Size( t42face->ttf_face, &ttsize );
t42size->ttsize = ttsize;
FT_Activate_Size( ttsize );
return error;
}
FT_LOCAL_DEF( FT_Error )
T42_Size_Request( FT_Size t42size, /* T42_Size */
FT_Size_Request req )
{
T42_Size size = (T42_Size)t42size;
T42_Face face = (T42_Face)t42size->face;
FT_Error error;
FT_Activate_Size( size->ttsize );
error = FT_Request_Size( face->ttf_face, req );
if ( !error )
t42size->metrics = face->ttf_face->size->metrics;
return error;
}
FT_LOCAL_DEF( FT_Error )
T42_Size_Select( FT_Size t42size, /* T42_Size */
FT_ULong strike_index )
{
T42_Size size = (T42_Size)t42size;
T42_Face face = (T42_Face)t42size->face;
FT_Error error;
FT_Activate_Size( size->ttsize );
error = FT_Select_Size( face->ttf_face, (FT_Int)strike_index );
if ( !error )
t42size->metrics = face->ttf_face->size->metrics;
return error;
}
FT_LOCAL_DEF( void )
T42_Size_Done( FT_Size t42size ) /* T42_Size */
{
T42_Size size = (T42_Size)t42size;
FT_Face face = t42size->face;
T42_Face t42face = (T42_Face)face;
FT_ListNode node;
node = FT_List_Find( &t42face->ttf_face->sizes_list, size->ttsize );
if ( node )
{
FT_Done_Size( size->ttsize );
size->ttsize = NULL;
}
}
FT_LOCAL_DEF( FT_Error )
T42_GlyphSlot_Init( FT_GlyphSlot t42slot ) /* T42_GlyphSlot */
{
T42_GlyphSlot slot = (T42_GlyphSlot)t42slot;
FT_Face face = t42slot->face;
T42_Face t42face = (T42_Face)face;
FT_GlyphSlot ttslot;
FT_Error error = FT_Err_Ok;
if ( face->glyph == NULL )
{
/* First glyph slot for this face */
slot->ttslot = t42face->ttf_face->glyph;
}
else
{
error = FT_New_GlyphSlot( t42face->ttf_face, &ttslot );
slot->ttslot = ttslot;
}
return error;
}
FT_LOCAL_DEF( void )
T42_GlyphSlot_Done( FT_GlyphSlot t42slot ) /* T42_GlyphSlot */
{
T42_GlyphSlot slot = (T42_GlyphSlot)t42slot;
FT_Done_GlyphSlot( slot->ttslot );
}
static void
t42_glyphslot_clear( FT_GlyphSlot slot )
{
/* free bitmap if needed */
ft_glyphslot_free_bitmap( slot );
/* clear all public fields in the glyph slot */
FT_ZERO( &slot->metrics );
FT_ZERO( &slot->outline );
FT_ZERO( &slot->bitmap );
slot->bitmap_left = 0;
slot->bitmap_top = 0;
slot->num_subglyphs = 0;
slot->subglyphs = 0;
slot->control_data = 0;
slot->control_len = 0;
slot->other = 0;
slot->format = FT_GLYPH_FORMAT_NONE;
slot->linearHoriAdvance = 0;
slot->linearVertAdvance = 0;
}
FT_LOCAL_DEF( FT_Error )
T42_GlyphSlot_Load( FT_GlyphSlot glyph,
FT_Size size,
FT_UInt glyph_index,
FT_Int32 load_flags )
{
FT_Error error;
T42_GlyphSlot t42slot = (T42_GlyphSlot)glyph;
T42_Size t42size = (T42_Size)size;
FT_Driver_Class ttclazz = ((T42_Driver)glyph->face->driver)->ttclazz;
FT_TRACE1(( "T42_GlyphSlot_Load: glyph index %d\n", glyph_index ));
t42_glyphslot_clear( t42slot->ttslot );
error = ttclazz->load_glyph( t42slot->ttslot,
t42size->ttsize,
glyph_index,
load_flags | FT_LOAD_NO_BITMAP );
if ( !error )
{
glyph->metrics = t42slot->ttslot->metrics;
glyph->linearHoriAdvance = t42slot->ttslot->linearHoriAdvance;
glyph->linearVertAdvance = t42slot->ttslot->linearVertAdvance;
glyph->format = t42slot->ttslot->format;
glyph->outline = t42slot->ttslot->outline;
glyph->bitmap = t42slot->ttslot->bitmap;
glyph->bitmap_left = t42slot->ttslot->bitmap_left;
glyph->bitmap_top = t42slot->ttslot->bitmap_top;
glyph->num_subglyphs = t42slot->ttslot->num_subglyphs;
glyph->subglyphs = t42slot->ttslot->subglyphs;
glyph->control_data = t42slot->ttslot->control_data;
glyph->control_len = t42slot->ttslot->control_len;
}
return error;
}
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/type42/t42objs.c | C | apache-2.0 | 20,228 |
/***************************************************************************/
/* */
/* t42objs.h */
/* */
/* Type 42 objects manager (specification). */
/* */
/* Copyright 2002, 2003, 2006, 2007, 2011 by Roberto Alameda. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
#ifndef __T42OBJS_H__
#define __T42OBJS_H__
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_TYPE1_TABLES_H
#include FT_INTERNAL_TYPE1_TYPES_H
#include "t42types.h"
#include FT_INTERNAL_OBJECTS_H
#include FT_INTERNAL_DRIVER_H
#include FT_SERVICE_POSTSCRIPT_CMAPS_H
#include FT_INTERNAL_POSTSCRIPT_HINTS_H
FT_BEGIN_HEADER
/* Type42 size */
typedef struct T42_SizeRec_
{
FT_SizeRec root;
FT_Size ttsize;
} T42_SizeRec, *T42_Size;
/* Type42 slot */
typedef struct T42_GlyphSlotRec_
{
FT_GlyphSlotRec root;
FT_GlyphSlot ttslot;
} T42_GlyphSlotRec, *T42_GlyphSlot;
/* Type 42 driver */
typedef struct T42_DriverRec_
{
FT_DriverRec root;
FT_Driver_Class ttclazz;
void* extension_component;
} T42_DriverRec, *T42_Driver;
/* */
FT_LOCAL( FT_Error )
T42_Face_Init( FT_Stream stream,
FT_Face face,
FT_Int face_index,
FT_Int num_params,
FT_Parameter* params );
FT_LOCAL( void )
T42_Face_Done( FT_Face face );
FT_LOCAL( FT_Error )
T42_Size_Init( FT_Size size );
FT_LOCAL( FT_Error )
T42_Size_Request( FT_Size size,
FT_Size_Request req );
FT_LOCAL( FT_Error )
T42_Size_Select( FT_Size size,
FT_ULong strike_index );
FT_LOCAL( void )
T42_Size_Done( FT_Size size );
FT_LOCAL( FT_Error )
T42_GlyphSlot_Init( FT_GlyphSlot slot );
FT_LOCAL( FT_Error )
T42_GlyphSlot_Load( FT_GlyphSlot glyph,
FT_Size size,
FT_UInt glyph_index,
FT_Int32 load_flags );
FT_LOCAL( void )
T42_GlyphSlot_Done( FT_GlyphSlot slot );
FT_LOCAL( FT_Error )
T42_Driver_Init( FT_Module module );
FT_LOCAL( void )
T42_Driver_Done( FT_Module module );
/* */
FT_END_HEADER
#endif /* __T42OBJS_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/type42/t42objs.h | C | apache-2.0 | 3,147 |
/***************************************************************************/
/* */
/* t42parse.c */
/* */
/* Type 42 font parser (body). */
/* */
/* Copyright 2002-2014 by */
/* Roberto Alameda. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
#include "t42parse.h"
#include "t42error.h"
#include FT_INTERNAL_DEBUG_H
#include FT_INTERNAL_STREAM_H
#include FT_INTERNAL_POSTSCRIPT_AUX_H
/*************************************************************************/
/* */
/* The macro FT_COMPONENT is used in trace mode. It is an implicit */
/* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */
/* messages during execution. */
/* */
#undef FT_COMPONENT
#define FT_COMPONENT trace_t42
static void
t42_parse_font_matrix( T42_Face face,
T42_Loader loader );
static void
t42_parse_encoding( T42_Face face,
T42_Loader loader );
static void
t42_parse_charstrings( T42_Face face,
T42_Loader loader );
static void
t42_parse_sfnts( T42_Face face,
T42_Loader loader );
/* as Type42 fonts have no Private dict, */
/* we set the last argument of T1_FIELD_XXX to 0 */
static const
T1_FieldRec t42_keywords[] =
{
#undef FT_STRUCTURE
#define FT_STRUCTURE T1_FontInfo
#undef T1CODE
#define T1CODE T1_FIELD_LOCATION_FONT_INFO
T1_FIELD_STRING( "version", version, 0 )
T1_FIELD_STRING( "Notice", notice, 0 )
T1_FIELD_STRING( "FullName", full_name, 0 )
T1_FIELD_STRING( "FamilyName", family_name, 0 )
T1_FIELD_STRING( "Weight", weight, 0 )
T1_FIELD_NUM ( "ItalicAngle", italic_angle, 0 )
T1_FIELD_BOOL ( "isFixedPitch", is_fixed_pitch, 0 )
T1_FIELD_NUM ( "UnderlinePosition", underline_position, 0 )
T1_FIELD_NUM ( "UnderlineThickness", underline_thickness, 0 )
#undef FT_STRUCTURE
#define FT_STRUCTURE PS_FontExtraRec
#undef T1CODE
#define T1CODE T1_FIELD_LOCATION_FONT_EXTRA
T1_FIELD_NUM ( "FSType", fs_type, 0 )
#undef FT_STRUCTURE
#define FT_STRUCTURE T1_FontRec
#undef T1CODE
#define T1CODE T1_FIELD_LOCATION_FONT_DICT
T1_FIELD_KEY ( "FontName", font_name, 0 )
T1_FIELD_NUM ( "PaintType", paint_type, 0 )
T1_FIELD_NUM ( "FontType", font_type, 0 )
T1_FIELD_FIXED( "StrokeWidth", stroke_width, 0 )
#undef FT_STRUCTURE
#define FT_STRUCTURE FT_BBox
#undef T1CODE
#define T1CODE T1_FIELD_LOCATION_BBOX
T1_FIELD_BBOX("FontBBox", xMin, 0 )
T1_FIELD_CALLBACK( "FontMatrix", t42_parse_font_matrix, 0 )
T1_FIELD_CALLBACK( "Encoding", t42_parse_encoding, 0 )
T1_FIELD_CALLBACK( "CharStrings", t42_parse_charstrings, 0 )
T1_FIELD_CALLBACK( "sfnts", t42_parse_sfnts, 0 )
{ 0, T1_FIELD_LOCATION_CID_INFO, T1_FIELD_TYPE_NONE, 0, 0, 0, 0, 0, 0 }
};
#define T1_Add_Table( p, i, o, l ) (p)->funcs.add( (p), i, o, l )
#define T1_Done_Table( p ) \
do \
{ \
if ( (p)->funcs.done ) \
(p)->funcs.done( p ); \
} while ( 0 )
#define T1_Release_Table( p ) \
do \
{ \
if ( (p)->funcs.release ) \
(p)->funcs.release( p ); \
} while ( 0 )
#define T1_Skip_Spaces( p ) (p)->root.funcs.skip_spaces( &(p)->root )
#define T1_Skip_PS_Token( p ) (p)->root.funcs.skip_PS_token( &(p)->root )
#define T1_ToInt( p ) \
(p)->root.funcs.to_int( &(p)->root )
#define T1_ToBytes( p, b, m, n, d ) \
(p)->root.funcs.to_bytes( &(p)->root, b, m, n, d )
#define T1_ToFixedArray( p, m, f, t ) \
(p)->root.funcs.to_fixed_array( &(p)->root, m, f, t )
#define T1_ToToken( p, t ) \
(p)->root.funcs.to_token( &(p)->root, t )
#define T1_Load_Field( p, f, o, m, pf ) \
(p)->root.funcs.load_field( &(p)->root, f, o, m, pf )
#define T1_Load_Field_Table( p, f, o, m, pf ) \
(p)->root.funcs.load_field_table( &(p)->root, f, o, m, pf )
/********************* Parsing Functions ******************/
FT_LOCAL_DEF( FT_Error )
t42_parser_init( T42_Parser parser,
FT_Stream stream,
FT_Memory memory,
PSAux_Service psaux )
{
FT_Error error = FT_Err_Ok;
FT_Long size;
psaux->ps_parser_funcs->init( &parser->root, 0, 0, memory );
parser->stream = stream;
parser->base_len = 0;
parser->base_dict = 0;
parser->in_memory = 0;
/*******************************************************************/
/* */
/* Here a short summary of what is going on: */
/* */
/* When creating a new Type 42 parser, we try to locate and load */
/* the base dictionary, loading the whole font into memory. */
/* */
/* When `loading' the base dictionary, we only set up pointers */
/* in the case of a memory-based stream. Otherwise, we allocate */
/* and load the base dictionary in it. */
/* */
/* parser->in_memory is set if we have a memory stream. */
/* */
if ( FT_STREAM_SEEK( 0L ) ||
FT_FRAME_ENTER( 17 ) )
goto Exit;
if ( ft_memcmp( stream->cursor, "%!PS-TrueTypeFont", 17 ) != 0 )
{
FT_TRACE2(( " not a Type42 font\n" ));
error = FT_THROW( Unknown_File_Format );
}
FT_FRAME_EXIT();
if ( error || FT_STREAM_SEEK( 0 ) )
goto Exit;
size = stream->size;
/* now, try to load `size' bytes of the `base' dictionary we */
/* found previously */
/* if it is a memory-based resource, set up pointers */
if ( !stream->read )
{
parser->base_dict = (FT_Byte*)stream->base + stream->pos;
parser->base_len = size;
parser->in_memory = 1;
/* check that the `size' field is valid */
if ( FT_STREAM_SKIP( size ) )
goto Exit;
}
else
{
/* read segment in memory */
if ( FT_ALLOC( parser->base_dict, size ) ||
FT_STREAM_READ( parser->base_dict, size ) )
goto Exit;
parser->base_len = size;
}
parser->root.base = parser->base_dict;
parser->root.cursor = parser->base_dict;
parser->root.limit = parser->root.cursor + parser->base_len;
Exit:
if ( error && !parser->in_memory )
FT_FREE( parser->base_dict );
return error;
}
FT_LOCAL_DEF( void )
t42_parser_done( T42_Parser parser )
{
FT_Memory memory = parser->root.memory;
/* free the base dictionary only when we have a disk stream */
if ( !parser->in_memory )
FT_FREE( parser->base_dict );
parser->root.funcs.done( &parser->root );
}
static int
t42_is_space( FT_Byte c )
{
return ( c == ' ' || c == '\t' ||
c == '\r' || c == '\n' || c == '\f' ||
c == '\0' );
}
static void
t42_parse_font_matrix( T42_Face face,
T42_Loader loader )
{
T42_Parser parser = &loader->parser;
FT_Matrix* matrix = &face->type1.font_matrix;
FT_Vector* offset = &face->type1.font_offset;
FT_Face root = (FT_Face)&face->root;
FT_Fixed temp[6];
FT_Fixed temp_scale;
FT_Int result;
result = T1_ToFixedArray( parser, 6, temp, 3 );
if ( result < 6 )
{
parser->root.error = FT_THROW( Invalid_File_Format );
return;
}
temp_scale = FT_ABS( temp[3] );
if ( temp_scale == 0 )
{
FT_ERROR(( "t1_parse_font_matrix: invalid font matrix\n" ));
parser->root.error = FT_THROW( Invalid_File_Format );
return;
}
/* Set Units per EM based on FontMatrix values. We set the value to */
/* 1000 / temp_scale, because temp_scale was already multiplied by */
/* 1000 (in t1_tofixed, from psobjs.c). */
root->units_per_EM = (FT_UShort)FT_DivFix( 1000, temp_scale );
/* we need to scale the values by 1.0/temp_scale */
if ( temp_scale != 0x10000L )
{
temp[0] = FT_DivFix( temp[0], temp_scale );
temp[1] = FT_DivFix( temp[1], temp_scale );
temp[2] = FT_DivFix( temp[2], temp_scale );
temp[4] = FT_DivFix( temp[4], temp_scale );
temp[5] = FT_DivFix( temp[5], temp_scale );
temp[3] = temp[3] < 0 ? -0x10000L : 0x10000L;
}
matrix->xx = temp[0];
matrix->yx = temp[1];
matrix->xy = temp[2];
matrix->yy = temp[3];
/* note that the offsets must be expressed in integer font units */
offset->x = temp[4] >> 16;
offset->y = temp[5] >> 16;
}
static void
t42_parse_encoding( T42_Face face,
T42_Loader loader )
{
T42_Parser parser = &loader->parser;
FT_Byte* cur;
FT_Byte* limit = parser->root.limit;
PSAux_Service psaux = (PSAux_Service)face->psaux;
T1_Skip_Spaces( parser );
cur = parser->root.cursor;
if ( cur >= limit )
{
FT_ERROR(( "t42_parse_encoding: out of bounds\n" ));
parser->root.error = FT_THROW( Invalid_File_Format );
return;
}
/* if we have a number or `[', the encoding is an array, */
/* and we must load it now */
if ( ft_isdigit( *cur ) || *cur == '[' )
{
T1_Encoding encode = &face->type1.encoding;
FT_Int count, n;
PS_Table char_table = &loader->encoding_table;
FT_Memory memory = parser->root.memory;
FT_Error error = FT_Err_Ok;
FT_Bool only_immediates = 0;
/* read the number of entries in the encoding; should be 256 */
if ( *cur == '[' )
{
count = 256;
only_immediates = 1;
parser->root.cursor++;
}
else
count = (FT_Int)T1_ToInt( parser );
T1_Skip_Spaces( parser );
if ( parser->root.cursor >= limit )
return;
/* we use a T1_Table to store our charnames */
loader->num_chars = encode->num_chars = count;
if ( FT_NEW_ARRAY( encode->char_index, count ) ||
FT_NEW_ARRAY( encode->char_name, count ) ||
FT_SET_ERROR( psaux->ps_table_funcs->init(
char_table, count, memory ) ) )
{
parser->root.error = error;
return;
}
/* We need to `zero' out encoding_table.elements */
for ( n = 0; n < count; n++ )
{
char* notdef = (char *)".notdef";
T1_Add_Table( char_table, n, notdef, 8 );
}
/* Now we need to read records of the form */
/* */
/* ... charcode /charname ... */
/* */
/* for each entry in our table. */
/* */
/* We simply look for a number followed by an immediate */
/* name. Note that this ignores correctly the sequence */
/* that is often seen in type42 fonts: */
/* */
/* 0 1 255 { 1 index exch /.notdef put } for dup */
/* */
/* used to clean the encoding array before anything else. */
/* */
/* Alternatively, if the array is directly given as */
/* */
/* /Encoding [ ... ] */
/* */
/* we only read immediates. */
n = 0;
T1_Skip_Spaces( parser );
while ( parser->root.cursor < limit )
{
cur = parser->root.cursor;
/* we stop when we encounter `def' or `]' */
if ( *cur == 'd' && cur + 3 < limit )
{
if ( cur[1] == 'e' &&
cur[2] == 'f' &&
t42_is_space( cur[3] ) )
{
FT_TRACE6(( "encoding end\n" ));
cur += 3;
break;
}
}
if ( *cur == ']' )
{
FT_TRACE6(( "encoding end\n" ));
cur++;
break;
}
/* check whether we have found an entry */
if ( ft_isdigit( *cur ) || only_immediates )
{
FT_Int charcode;
if ( only_immediates )
charcode = n;
else
{
charcode = (FT_Int)T1_ToInt( parser );
T1_Skip_Spaces( parser );
}
cur = parser->root.cursor;
if ( cur + 2 < limit && *cur == '/' && n < count )
{
FT_PtrDist len;
cur++;
parser->root.cursor = cur;
T1_Skip_PS_Token( parser );
if ( parser->root.cursor >= limit )
return;
if ( parser->root.error )
return;
len = parser->root.cursor - cur;
parser->root.error = T1_Add_Table( char_table, charcode,
cur, len + 1 );
if ( parser->root.error )
return;
char_table->elements[charcode][len] = '\0';
n++;
}
else if ( only_immediates )
{
/* Since the current position is not updated for */
/* immediates-only mode we would get an infinite loop if */
/* we don't do anything here. */
/* */
/* This encoding array is not valid according to the type1 */
/* specification (it might be an encoding for a CID type1 */
/* font, however), so we conclude that this font is NOT a */
/* type1 font. */
parser->root.error = FT_THROW( Unknown_File_Format );
return;
}
}
else
{
T1_Skip_PS_Token( parser );
if ( parser->root.error )
return;
}
T1_Skip_Spaces( parser );
}
face->type1.encoding_type = T1_ENCODING_TYPE_ARRAY;
parser->root.cursor = cur;
}
/* Otherwise, we should have either `StandardEncoding', */
/* `ExpertEncoding', or `ISOLatin1Encoding' */
else
{
if ( cur + 17 < limit &&
ft_strncmp( (const char*)cur, "StandardEncoding", 16 ) == 0 )
face->type1.encoding_type = T1_ENCODING_TYPE_STANDARD;
else if ( cur + 15 < limit &&
ft_strncmp( (const char*)cur, "ExpertEncoding", 14 ) == 0 )
face->type1.encoding_type = T1_ENCODING_TYPE_EXPERT;
else if ( cur + 18 < limit &&
ft_strncmp( (const char*)cur, "ISOLatin1Encoding", 17 ) == 0 )
face->type1.encoding_type = T1_ENCODING_TYPE_ISOLATIN1;
else
parser->root.error = FT_THROW( Ignore );
}
}
typedef enum T42_Load_Status_
{
BEFORE_START,
BEFORE_TABLE_DIR,
OTHER_TABLES
} T42_Load_Status;
static void
t42_parse_sfnts( T42_Face face,
T42_Loader loader )
{
T42_Parser parser = &loader->parser;
FT_Memory memory = parser->root.memory;
FT_Byte* cur;
FT_Byte* limit = parser->root.limit;
FT_Error error;
FT_Int num_tables = 0;
FT_ULong count, ttf_size = 0;
FT_Long n, string_size, old_string_size, real_size;
FT_Byte* string_buf = NULL;
FT_Bool allocated = 0;
T42_Load_Status status;
/* The format is */
/* */
/* /sfnts [ <hexstring> <hexstring> ... ] def */
/* */
/* or */
/* */
/* /sfnts [ */
/* <num_bin_bytes> RD <binary data> */
/* <num_bin_bytes> RD <binary data> */
/* ... */
/* ] def */
/* */
/* with exactly one space after the `RD' token. */
T1_Skip_Spaces( parser );
if ( parser->root.cursor >= limit || *parser->root.cursor++ != '[' )
{
FT_ERROR(( "t42_parse_sfnts: can't find begin of sfnts vector\n" ));
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
T1_Skip_Spaces( parser );
status = BEFORE_START;
string_size = 0;
old_string_size = 0;
count = 0;
while ( parser->root.cursor < limit )
{
cur = parser->root.cursor;
if ( *cur == ']' )
{
parser->root.cursor++;
goto Exit;
}
else if ( *cur == '<' )
{
T1_Skip_PS_Token( parser );
if ( parser->root.error )
goto Exit;
/* don't include delimiters */
string_size = (FT_Long)( ( parser->root.cursor - cur - 2 + 1 ) / 2 );
if ( FT_REALLOC( string_buf, old_string_size, string_size ) )
goto Fail;
allocated = 1;
parser->root.cursor = cur;
(void)T1_ToBytes( parser, string_buf, string_size, &real_size, 1 );
old_string_size = string_size;
string_size = real_size;
}
else if ( ft_isdigit( *cur ) )
{
if ( allocated )
{
FT_ERROR(( "t42_parse_sfnts: "
"can't handle mixed binary and hex strings\n" ));
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
string_size = T1_ToInt( parser );
if ( string_size < 0 )
{
FT_ERROR(( "t42_parse_sfnts: invalid string size\n" ));
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
T1_Skip_PS_Token( parser ); /* `RD' */
if ( parser->root.error )
return;
string_buf = parser->root.cursor + 1; /* one space after `RD' */
if ( limit - parser->root.cursor < string_size )
{
FT_ERROR(( "t42_parse_sfnts: too many binary data\n" ));
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
else
parser->root.cursor += string_size + 1;
}
if ( !string_buf )
{
FT_ERROR(( "t42_parse_sfnts: invalid data in sfnts array\n" ));
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
/* A string can have a trailing zero (odd) byte for padding. */
/* Ignore it. */
if ( ( string_size & 1 ) && string_buf[string_size - 1] == 0 )
string_size--;
if ( !string_size )
{
FT_ERROR(( "t42_parse_sfnts: invalid string\n" ));
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
for ( n = 0; n < string_size; n++ )
{
switch ( status )
{
case BEFORE_START:
/* load offset table, 12 bytes */
if ( count < 12 )
{
face->ttf_data[count++] = string_buf[n];
continue;
}
else
{
num_tables = 16 * face->ttf_data[4] + face->ttf_data[5];
status = BEFORE_TABLE_DIR;
ttf_size = 12 + 16 * num_tables;
if ( FT_REALLOC( face->ttf_data, 12, ttf_size ) )
goto Fail;
}
/* fall through */
case BEFORE_TABLE_DIR:
/* the offset table is read; read the table directory */
if ( count < ttf_size )
{
face->ttf_data[count++] = string_buf[n];
continue;
}
else
{
int i;
FT_ULong len;
for ( i = 0; i < num_tables; i++ )
{
FT_Byte* p = face->ttf_data + 12 + 16 * i + 12;
len = FT_PEEK_ULONG( p );
/* Pad to a 4-byte boundary length */
ttf_size += ( len + 3 ) & ~3;
}
status = OTHER_TABLES;
face->ttf_size = ttf_size;
/* there are no more than 256 tables, so no size check here */
if ( FT_REALLOC( face->ttf_data, 12 + 16 * num_tables,
ttf_size + 1 ) )
goto Fail;
}
/* fall through */
case OTHER_TABLES:
/* all other tables are just copied */
if ( count >= ttf_size )
{
FT_ERROR(( "t42_parse_sfnts: too many binary data\n" ));
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
face->ttf_data[count++] = string_buf[n];
}
}
T1_Skip_Spaces( parser );
}
/* if control reaches this point, the format was not valid */
error = FT_THROW( Invalid_File_Format );
Fail:
parser->root.error = error;
Exit:
if ( allocated )
FT_FREE( string_buf );
}
static void
t42_parse_charstrings( T42_Face face,
T42_Loader loader )
{
T42_Parser parser = &loader->parser;
PS_Table code_table = &loader->charstrings;
PS_Table name_table = &loader->glyph_names;
PS_Table swap_table = &loader->swap_table;
FT_Memory memory = parser->root.memory;
FT_Error error;
PSAux_Service psaux = (PSAux_Service)face->psaux;
FT_Byte* cur;
FT_Byte* limit = parser->root.limit;
FT_UInt n;
FT_UInt notdef_index = 0;
FT_Byte notdef_found = 0;
T1_Skip_Spaces( parser );
if ( parser->root.cursor >= limit )
{
FT_ERROR(( "t42_parse_charstrings: out of bounds\n" ));
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
if ( ft_isdigit( *parser->root.cursor ) )
{
loader->num_glyphs = (FT_UInt)T1_ToInt( parser );
if ( parser->root.error )
return;
}
else if ( *parser->root.cursor == '<' )
{
/* We have `<< ... >>'. Count the number of `/' in the dictionary */
/* to get its size. */
FT_UInt count = 0;
T1_Skip_PS_Token( parser );
if ( parser->root.error )
return;
T1_Skip_Spaces( parser );
cur = parser->root.cursor;
while ( parser->root.cursor < limit )
{
if ( *parser->root.cursor == '/' )
count++;
else if ( *parser->root.cursor == '>' )
{
loader->num_glyphs = count;
parser->root.cursor = cur; /* rewind */
break;
}
T1_Skip_PS_Token( parser );
if ( parser->root.error )
return;
T1_Skip_Spaces( parser );
}
}
else
{
FT_ERROR(( "t42_parse_charstrings: invalid token\n" ));
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
if ( parser->root.cursor >= limit )
{
FT_ERROR(( "t42_parse_charstrings: out of bounds\n" ));
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
/* initialize tables */
error = psaux->ps_table_funcs->init( code_table,
loader->num_glyphs,
memory );
if ( error )
goto Fail;
error = psaux->ps_table_funcs->init( name_table,
loader->num_glyphs,
memory );
if ( error )
goto Fail;
/* Initialize table for swapping index notdef_index and */
/* index 0 names and codes (if necessary). */
error = psaux->ps_table_funcs->init( swap_table, 4, memory );
if ( error )
goto Fail;
n = 0;
for (;;)
{
/* The format is simple: */
/* `/glyphname' + index [+ def] */
T1_Skip_Spaces( parser );
cur = parser->root.cursor;
if ( cur >= limit )
break;
/* We stop when we find an `end' keyword or '>' */
if ( *cur == 'e' &&
cur + 3 < limit &&
cur[1] == 'n' &&
cur[2] == 'd' &&
t42_is_space( cur[3] ) )
break;
if ( *cur == '>' )
break;
T1_Skip_PS_Token( parser );
if ( parser->root.error )
return;
if ( *cur == '/' )
{
FT_PtrDist len;
if ( cur + 1 >= limit )
{
FT_ERROR(( "t42_parse_charstrings: out of bounds\n" ));
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
cur++; /* skip `/' */
len = parser->root.cursor - cur;
error = T1_Add_Table( name_table, n, cur, len + 1 );
if ( error )
goto Fail;
/* add a trailing zero to the name table */
name_table->elements[n][len] = '\0';
/* record index of /.notdef */
if ( *cur == '.' &&
ft_strcmp( ".notdef",
(const char*)(name_table->elements[n]) ) == 0 )
{
notdef_index = n;
notdef_found = 1;
}
T1_Skip_Spaces( parser );
cur = parser->root.cursor;
(void)T1_ToInt( parser );
if ( parser->root.cursor >= limit )
{
FT_ERROR(( "t42_parse_charstrings: out of bounds\n" ));
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
len = parser->root.cursor - cur;
error = T1_Add_Table( code_table, n, cur, len + 1 );
if ( error )
goto Fail;
code_table->elements[n][len] = '\0';
n++;
if ( n >= loader->num_glyphs )
break;
}
}
loader->num_glyphs = n;
if ( !notdef_found )
{
FT_ERROR(( "t42_parse_charstrings: no /.notdef glyph\n" ));
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
/* if /.notdef does not occupy index 0, do our magic. */
if ( ft_strcmp( (const char*)".notdef",
(const char*)name_table->elements[0] ) )
{
/* Swap glyph in index 0 with /.notdef glyph. First, add index 0 */
/* name and code entries to swap_table. Then place notdef_index */
/* name and code entries into swap_table. Then swap name and code */
/* entries at indices notdef_index and 0 using values stored in */
/* swap_table. */
/* Index 0 name */
error = T1_Add_Table( swap_table, 0,
name_table->elements[0],
name_table->lengths [0] );
if ( error )
goto Fail;
/* Index 0 code */
error = T1_Add_Table( swap_table, 1,
code_table->elements[0],
code_table->lengths [0] );
if ( error )
goto Fail;
/* Index notdef_index name */
error = T1_Add_Table( swap_table, 2,
name_table->elements[notdef_index],
name_table->lengths [notdef_index] );
if ( error )
goto Fail;
/* Index notdef_index code */
error = T1_Add_Table( swap_table, 3,
code_table->elements[notdef_index],
code_table->lengths [notdef_index] );
if ( error )
goto Fail;
error = T1_Add_Table( name_table, notdef_index,
swap_table->elements[0],
swap_table->lengths [0] );
if ( error )
goto Fail;
error = T1_Add_Table( code_table, notdef_index,
swap_table->elements[1],
swap_table->lengths [1] );
if ( error )
goto Fail;
error = T1_Add_Table( name_table, 0,
swap_table->elements[2],
swap_table->lengths [2] );
if ( error )
goto Fail;
error = T1_Add_Table( code_table, 0,
swap_table->elements[3],
swap_table->lengths [3] );
if ( error )
goto Fail;
}
return;
Fail:
parser->root.error = error;
}
static FT_Error
t42_load_keyword( T42_Face face,
T42_Loader loader,
T1_Field field )
{
FT_Error error;
void* dummy_object;
void** objects;
FT_UInt max_objects = 0;
/* if the keyword has a dedicated callback, call it */
if ( field->type == T1_FIELD_TYPE_CALLBACK )
{
field->reader( (FT_Face)face, loader );
error = loader->parser.root.error;
goto Exit;
}
/* now the keyword is either a simple field or a table of fields; */
/* we are now going to take care of it */
switch ( field->location )
{
case T1_FIELD_LOCATION_FONT_INFO:
dummy_object = &face->type1.font_info;
break;
case T1_FIELD_LOCATION_FONT_EXTRA:
dummy_object = &face->type1.font_extra;
break;
case T1_FIELD_LOCATION_BBOX:
dummy_object = &face->type1.font_bbox;
break;
default:
dummy_object = &face->type1;
}
objects = &dummy_object;
if ( field->type == T1_FIELD_TYPE_INTEGER_ARRAY ||
field->type == T1_FIELD_TYPE_FIXED_ARRAY )
error = T1_Load_Field_Table( &loader->parser, field,
objects, max_objects, 0 );
else
error = T1_Load_Field( &loader->parser, field,
objects, max_objects, 0 );
Exit:
return error;
}
FT_LOCAL_DEF( FT_Error )
t42_parse_dict( T42_Face face,
T42_Loader loader,
FT_Byte* base,
FT_Long size )
{
T42_Parser parser = &loader->parser;
FT_Byte* limit;
FT_Int n_keywords = (FT_Int)( sizeof ( t42_keywords ) /
sizeof ( t42_keywords[0] ) );
parser->root.cursor = base;
parser->root.limit = base + size;
parser->root.error = FT_Err_Ok;
limit = parser->root.limit;
T1_Skip_Spaces( parser );
while ( parser->root.cursor < limit )
{
FT_Byte* cur;
cur = parser->root.cursor;
/* look for `FontDirectory' which causes problems for some fonts */
if ( *cur == 'F' && cur + 25 < limit &&
ft_strncmp( (char*)cur, "FontDirectory", 13 ) == 0 )
{
FT_Byte* cur2;
/* skip the `FontDirectory' keyword */
T1_Skip_PS_Token( parser );
T1_Skip_Spaces ( parser );
cur = cur2 = parser->root.cursor;
/* look up the `known' keyword */
while ( cur < limit )
{
if ( *cur == 'k' && cur + 5 < limit &&
ft_strncmp( (char*)cur, "known", 5 ) == 0 )
break;
T1_Skip_PS_Token( parser );
if ( parser->root.error )
goto Exit;
T1_Skip_Spaces ( parser );
cur = parser->root.cursor;
}
if ( cur < limit )
{
T1_TokenRec token;
/* skip the `known' keyword and the token following it */
T1_Skip_PS_Token( parser );
T1_ToToken( parser, &token );
/* if the last token was an array, skip it! */
if ( token.type == T1_TOKEN_TYPE_ARRAY )
cur2 = parser->root.cursor;
}
parser->root.cursor = cur2;
}
/* look for immediates */
else if ( *cur == '/' && cur + 2 < limit )
{
FT_PtrDist len;
cur++;
parser->root.cursor = cur;
T1_Skip_PS_Token( parser );
if ( parser->root.error )
goto Exit;
len = parser->root.cursor - cur;
if ( len > 0 && len < 22 && parser->root.cursor < limit )
{
int i;
/* now compare the immediate name to the keyword table */
/* loop through all known keywords */
for ( i = 0; i < n_keywords; i++ )
{
T1_Field keyword = (T1_Field)&t42_keywords[i];
FT_Byte *name = (FT_Byte*)keyword->ident;
if ( !name )
continue;
if ( cur[0] == name[0] &&
len == (FT_PtrDist)ft_strlen( (const char *)name ) &&
ft_memcmp( cur, name, len ) == 0 )
{
/* we found it -- run the parsing callback! */
parser->root.error = t42_load_keyword( face,
loader,
keyword );
if ( parser->root.error )
return parser->root.error;
break;
}
}
}
}
else
{
T1_Skip_PS_Token( parser );
if ( parser->root.error )
goto Exit;
}
T1_Skip_Spaces( parser );
}
Exit:
return parser->root.error;
}
FT_LOCAL_DEF( void )
t42_loader_init( T42_Loader loader,
T42_Face face )
{
FT_UNUSED( face );
FT_MEM_ZERO( loader, sizeof ( *loader ) );
loader->num_glyphs = 0;
loader->num_chars = 0;
/* initialize the tables -- simply set their `init' field to 0 */
loader->encoding_table.init = 0;
loader->charstrings.init = 0;
loader->glyph_names.init = 0;
}
FT_LOCAL_DEF( void )
t42_loader_done( T42_Loader loader )
{
T42_Parser parser = &loader->parser;
/* finalize tables */
T1_Release_Table( &loader->encoding_table );
T1_Release_Table( &loader->charstrings );
T1_Release_Table( &loader->glyph_names );
T1_Release_Table( &loader->swap_table );
/* finalize parser */
t42_parser_done( parser );
}
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/type42/t42parse.c | C | apache-2.0 | 36,576 |
/***************************************************************************/
/* */
/* t42parse.h */
/* */
/* Type 42 font parser (specification). */
/* */
/* Copyright 2002, 2003 by Roberto Alameda. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
#ifndef __T42PARSE_H__
#define __T42PARSE_H__
#include "t42objs.h"
#include FT_INTERNAL_POSTSCRIPT_AUX_H
FT_BEGIN_HEADER
typedef struct T42_ParserRec_
{
PS_ParserRec root;
FT_Stream stream;
FT_Byte* base_dict;
FT_Long base_len;
FT_Bool in_memory;
} T42_ParserRec, *T42_Parser;
typedef struct T42_Loader_
{
T42_ParserRec parser; /* parser used to read the stream */
FT_UInt num_chars; /* number of characters in encoding */
PS_TableRec encoding_table; /* PS_Table used to store the */
/* encoding character names */
FT_UInt num_glyphs;
PS_TableRec glyph_names;
PS_TableRec charstrings;
PS_TableRec swap_table; /* For moving .notdef glyph to index 0. */
} T42_LoaderRec, *T42_Loader;
FT_LOCAL( FT_Error )
t42_parser_init( T42_Parser parser,
FT_Stream stream,
FT_Memory memory,
PSAux_Service psaux );
FT_LOCAL( void )
t42_parser_done( T42_Parser parser );
FT_LOCAL( FT_Error )
t42_parse_dict( T42_Face face,
T42_Loader loader,
FT_Byte* base,
FT_Long size );
FT_LOCAL( void )
t42_loader_init( T42_Loader loader,
T42_Face face );
FT_LOCAL( void )
t42_loader_done( T42_Loader loader );
/* */
FT_END_HEADER
#endif /* __T42PARSE_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/type42/t42parse.h | C | apache-2.0 | 2,703 |
/***************************************************************************/
/* */
/* t42types.h */
/* */
/* Type 42 font data types (specification only). */
/* */
/* Copyright 2002, 2003, 2006, 2008 by Roberto Alameda. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
#ifndef __T42TYPES_H__
#define __T42TYPES_H__
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_TYPE1_TABLES_H
#include FT_INTERNAL_TYPE1_TYPES_H
#include FT_INTERNAL_POSTSCRIPT_HINTS_H
FT_BEGIN_HEADER
typedef struct T42_FaceRec_
{
FT_FaceRec root;
T1_FontRec type1;
const void* psnames;
const void* psaux;
#if 0
const void* afm_data;
#endif
FT_Byte* ttf_data;
FT_ULong ttf_size;
FT_Face ttf_face;
FT_CharMapRec charmaprecs[2];
FT_CharMap charmaps[2];
PS_UnicodesRec unicode_map;
} T42_FaceRec, *T42_Face;
FT_END_HEADER
#endif /* __T42TYPES_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/type42/t42types.h | C | apache-2.0 | 1,852 |
/***************************************************************************/
/* */
/* type42.c */
/* */
/* FreeType Type 42 driver component. */
/* */
/* Copyright 2002 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
#define FT_MAKE_OPTION_SINGLE_OBJECT
#include <ft2build.h>
#include "t42objs.c"
#include "t42parse.c"
#include "t42drivr.c"
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/type42/type42.c | C | apache-2.0 | 1,385 |
/***************************************************************************/
/* */
/* fnterrs.h */
/* */
/* Win FNT/FON error codes (specification only). */
/* */
/* Copyright 2001, 2012 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
/*************************************************************************/
/* */
/* This file is used to define the Windows FNT/FON error enumeration */
/* constants. */
/* */
/*************************************************************************/
#ifndef __FNTERRS_H__
#define __FNTERRS_H__
#include FT_MODULE_ERRORS_H
#undef __FTERRORS_H__
#undef FT_ERR_PREFIX
#define FT_ERR_PREFIX FNT_Err_
#define FT_ERR_BASE FT_Mod_Err_Winfonts
#include FT_ERRORS_H
#endif /* __FNTERRS_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/winfonts/fnterrs.h | C | apache-2.0 | 1,975 |
#
# FreeType 2 Windows FNT/FON module definition
#
# Copyright 1996-2000, 2006 by
# David Turner, Robert Wilhelm, and Werner Lemberg.
#
# This file is part of the FreeType project, and may only be used, modified,
# and distributed under the terms of the FreeType project license,
# LICENSE.TXT. By continuing to use, modify, or distribute this file you
# indicate that you have read the license and understand and accept it
# fully.
FTMODULE_H_COMMANDS += WINDOWS_DRIVER
define WINDOWS_DRIVER
$(OPEN_DRIVER) FT_Driver_ClassRec, winfnt_driver_class $(CLOSE_DRIVER)
$(ECHO_DRIVER)winfnt $(ECHO_DRIVER_DESC)Windows bitmap fonts with extension *.fnt or *.fon$(ECHO_DRIVER_DONE)
endef
# EOF
| YifuLiu/AliOS-Things | components/freetype/src/winfonts/module.mk | Makefile | apache-2.0 | 696 |
#
# FreeType 2 Windows FNT/FON driver configuration rules
#
# Copyright 1996-2000, 2001, 2003 by
# David Turner, Robert Wilhelm, and Werner Lemberg.
#
# This file is part of the FreeType project, and may only be used, modified,
# and distributed under the terms of the FreeType project license,
# LICENSE.TXT. By continuing to use, modify, or distribute this file you
# indicate that you have read the license and understand and accept it
# fully.
# Windows driver directory
#
FNT_DIR := $(SRC_DIR)/winfonts
FNT_COMPILE := $(FT_COMPILE) $I$(subst /,$(COMPILER_SEP),$(FNT_DIR))
# Windows driver sources (i.e., C files)
#
FNT_DRV_SRC := $(FNT_DIR)/winfnt.c
# Windows driver headers
#
FNT_DRV_H := $(FNT_DRV_SRC:%.c=%.h) \
$(FNT_DIR)/fnterrs.h
# Windows driver object(s)
#
# FNT_DRV_OBJ_M is used during `multi' builds
# FNT_DRV_OBJ_S is used during `single' builds
#
FNT_DRV_OBJ_M := $(FNT_DRV_SRC:$(FNT_DIR)/%.c=$(OBJ_DIR)/%.$O)
FNT_DRV_OBJ_S := $(OBJ_DIR)/winfnt.$O
# Windows driver source file for single build
#
FNT_DRV_SRC_S := $(FNT_DIR)/winfnt.c
# Windows driver - single object
#
$(FNT_DRV_OBJ_S): $(FNT_DRV_SRC_S) $(FNT_DRV_SRC) $(FREETYPE_H) $(FNT_DRV_H)
$(FNT_COMPILE) $T$(subst /,$(COMPILER_SEP),$@ $(FNT_DRV_SRC_S))
# Windows driver - multiple objects
#
$(OBJ_DIR)/%.$O: $(FNT_DIR)/%.c $(FREETYPE_H) $(FNT_DRV_H)
$(FNT_COMPILE) $T$(subst /,$(COMPILER_SEP),$@ $<)
# update main driver object lists
#
DRV_OBJS_S += $(FNT_DRV_OBJ_S)
DRV_OBJS_M += $(FNT_DRV_OBJ_M)
# EOF
| YifuLiu/AliOS-Things | components/freetype/src/winfonts/rules.mk | Makefile | apache-2.0 | 1,518 |
/***************************************************************************/
/* */
/* winfnt.c */
/* */
/* FreeType font driver for Windows FNT/FON files */
/* */
/* Copyright 1996-2004, 2006-2014 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* Copyright 2003 Huw D M Davies for Codeweavers */
/* Copyright 2007 Dmitry Timoshkov for Codeweavers */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
#include <ft2build.h>
#include FT_WINFONTS_H
#include FT_INTERNAL_DEBUG_H
#include FT_INTERNAL_STREAM_H
#include FT_INTERNAL_OBJECTS_H
#include FT_TRUETYPE_IDS_H
#include "winfnt.h"
#include "fnterrs.h"
#include FT_SERVICE_WINFNT_H
#include FT_SERVICE_XFREE86_NAME_H
/*************************************************************************/
/* */
/* The macro FT_COMPONENT is used in trace mode. It is an implicit */
/* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */
/* messages during execution. */
/* */
#undef FT_COMPONENT
#define FT_COMPONENT trace_winfnt
static const FT_Frame_Field winmz_header_fields[] =
{
#undef FT_STRUCTURE
#define FT_STRUCTURE WinMZ_HeaderRec
FT_FRAME_START( 64 ),
FT_FRAME_USHORT_LE ( magic ),
FT_FRAME_SKIP_BYTES( 29 * 2 ),
FT_FRAME_ULONG_LE ( lfanew ),
FT_FRAME_END
};
static const FT_Frame_Field winne_header_fields[] =
{
#undef FT_STRUCTURE
#define FT_STRUCTURE WinNE_HeaderRec
FT_FRAME_START( 40 ),
FT_FRAME_USHORT_LE ( magic ),
FT_FRAME_SKIP_BYTES( 34 ),
FT_FRAME_USHORT_LE ( resource_tab_offset ),
FT_FRAME_USHORT_LE ( rname_tab_offset ),
FT_FRAME_END
};
static const FT_Frame_Field winpe32_header_fields[] =
{
#undef FT_STRUCTURE
#define FT_STRUCTURE WinPE32_HeaderRec
FT_FRAME_START( 248 ),
FT_FRAME_ULONG_LE ( magic ), /* PE00 */
FT_FRAME_USHORT_LE ( machine ), /* 0x014c - i386 */
FT_FRAME_USHORT_LE ( number_of_sections ),
FT_FRAME_SKIP_BYTES( 12 ),
FT_FRAME_USHORT_LE ( size_of_optional_header ),
FT_FRAME_SKIP_BYTES( 2 ),
FT_FRAME_USHORT_LE ( magic32 ), /* 0x10b */
FT_FRAME_SKIP_BYTES( 110 ),
FT_FRAME_ULONG_LE ( rsrc_virtual_address ),
FT_FRAME_ULONG_LE ( rsrc_size ),
FT_FRAME_SKIP_BYTES( 104 ),
FT_FRAME_END
};
static const FT_Frame_Field winpe32_section_fields[] =
{
#undef FT_STRUCTURE
#define FT_STRUCTURE WinPE32_SectionRec
FT_FRAME_START( 40 ),
FT_FRAME_BYTES ( name, 8 ),
FT_FRAME_SKIP_BYTES( 4 ),
FT_FRAME_ULONG_LE ( virtual_address ),
FT_FRAME_ULONG_LE ( size_of_raw_data ),
FT_FRAME_ULONG_LE ( pointer_to_raw_data ),
FT_FRAME_SKIP_BYTES( 16 ),
FT_FRAME_END
};
static const FT_Frame_Field winpe_rsrc_dir_fields[] =
{
#undef FT_STRUCTURE
#define FT_STRUCTURE WinPE_RsrcDirRec
FT_FRAME_START( 16 ),
FT_FRAME_ULONG_LE ( characteristics ),
FT_FRAME_ULONG_LE ( time_date_stamp ),
FT_FRAME_USHORT_LE( major_version ),
FT_FRAME_USHORT_LE( minor_version ),
FT_FRAME_USHORT_LE( number_of_named_entries ),
FT_FRAME_USHORT_LE( number_of_id_entries ),
FT_FRAME_END
};
static const FT_Frame_Field winpe_rsrc_dir_entry_fields[] =
{
#undef FT_STRUCTURE
#define FT_STRUCTURE WinPE_RsrcDirEntryRec
FT_FRAME_START( 8 ),
FT_FRAME_ULONG_LE( name ),
FT_FRAME_ULONG_LE( offset ),
FT_FRAME_END
};
static const FT_Frame_Field winpe_rsrc_data_entry_fields[] =
{
#undef FT_STRUCTURE
#define FT_STRUCTURE WinPE_RsrcDataEntryRec
FT_FRAME_START( 16 ),
FT_FRAME_ULONG_LE( offset_to_data ),
FT_FRAME_ULONG_LE( size ),
FT_FRAME_ULONG_LE( code_page ),
FT_FRAME_ULONG_LE( reserved ),
FT_FRAME_END
};
static const FT_Frame_Field winfnt_header_fields[] =
{
#undef FT_STRUCTURE
#define FT_STRUCTURE FT_WinFNT_HeaderRec
FT_FRAME_START( 148 ),
FT_FRAME_USHORT_LE( version ),
FT_FRAME_ULONG_LE ( file_size ),
FT_FRAME_BYTES ( copyright, 60 ),
FT_FRAME_USHORT_LE( file_type ),
FT_FRAME_USHORT_LE( nominal_point_size ),
FT_FRAME_USHORT_LE( vertical_resolution ),
FT_FRAME_USHORT_LE( horizontal_resolution ),
FT_FRAME_USHORT_LE( ascent ),
FT_FRAME_USHORT_LE( internal_leading ),
FT_FRAME_USHORT_LE( external_leading ),
FT_FRAME_BYTE ( italic ),
FT_FRAME_BYTE ( underline ),
FT_FRAME_BYTE ( strike_out ),
FT_FRAME_USHORT_LE( weight ),
FT_FRAME_BYTE ( charset ),
FT_FRAME_USHORT_LE( pixel_width ),
FT_FRAME_USHORT_LE( pixel_height ),
FT_FRAME_BYTE ( pitch_and_family ),
FT_FRAME_USHORT_LE( avg_width ),
FT_FRAME_USHORT_LE( max_width ),
FT_FRAME_BYTE ( first_char ),
FT_FRAME_BYTE ( last_char ),
FT_FRAME_BYTE ( default_char ),
FT_FRAME_BYTE ( break_char ),
FT_FRAME_USHORT_LE( bytes_per_row ),
FT_FRAME_ULONG_LE ( device_offset ),
FT_FRAME_ULONG_LE ( face_name_offset ),
FT_FRAME_ULONG_LE ( bits_pointer ),
FT_FRAME_ULONG_LE ( bits_offset ),
FT_FRAME_BYTE ( reserved ),
FT_FRAME_ULONG_LE ( flags ),
FT_FRAME_USHORT_LE( A_space ),
FT_FRAME_USHORT_LE( B_space ),
FT_FRAME_USHORT_LE( C_space ),
FT_FRAME_ULONG_LE ( color_table_offset ),
FT_FRAME_BYTES ( reserved1, 16 ),
FT_FRAME_END
};
static void
fnt_font_done( FNT_Face face )
{
FT_Memory memory = FT_FACE( face )->memory;
FT_Stream stream = FT_FACE( face )->stream;
FNT_Font font = face->font;
if ( !font )
return;
if ( font->fnt_frame )
FT_FRAME_RELEASE( font->fnt_frame );
FT_FREE( font->family_name );
FT_FREE( font );
face->font = 0;
}
static FT_Error
fnt_font_load( FNT_Font font,
FT_Stream stream )
{
FT_Error error;
FT_WinFNT_Header header = &font->header;
FT_Bool new_format;
FT_UInt size;
/* first of all, read the FNT header */
if ( FT_STREAM_SEEK( font->offset ) ||
FT_STREAM_READ_FIELDS( winfnt_header_fields, header ) )
goto Exit;
/* check header */
if ( header->version != 0x200 &&
header->version != 0x300 )
{
FT_TRACE2(( " not a Windows FNT file\n" ));
error = FT_THROW( Unknown_File_Format );
goto Exit;
}
new_format = FT_BOOL( font->header.version == 0x300 );
size = new_format ? 148 : 118;
if ( header->file_size < size )
{
FT_TRACE2(( " not a Windows FNT file\n" ));
error = FT_THROW( Unknown_File_Format );
goto Exit;
}
/* Version 2 doesn't have these fields */
if ( header->version == 0x200 )
{
header->flags = 0;
header->A_space = 0;
header->B_space = 0;
header->C_space = 0;
header->color_table_offset = 0;
}
if ( header->file_type & 1 )
{
FT_TRACE2(( "[can't handle vector FNT fonts]\n" ));
error = FT_THROW( Unknown_File_Format );
goto Exit;
}
/* this is a FNT file/table; extract its frame */
if ( FT_STREAM_SEEK( font->offset ) ||
FT_FRAME_EXTRACT( header->file_size, font->fnt_frame ) )
goto Exit;
Exit:
return error;
}
static FT_Error
fnt_face_get_dll_font( FNT_Face face,
FT_Int face_index )
{
FT_Error error;
FT_Stream stream = FT_FACE( face )->stream;
FT_Memory memory = FT_FACE( face )->memory;
WinMZ_HeaderRec mz_header;
face->font = 0;
/* does it begin with an MZ header? */
if ( FT_STREAM_SEEK( 0 ) ||
FT_STREAM_READ_FIELDS( winmz_header_fields, &mz_header ) )
goto Exit;
error = FT_ERR( Unknown_File_Format );
if ( mz_header.magic == WINFNT_MZ_MAGIC )
{
/* yes, now look for an NE header in the file */
WinNE_HeaderRec ne_header;
FT_TRACE2(( "MZ signature found\n" ));
if ( FT_STREAM_SEEK( mz_header.lfanew ) ||
FT_STREAM_READ_FIELDS( winne_header_fields, &ne_header ) )
goto Exit;
error = FT_ERR( Unknown_File_Format );
if ( ne_header.magic == WINFNT_NE_MAGIC )
{
/* good, now look into the resource table for each FNT resource */
FT_ULong res_offset = mz_header.lfanew +
ne_header.resource_tab_offset;
FT_UShort size_shift;
FT_UShort font_count = 0;
FT_ULong font_offset = 0;
FT_TRACE2(( "NE signature found\n" ));
if ( FT_STREAM_SEEK( res_offset ) ||
FT_FRAME_ENTER( ne_header.rname_tab_offset -
ne_header.resource_tab_offset ) )
goto Exit;
size_shift = FT_GET_USHORT_LE();
for (;;)
{
FT_UShort type_id, count;
type_id = FT_GET_USHORT_LE();
if ( !type_id )
break;
count = FT_GET_USHORT_LE();
if ( type_id == 0x8008U )
{
font_count = count;
font_offset = (FT_ULong)( FT_STREAM_POS() + 4 +
( stream->cursor - stream->limit ) );
break;
}
stream->cursor += 4 + count * 12;
}
FT_FRAME_EXIT();
if ( !font_count || !font_offset )
{
FT_TRACE2(( "this file doesn't contain any FNT resources\n" ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
/* loading `winfnt_header_fields' needs at least 118 bytes; */
/* use this as a rough measure to check the expected font size */
if ( font_count * 118UL > stream->size )
{
FT_TRACE2(( "invalid number of faces\n" ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
face->root.num_faces = font_count;
if ( face_index >= font_count )
{
error = FT_THROW( Invalid_Argument );
goto Exit;
}
else if ( face_index < 0 )
goto Exit;
if ( FT_NEW( face->font ) )
goto Exit;
if ( FT_STREAM_SEEK( font_offset + face_index * 12 ) ||
FT_FRAME_ENTER( 12 ) )
goto Fail;
face->font->offset = (FT_ULong)FT_GET_USHORT_LE() << size_shift;
face->font->fnt_size = (FT_ULong)FT_GET_USHORT_LE() << size_shift;
stream->cursor += 8;
FT_FRAME_EXIT();
error = fnt_font_load( face->font, stream );
}
else if ( ne_header.magic == WINFNT_PE_MAGIC )
{
WinPE32_HeaderRec pe32_header;
WinPE32_SectionRec pe32_section;
WinPE_RsrcDirRec root_dir, name_dir, lang_dir;
WinPE_RsrcDirEntryRec dir_entry1, dir_entry2, dir_entry3;
WinPE_RsrcDataEntryRec data_entry;
FT_Long root_dir_offset, name_dir_offset, lang_dir_offset;
FT_UShort i, j, k;
FT_TRACE2(( "PE signature found\n" ));
if ( FT_STREAM_SEEK( mz_header.lfanew ) ||
FT_STREAM_READ_FIELDS( winpe32_header_fields, &pe32_header ) )
goto Exit;
FT_TRACE2(( "magic %04lx, machine %02x, number_of_sections %u, "
"size_of_optional_header %02x\n"
"magic32 %02x, rsrc_virtual_address %04lx, "
"rsrc_size %04lx\n",
pe32_header.magic, pe32_header.machine,
pe32_header.number_of_sections,
pe32_header.size_of_optional_header,
pe32_header.magic32, pe32_header.rsrc_virtual_address,
pe32_header.rsrc_size ));
if ( pe32_header.magic != WINFNT_PE_MAGIC /* check full signature */ ||
pe32_header.machine != 0x014c /* i386 */ ||
pe32_header.size_of_optional_header != 0xe0 /* FIXME */ ||
pe32_header.magic32 != 0x10b )
{
FT_TRACE2(( "this file has an invalid PE header\n" ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
face->root.num_faces = 0;
for ( i = 0; i < pe32_header.number_of_sections; i++ )
{
if ( FT_STREAM_READ_FIELDS( winpe32_section_fields,
&pe32_section ) )
goto Exit;
FT_TRACE2(( "name %.8s, va %04lx, size %04lx, offset %04lx\n",
pe32_section.name, pe32_section.virtual_address,
pe32_section.size_of_raw_data,
pe32_section.pointer_to_raw_data ));
if ( pe32_header.rsrc_virtual_address ==
pe32_section.virtual_address )
goto Found_rsrc_section;
}
FT_TRACE2(( "this file doesn't contain any resources\n" ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
Found_rsrc_section:
FT_TRACE2(( "found resources section %.8s\n", pe32_section.name ));
if ( FT_STREAM_SEEK( pe32_section.pointer_to_raw_data ) ||
FT_STREAM_READ_FIELDS( winpe_rsrc_dir_fields, &root_dir ) )
goto Exit;
root_dir_offset = pe32_section.pointer_to_raw_data;
for ( i = 0; i < root_dir.number_of_named_entries +
root_dir.number_of_id_entries; i++ )
{
if ( FT_STREAM_SEEK( root_dir_offset + 16 + i * 8 ) ||
FT_STREAM_READ_FIELDS( winpe_rsrc_dir_entry_fields,
&dir_entry1 ) )
goto Exit;
if ( !(dir_entry1.offset & 0x80000000UL ) /* DataIsDirectory */ )
{
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
dir_entry1.offset &= ~0x80000000UL;
name_dir_offset = pe32_section.pointer_to_raw_data +
dir_entry1.offset;
if ( FT_STREAM_SEEK( pe32_section.pointer_to_raw_data +
dir_entry1.offset ) ||
FT_STREAM_READ_FIELDS( winpe_rsrc_dir_fields, &name_dir ) )
goto Exit;
for ( j = 0; j < name_dir.number_of_named_entries +
name_dir.number_of_id_entries; j++ )
{
if ( FT_STREAM_SEEK( name_dir_offset + 16 + j * 8 ) ||
FT_STREAM_READ_FIELDS( winpe_rsrc_dir_entry_fields,
&dir_entry2 ) )
goto Exit;
if ( !(dir_entry2.offset & 0x80000000UL ) /* DataIsDirectory */ )
{
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
dir_entry2.offset &= ~0x80000000UL;
lang_dir_offset = pe32_section.pointer_to_raw_data +
dir_entry2.offset;
if ( FT_STREAM_SEEK( pe32_section.pointer_to_raw_data +
dir_entry2.offset ) ||
FT_STREAM_READ_FIELDS( winpe_rsrc_dir_fields, &lang_dir ) )
goto Exit;
for ( k = 0; k < lang_dir.number_of_named_entries +
lang_dir.number_of_id_entries; k++ )
{
if ( FT_STREAM_SEEK( lang_dir_offset + 16 + k * 8 ) ||
FT_STREAM_READ_FIELDS( winpe_rsrc_dir_entry_fields,
&dir_entry3 ) )
goto Exit;
if ( dir_entry2.offset & 0x80000000UL /* DataIsDirectory */ )
{
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
if ( dir_entry1.name == 8 /* RT_FONT */ )
{
if ( FT_STREAM_SEEK( root_dir_offset + dir_entry3.offset ) ||
FT_STREAM_READ_FIELDS( winpe_rsrc_data_entry_fields,
&data_entry ) )
goto Exit;
FT_TRACE2(( "found font #%lu, offset %04lx, "
"size %04lx, cp %lu\n",
dir_entry2.name,
pe32_section.pointer_to_raw_data +
data_entry.offset_to_data -
pe32_section.virtual_address,
data_entry.size, data_entry.code_page ));
if ( face_index == face->root.num_faces )
{
if ( FT_NEW( face->font ) )
goto Exit;
face->font->offset = pe32_section.pointer_to_raw_data +
data_entry.offset_to_data -
pe32_section.virtual_address;
face->font->fnt_size = data_entry.size;
error = fnt_font_load( face->font, stream );
if ( error )
{
FT_TRACE2(( "font #%lu load error %d\n",
dir_entry2.name, error ));
goto Fail;
}
else
FT_TRACE2(( "font #%lu successfully loaded\n",
dir_entry2.name ));
}
face->root.num_faces++;
}
}
}
}
}
if ( !face->root.num_faces )
{
FT_TRACE2(( "this file doesn't contain any RT_FONT resources\n" ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
if ( face_index >= face->root.num_faces )
{
error = FT_THROW( Invalid_Argument );
goto Exit;
}
}
Fail:
if ( error )
fnt_font_done( face );
Exit:
return error;
}
typedef struct FNT_CMapRec_
{
FT_CMapRec cmap;
FT_UInt32 first;
FT_UInt32 count;
} FNT_CMapRec, *FNT_CMap;
static FT_Error
fnt_cmap_init( FNT_CMap cmap )
{
FNT_Face face = (FNT_Face)FT_CMAP_FACE( cmap );
FNT_Font font = face->font;
cmap->first = (FT_UInt32) font->header.first_char;
cmap->count = (FT_UInt32)( font->header.last_char - cmap->first + 1 );
return 0;
}
static FT_UInt
fnt_cmap_char_index( FNT_CMap cmap,
FT_UInt32 char_code )
{
FT_UInt gindex = 0;
char_code -= cmap->first;
if ( char_code < cmap->count )
/* we artificially increase the glyph index; */
/* FNT_Load_Glyph reverts to the right one */
gindex = (FT_UInt)( char_code + 1 );
return gindex;
}
static FT_UInt32
fnt_cmap_char_next( FNT_CMap cmap,
FT_UInt32 *pchar_code )
{
FT_UInt gindex = 0;
FT_UInt32 result = 0;
FT_UInt32 char_code = *pchar_code + 1;
if ( char_code <= cmap->first )
{
result = cmap->first;
gindex = 1;
}
else
{
char_code -= cmap->first;
if ( char_code < cmap->count )
{
result = cmap->first + char_code;
gindex = (FT_UInt)( char_code + 1 );
}
}
*pchar_code = result;
return gindex;
}
static const FT_CMap_ClassRec fnt_cmap_class_rec =
{
sizeof ( FNT_CMapRec ),
(FT_CMap_InitFunc) fnt_cmap_init,
(FT_CMap_DoneFunc) NULL,
(FT_CMap_CharIndexFunc)fnt_cmap_char_index,
(FT_CMap_CharNextFunc) fnt_cmap_char_next,
NULL, NULL, NULL, NULL, NULL
};
static FT_CMap_Class const fnt_cmap_class = &fnt_cmap_class_rec;
static void
FNT_Face_Done( FT_Face fntface ) /* FNT_Face */
{
FNT_Face face = (FNT_Face)fntface;
FT_Memory memory;
if ( !face )
return;
memory = FT_FACE_MEMORY( face );
fnt_font_done( face );
FT_FREE( fntface->available_sizes );
fntface->num_fixed_sizes = 0;
}
static FT_Error
FNT_Face_Init( FT_Stream stream,
FT_Face fntface, /* FNT_Face */
FT_Int face_index,
FT_Int num_params,
FT_Parameter* params )
{
FNT_Face face = (FNT_Face)fntface;
FT_Error error;
FT_Memory memory = FT_FACE_MEMORY( face );
FT_UNUSED( num_params );
FT_UNUSED( params );
FT_TRACE2(( "Windows FNT driver\n" ));
/* try to load font from a DLL */
error = fnt_face_get_dll_font( face, face_index );
if ( !error && face_index < 0 )
goto Exit;
if ( FT_ERR_EQ( error, Unknown_File_Format ) )
{
/* this didn't work; try to load a single FNT font */
FNT_Font font;
if ( FT_NEW( face->font ) )
goto Exit;
fntface->num_faces = 1;
font = face->font;
font->offset = 0;
font->fnt_size = stream->size;
error = fnt_font_load( font, stream );
if ( !error )
{
if ( face_index > 0 )
error = FT_THROW( Invalid_Argument );
else if ( face_index < 0 )
goto Exit;
}
}
if ( error )
goto Fail;
/* we now need to fill the root FT_Face fields */
/* with relevant information */
{
FT_Face root = FT_FACE( face );
FNT_Font font = face->font;
FT_PtrDist family_size;
root->face_index = face_index;
root->face_flags |= FT_FACE_FLAG_FIXED_SIZES |
FT_FACE_FLAG_HORIZONTAL;
if ( font->header.avg_width == font->header.max_width )
root->face_flags |= FT_FACE_FLAG_FIXED_WIDTH;
if ( font->header.italic )
root->style_flags |= FT_STYLE_FLAG_ITALIC;
if ( font->header.weight >= 800 )
root->style_flags |= FT_STYLE_FLAG_BOLD;
/* set up the `fixed_sizes' array */
if ( FT_NEW_ARRAY( root->available_sizes, 1 ) )
goto Fail;
root->num_fixed_sizes = 1;
{
FT_Bitmap_Size* bsize = root->available_sizes;
FT_UShort x_res, y_res;
bsize->width = font->header.avg_width;
bsize->height = (FT_Short)(
font->header.pixel_height + font->header.external_leading );
bsize->size = font->header.nominal_point_size << 6;
x_res = font->header.horizontal_resolution;
if ( !x_res )
x_res = 72;
y_res = font->header.vertical_resolution;
if ( !y_res )
y_res = 72;
bsize->y_ppem = FT_MulDiv( bsize->size, y_res, 72 );
bsize->y_ppem = FT_PIX_ROUND( bsize->y_ppem );
/*
* this reads:
*
* the nominal height is larger than the bbox's height
*
* => nominal_point_size contains incorrect value;
* use pixel_height as the nominal height
*/
if ( bsize->y_ppem > ( font->header.pixel_height << 6 ) )
{
FT_TRACE2(( "use pixel_height as the nominal height\n" ));
bsize->y_ppem = font->header.pixel_height << 6;
bsize->size = FT_MulDiv( bsize->y_ppem, 72, y_res );
}
bsize->x_ppem = FT_MulDiv( bsize->size, x_res, 72 );
bsize->x_ppem = FT_PIX_ROUND( bsize->x_ppem );
}
{
FT_CharMapRec charmap;
charmap.encoding = FT_ENCODING_NONE;
/* initial platform/encoding should indicate unset status? */
charmap.platform_id = TT_PLATFORM_APPLE_UNICODE;
charmap.encoding_id = TT_APPLE_ID_DEFAULT;
charmap.face = root;
if ( font->header.charset == FT_WinFNT_ID_MAC )
{
charmap.encoding = FT_ENCODING_APPLE_ROMAN;
charmap.platform_id = TT_PLATFORM_MACINTOSH;
/* charmap.encoding_id = TT_MAC_ID_ROMAN; */
}
error = FT_CMap_New( fnt_cmap_class,
NULL,
&charmap,
NULL );
if ( error )
goto Fail;
/* Select default charmap */
if ( root->num_charmaps )
root->charmap = root->charmaps[0];
}
/* set up remaining flags */
if ( font->header.last_char < font->header.first_char )
{
FT_TRACE2(( "invalid number of glyphs\n" ));
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
/* reserve one slot for the .notdef glyph at index 0 */
root->num_glyphs = font->header.last_char -
font->header.first_char + 1 + 1;
if ( font->header.face_name_offset >= font->header.file_size )
{
FT_TRACE2(( "invalid family name offset\n" ));
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
family_size = font->header.file_size - font->header.face_name_offset;
/* Some broken fonts don't delimit the face name with a final */
/* NULL byte -- the frame is erroneously one byte too small. */
/* We thus allocate one more byte, setting it explicitly to */
/* zero. */
if ( FT_ALLOC( font->family_name, family_size + 1 ) )
goto Fail;
FT_MEM_COPY( font->family_name,
font->fnt_frame + font->header.face_name_offset,
family_size );
font->family_name[family_size] = '\0';
if ( FT_REALLOC( font->family_name,
family_size,
ft_strlen( font->family_name ) + 1 ) )
goto Fail;
root->family_name = font->family_name;
root->style_name = (char *)"Regular";
if ( root->style_flags & FT_STYLE_FLAG_BOLD )
{
if ( root->style_flags & FT_STYLE_FLAG_ITALIC )
root->style_name = (char *)"Bold Italic";
else
root->style_name = (char *)"Bold";
}
else if ( root->style_flags & FT_STYLE_FLAG_ITALIC )
root->style_name = (char *)"Italic";
}
goto Exit;
Fail:
FNT_Face_Done( fntface );
Exit:
return error;
}
static FT_Error
FNT_Size_Select( FT_Size size,
FT_ULong strike_index )
{
FNT_Face face = (FNT_Face)size->face;
FT_WinFNT_Header header = &face->font->header;
FT_UNUSED( strike_index );
FT_Select_Metrics( size->face, 0 );
size->metrics.ascender = header->ascent * 64;
size->metrics.descender = -( header->pixel_height -
header->ascent ) * 64;
size->metrics.max_advance = header->max_width * 64;
return FT_Err_Ok;
}
static FT_Error
FNT_Size_Request( FT_Size size,
FT_Size_Request req )
{
FNT_Face face = (FNT_Face)size->face;
FT_WinFNT_Header header = &face->font->header;
FT_Bitmap_Size* bsize = size->face->available_sizes;
FT_Error error = FT_ERR( Invalid_Pixel_Size );
FT_Long height;
height = FT_REQUEST_HEIGHT( req );
height = ( height + 32 ) >> 6;
switch ( req->type )
{
case FT_SIZE_REQUEST_TYPE_NOMINAL:
if ( height == ( ( bsize->y_ppem + 32 ) >> 6 ) )
error = FT_Err_Ok;
break;
case FT_SIZE_REQUEST_TYPE_REAL_DIM:
if ( height == header->pixel_height )
error = FT_Err_Ok;
break;
default:
error = FT_THROW( Unimplemented_Feature );
break;
}
if ( error )
return error;
else
return FNT_Size_Select( size, 0 );
}
static FT_Error
FNT_Load_Glyph( FT_GlyphSlot slot,
FT_Size size,
FT_UInt glyph_index,
FT_Int32 load_flags )
{
FNT_Face face = (FNT_Face)FT_SIZE_FACE( size );
FNT_Font font;
FT_Error error = FT_Err_Ok;
FT_Byte* p;
FT_Int len;
FT_Bitmap* bitmap = &slot->bitmap;
FT_ULong offset;
FT_Bool new_format;
FT_UNUSED( load_flags );
if ( !face )
{
error = FT_THROW( Invalid_Argument );
goto Exit;
}
font = face->font;
if ( !font ||
glyph_index >= (FT_UInt)( FT_FACE( face )->num_glyphs ) )
{
error = FT_THROW( Invalid_Argument );
goto Exit;
}
FT_TRACE1(( "FNT_Load_Glyph: glyph index %d\n", glyph_index ));
if ( glyph_index > 0 )
glyph_index--; /* revert to real index */
else
glyph_index = font->header.default_char; /* the `.notdef' glyph */
new_format = FT_BOOL( font->header.version == 0x300 );
len = new_format ? 6 : 4;
/* get glyph width and offset */
offset = ( new_format ? 148 : 118 ) + len * glyph_index;
if ( offset >= font->header.file_size - 2 - ( new_format ? 4 : 2 ) )
{
FT_TRACE2(( "invalid FNT offset\n" ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
p = font->fnt_frame + offset;
bitmap->width = FT_NEXT_SHORT_LE( p );
/* jump to glyph entry */
if ( new_format )
offset = FT_NEXT_ULONG_LE( p );
else
offset = FT_NEXT_USHORT_LE( p );
if ( offset >= font->header.file_size )
{
FT_TRACE2(( "invalid FNT offset\n" ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
/* jump to glyph data */
p = font->fnt_frame + /* font->header.bits_offset */ + offset;
/* allocate and build bitmap */
{
FT_Memory memory = FT_FACE_MEMORY( slot->face );
FT_Int pitch = ( bitmap->width + 7 ) >> 3;
FT_Byte* column;
FT_Byte* write;
bitmap->pitch = pitch;
bitmap->rows = font->header.pixel_height;
bitmap->pixel_mode = FT_PIXEL_MODE_MONO;
if ( offset + pitch * bitmap->rows > font->header.file_size )
{
FT_TRACE2(( "invalid bitmap width\n" ));
error = FT_THROW( Invalid_File_Format );
goto Exit;
}
/* note: since glyphs are stored in columns and not in rows we */
/* can't use ft_glyphslot_set_bitmap */
if ( FT_ALLOC_MULT( bitmap->buffer, pitch, bitmap->rows ) )
goto Exit;
column = (FT_Byte*)bitmap->buffer;
for ( ; pitch > 0; pitch--, column++ )
{
FT_Byte* limit = p + bitmap->rows;
for ( write = column; p < limit; p++, write += bitmap->pitch )
*write = *p;
}
}
slot->internal->flags = FT_GLYPH_OWN_BITMAP;
slot->bitmap_left = 0;
slot->bitmap_top = font->header.ascent;
slot->format = FT_GLYPH_FORMAT_BITMAP;
/* now set up metrics */
slot->metrics.width = bitmap->width << 6;
slot->metrics.height = bitmap->rows << 6;
slot->metrics.horiAdvance = bitmap->width << 6;
slot->metrics.horiBearingX = 0;
slot->metrics.horiBearingY = slot->bitmap_top << 6;
ft_synthesize_vertical_metrics( &slot->metrics,
bitmap->rows << 6 );
Exit:
return error;
}
static FT_Error
winfnt_get_header( FT_Face face,
FT_WinFNT_HeaderRec *aheader )
{
FNT_Font font = ((FNT_Face)face)->font;
*aheader = font->header;
return 0;
}
static const FT_Service_WinFntRec winfnt_service_rec =
{
winfnt_get_header
};
/*
* SERVICE LIST
*
*/
static const FT_ServiceDescRec winfnt_services[] =
{
{ FT_SERVICE_ID_XF86_NAME, FT_XF86_FORMAT_WINFNT },
{ FT_SERVICE_ID_WINFNT, &winfnt_service_rec },
{ NULL, NULL }
};
static FT_Module_Interface
winfnt_get_service( FT_Module module,
const FT_String* service_id )
{
FT_UNUSED( module );
return ft_service_list_lookup( winfnt_services, service_id );
}
FT_CALLBACK_TABLE_DEF
const FT_Driver_ClassRec winfnt_driver_class =
{
{
FT_MODULE_FONT_DRIVER |
FT_MODULE_DRIVER_NO_OUTLINES,
sizeof ( FT_DriverRec ),
"winfonts",
0x10000L,
0x20000L,
0,
0, /* FT_Module_Constructor */
0, /* FT_Module_Destructor */
winfnt_get_service
},
sizeof ( FNT_FaceRec ),
sizeof ( FT_SizeRec ),
sizeof ( FT_GlyphSlotRec ),
FNT_Face_Init,
FNT_Face_Done,
0, /* FT_Size_InitFunc */
0, /* FT_Size_DoneFunc */
0, /* FT_Slot_InitFunc */
0, /* FT_Slot_DoneFunc */
FNT_Load_Glyph,
0, /* FT_Face_GetKerningFunc */
0, /* FT_Face_AttachFunc */
0, /* FT_Face_GetAdvancesFunc */
FNT_Size_Request,
FNT_Size_Select
};
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/winfonts/winfnt.c | C | apache-2.0 | 34,148 |
/***************************************************************************/
/* */
/* winfnt.h */
/* */
/* FreeType font driver for Windows FNT/FON files */
/* */
/* Copyright 1996-2001, 2002, 2003, 2004, 2007 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* Copyright 2007 Dmitry Timoshkov for Codeweavers */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
#ifndef __WINFNT_H__
#define __WINFNT_H__
#include <ft2build.h>
#include FT_WINFONTS_H
#include FT_INTERNAL_DRIVER_H
FT_BEGIN_HEADER
#ifdef FT_CONFIG_OPTION_PIC
#error "this module does not support PIC yet"
#endif
typedef struct WinMZ_HeaderRec_
{
FT_UShort magic;
/* skipped content */
FT_UShort lfanew;
} WinMZ_HeaderRec;
typedef struct WinNE_HeaderRec_
{
FT_UShort magic;
/* skipped content */
FT_UShort resource_tab_offset;
FT_UShort rname_tab_offset;
} WinNE_HeaderRec;
typedef struct WinPE32_HeaderRec_
{
FT_ULong magic;
FT_UShort machine;
FT_UShort number_of_sections;
/* skipped content */
FT_UShort size_of_optional_header;
/* skipped content */
FT_UShort magic32;
/* skipped content */
FT_ULong rsrc_virtual_address;
FT_ULong rsrc_size;
/* skipped content */
} WinPE32_HeaderRec;
typedef struct WinPE32_SectionRec_
{
FT_Byte name[8];
/* skipped content */
FT_ULong virtual_address;
FT_ULong size_of_raw_data;
FT_ULong pointer_to_raw_data;
/* skipped content */
} WinPE32_SectionRec;
typedef struct WinPE_RsrcDirRec_
{
FT_ULong characteristics;
FT_ULong time_date_stamp;
FT_UShort major_version;
FT_UShort minor_version;
FT_UShort number_of_named_entries;
FT_UShort number_of_id_entries;
} WinPE_RsrcDirRec;
typedef struct WinPE_RsrcDirEntryRec_
{
FT_ULong name;
FT_ULong offset;
} WinPE_RsrcDirEntryRec;
typedef struct WinPE_RsrcDataEntryRec_
{
FT_ULong offset_to_data;
FT_ULong size;
FT_ULong code_page;
FT_ULong reserved;
} WinPE_RsrcDataEntryRec;
typedef struct WinNameInfoRec_
{
FT_UShort offset;
FT_UShort length;
FT_UShort flags;
FT_UShort id;
FT_UShort handle;
FT_UShort usage;
} WinNameInfoRec;
typedef struct WinResourceInfoRec_
{
FT_UShort type_id;
FT_UShort count;
} WinResourceInfoRec;
#define WINFNT_MZ_MAGIC 0x5A4D
#define WINFNT_NE_MAGIC 0x454E
#define WINFNT_PE_MAGIC 0x4550
typedef struct FNT_FontRec_
{
FT_ULong offset;
FT_WinFNT_HeaderRec header;
FT_Byte* fnt_frame;
FT_ULong fnt_size;
FT_String* family_name;
} FNT_FontRec, *FNT_Font;
typedef struct FNT_FaceRec_
{
FT_FaceRec root;
FNT_Font font;
FT_CharMap charmap_handle;
FT_CharMapRec charmap; /* a single charmap per face */
} FNT_FaceRec, *FNT_Face;
FT_EXPORT_VAR( const FT_Driver_ClassRec ) winfnt_driver_class;
FT_END_HEADER
#endif /* __WINFNT_H__ */
/* END */
| YifuLiu/AliOS-Things | components/freetype/src/winfonts/winfnt.h | C | apache-2.0 | 4,026 |
#ifndef __GENIE_ADDR_H__
#define __GENIE_ADDR_H__
typedef enum _genie_addr
{
GENIE_ADDR_MIN = 0xc000,
GENIE_ADDR_LIGHT = 0xc000,
GENIE_ADDR_SWITCH = 0xc001,
GENIE_ADDR_SOCKET = 0xc002,
GENIE_ADDR_CURTAIN = 0xc003,
GENIE_ADDR_BODY_SCALE = 0xc004,
GENIE_ADDR_BUTTON = 0xc005,
GENIE_ADDR_MAX = 0xcfff
} genie_addr_e;
#endif
| YifuLiu/AliOS-Things | components/genie_service/core/inc/genie_addr.h | C | apache-2.0 | 356 |
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#ifndef __GENIE_AIS_H__
#define __GENIE_AIS_H__
#include <misc/byteorder.h>
#include <bluetooth/gatt.h>
#define AIS_DISCONNECT_TIMEOUT 1000 //1s
#define AIS_SERVICE_UUID BT_UUID_DECLARE_16(0xFEB3)
#define AIS_READ_UUID BT_UUID_DECLARE_16(0xFED4)
#define AIS_WRITE_UUID BT_UUID_DECLARE_16(0xFED5)
#define AIS_INDICATE_UUID BT_UUID_DECLARE_16(0xFED6)
#define AIS_WRITE_WO_RESP_UUID BT_UUID_DECLARE_16(0xFED7)
#define AIS_NOTIFY_UUID BT_UUID_DECLARE_16(0xFED8)
enum
{
AIS_STATE_DISCON,
AIS_STATE_CONNECT,
AIS_STATE_AUTH,
AIS_STATE_IDLE,
AIS_STATE_OTA,
AIS_STATE_REBOOT,
};
enum
{
AIS_RESP_ERR = 0x0F,
AIS_SCRT_RANDOM = 0x10,
AIS_SCRT_CIPHER = 0x11,
AIS_SCRT_RESULT = 0x12,
AIS_SCRT_ACK = 0x13,
AIS_LINK_STATUS = 0x14,
AIS_LINK_ACK = 0x15,
};
//AIS PDU FORMAT
typedef struct
{
uint8_t msg_id : 4;
uint8_t enc : 1;
uint8_t ver : 3;
uint8_t cmd;
uint8_t seq : 4;
uint8_t total_frame : 4;
uint8_t payload_len;
} __attribute__((packed)) ais_header_t;
typedef struct
{
uint8_t random[16];
} __attribute__((packed)) ais_scrt_random_t;
typedef struct
{
uint8_t cipher[16];
} __attribute__((packed)) ais_scrt_cipher_t;
typedef struct
{
uint8_t result;
} __attribute__((packed)) ais_scrt_result_t;
typedef struct
{
uint8_t ack;
} __attribute__((packed)) ais_scrt_ack_t;
typedef struct
{
ais_header_t header;
uint8_t payload[16];
} __attribute__((packed)) ais_pdu_t;
typedef struct _genie_ais_ctx_s
{
uint8_t state;
struct bt_conn *p_conn;
k_timer_t state_update_timer;
k_timer_t disconnect_timer;
} genie_ais_ctx_t;
/**
* @brief the ais service action when gatt is connected.
* @param[in] the handle of connect.
*/
void genie_ais_connect(struct bt_conn *p_conn);
/**
* @brief the ais service action when gatt is disconnected.
* @param[in] the disconnect reason.
*/
void genie_ais_disconnect(uint8_t reason);
/**
* @brief regist the ais service.
* @return the result of registion.
*/
int genie_ais_init(void);
int genie_ais_pre_init(void);
int genie_ais_state_set(uint8_t state);
uint8_t genie_ais_state_get(void);
void genie_ais_notify(uint8_t msg_id, uint8_t cmd, uint8_t *p_msg, uint16_t len);
#endif
| YifuLiu/AliOS-Things | components/genie_service/core/inc/genie_ais.h | C | apache-2.0 | 2,304 |
/*
* Copyright (C) 2018-2020 Alibaba Group Holding Limited
*/
#ifndef __GENIE_AT_H__
#define __GENIE_AT_H__
typedef enum
{
AT_CMD_NO_ADD = 0x1,
AT_CMD_ADD = 0x2,
AT_CMD_QUERY = 0x4,
AT_CMD_DOU = 0x8,
AT_CMD_FIND = 0x10,
} AT_CMD_TYPE_e;
typedef enum
{
AT_OP_EXECUTE = 0x1,
AT_OP_FCURRENT = 0x2,
AT_OP_HLOOKUP = 0x3,
AT_OP_HELP = 0x4,
} AT_OP_CODE_e;
typedef enum
{
AT_ERR_NOT_FOUND = -1,
AT_ERR_FORMAT = -2,
AT_ERR_EXE = -3,
} AT_OP_ERROR_e;
typedef enum
{
MESH_TEST_RSSI = 0x00,
} MESH_TEST_OP_CODE_e;
typedef enum
{
MESH_EVENT_PROV_SUCCESS = 0x00,
MESH_EVENT_PROV_FAILED = 0x05,
MESH_EVENT_DEV_READY = 0x04,
MESH_EVENT_UNKNOW = 0xFF,
} MESH_EVENT_VAL_e;
typedef enum
{
MESH_ADV_CLOSE = 0x00,
MESH_ADV_START = 0x01,
MESH_ADV_SILENT = 0x02,
} MESH_ADV_TYPE_e;
typedef int (*at_cmd_function_t)(int argc, char *argv[]);
typedef struct at_cmd_s
{
const char *cmd_name;
at_cmd_function_t cb;
const char *help;
at_cmd_function_t fcb;
} at_cmd_t;
#define AT_MAX_ARGC 10
#define AT_MAX_ARGV_LEN 32
#define AT_CME_ERROR_STR "+ERROR:%d\r\n"
#define AT_RESPONSE_STR "+%s:"
#define AT_OK_STR "OK\r\n"
// control cmd
#define BLE_MESH_ADV "MESHADV" // start adv
#define BLE_MESH_REBOOT "REBOOT" // reboot
#define BLE_MESH_RESET "MESHRST" // mesh reset
#define BLE_MESH_INFO "MESHINF" // mesh info
#define BLE_MESH_VER "MESHVER" // mesh version
#define BLE_MESH_TEST "MESHTEST" // mesh test
#define BLE_MESH_GROUP "MESHGRP" // mesh group
#define BLE_MESH_MSG_TX "MESHMSGTX" // mesh trans msg send
#define BLE_MESH_MAC "MESHMAC" // mesh MAC
#define BLE_MESH_FACTY_TEST "FACTYTEST" // factory test
#define BLE_MESH_LOG "MESHLOG" // mesh log
//event
#define BLE_MESH_EVENT "MESHEVT" // mesh event
#define BLE_MESH_MSG_RX "MESHMSGRX" // mesh trans msg recv
int genie_at_cmd_reboot(int argc, char *argv[]);
int genie_at_cmd_adv_start(int argc, char *argv[]);
int genie_at_cmd_adv_query(int argc, char *argv[]);
int genie_at_cmd_mesh_reset(int argc, char *argv[]);
int genie_at_cmd_mesh_info(int argc, char *argv[]);
int genie_at_cmd_mesh_ver(int argc, char *argv[]);
int genie_at_cmd_mesh_mac(int argc, char *argv[]);
int genie_at_cmd_facty_test(int argc, char *argv[]);
int genie_at_cmd_mesh_test(int argc, char *argv[]);
int genie_at_cmd_mesh_group(int argc, char *argv[]);
int genie_at_cmd_mesh_group_query(int argc, char *argv[]);
int genie_at_cmd_mesh_trans_send(int argc, char *argv[]);
int genie_at_cmd_mesh_log(int argc, char *argv[]);
int genie_at_cmd_mesh_log_query(int argc, char *argv[]);
int genie_at_output_event(genie_event_e event, void *p_arg);
int genie_at_cmd_send_data_to_mcu(uint8_t *p_data, uint16_t data_len);
#endif /*--_GENIE_AT_CMDS_H_--*/
| YifuLiu/AliOS-Things | components/genie_service/core/inc/genie_at.h | C | apache-2.0 | 2,839 |
#ifndef __GENIE_BIN_CMDS_H__
#define __GENIE_BIN_CMDS_H__
#define GENIE_BIN_OPCODE_DATA (0xFF00)
#define GENIE_BIN_OPCODE_CMD (0xFE00)
#define GENIE_BIN_OPCODE_ERR (0x5555)
#define GENIE_BIN_MIN_DATA_LEN (5)
#define GENIE_BLE_MAC_LEN (6)
#define GENIE_BINARY_CMD_TOTAL_LEN_ERR (0x01)
#define GENIE_BINARY_CMD_DATA_LEN_ERR (0x02)
#define GENIE_BINARY_CMD_CRC_ERR (0x03)
#define GENIE_BINARY_CMD_GET_RSSI_INPUT_ERR (0x04)
#define GENIE_BINARY_CMD_GET_RSSI_BLE_ERR (0x05)
#define GENIE_BINARY_CMD_GET_RSSI_MAC_NOT_MATCH_ERR (0x06)
#define GENIE_BINARY_CMD_UPDATE_GROUP_ADDR_LEN_ERR (0x07)
#define GENIE_BINARY_CMD_UPDATE_GROUP_ADDR_INVALID_ERR (0x08)
#define GENIE_BINARY_CMD_UPDATE_GROUP_ADDR_FLASH_ERR (0x09)
#define GENIE_BINARY_CMD_START_FACTORY_ERR (0x0A)
#define GENIE_BINARY_CMD_TRANSPARENT_ERR (0x80)
#define GENIE_BINARY_CMD_UNKNOW_ERR (0xFF)
typedef enum _genie_control_cmd
{
GENIE_CTL_MESH_ADV = 0x01,
GENIE_CTL_CLEAR_PROV_INFO = 0x02,
GENIE_CTL_DEVIE_INFO_AND_EVENT = 0x03, //This is device update info
GENIE_CTL_TEST_MODE = 0x04,
GENIE_CTL_DEVICE_INFO = 0x05, //This is MCU command
GENIE_CTL_REBOOT_DEVICE = 0x06,
GENIE_CTL_UPDATE_GROUP_ADDR = 0x07,
GENIE_CTL_UPDATE_GROUP_ADDR_RESPONSE = 0x08,
GENIE_CTL_GET_GROUP_ADDR = 0x09,
GENIE_CTL_GET_GOURP_ADDR_RESPONSE = 0x0A,
GENIE_CTL_FACTORY_TEST = 0x0B,
GENIE_CTL_SWITCH_DEBUG = 0x0C
} genie_control_cmd;
extern int genie_bin_cmd_handle_event(genie_event_e event, void *p_arg);
extern void genie_bin_cmds_send_data_to_mcu(uint8_t *p_data, uint8_t len);
#endif
| YifuLiu/AliOS-Things | components/genie_service/core/inc/genie_bin_cmds.h | C | apache-2.0 | 1,573 |
/*
* Copyright (C) 2018-2020 Alibaba Group Holding Limited
*/
#ifndef __GENIE_CLI_H__
#define __GENIE_CLI_H__
#define CUSTOM_SN_LEN (23)
/**
* @brief initialize the command tool for debugging.
*/
void genie_cli_init(void);
#endif
| YifuLiu/AliOS-Things | components/genie_service/core/inc/genie_cli.h | C | apache-2.0 | 238 |
#ifndef __GENIE_CRYPTO_H__
#define __GENIE_CRYPTO_H__
#define GENIE_CRYPTO_UNIT_SIZE (16)
#define STATIC_OOB_LENGTH 16
/**
* @brief get the authentication info
* @param[in] random: the random sequence used for calculating.
* @return the authenticated sequence
*/
uint8_t *genie_crypto_get_auth(const uint8_t random[16]);
/**
* @brief encrypt ais data.
* @param[in] raw data
* @param[out] encryped data
*/
int genie_crypto_encrypt(const uint8_t data_in[16], uint8_t data_out[16]);
/**
* @brief decrypt ais data.
* @param[in] encryped data
* @param[out] raw data
*/
int genie_crypto_decrypt(const uint8_t data_in[16], uint8_t data_out[16]);
/**
* @brief get the cipher for ble auth.
* @param[in] random, 16 Byte
* @param[out] cipher, 1 6Byte
*/
void genie_ais_get_cipher(const uint8_t random[16], uint8_t *cipher);
/**
* @brief clear the keys of ais service.
*/
void genie_ais_reset(void);
/**
* @brief init the ais advertising.
* @param[inout] the phoint of advertising data
* @param[in] is silent adv or not
*/
void genie_crypto_adv_create(uint8_t ad_structure[14], uint8_t is_silent);
#endif
| YifuLiu/AliOS-Things | components/genie_service/core/inc/genie_crypto.h | C | apache-2.0 | 1,124 |
/*
* Copyright (C) 2018-2020 Alibaba Group Holding Limited
*/
#ifndef __GENIE_EVENT_H__
#define __GENIE_EVENT_H__
#include <stdint.h>
#include <stdbool.h>
#ifndef GENIE_PROV_SUCCESS_REPORT_TIMEOUT
#define GENIE_PROV_SUCCESS_REPORT_TIMEOUT 30
#endif
typedef enum
{
GENIE_EVT_NONE = 0,
GENIE_EVT_SW_RESET, /* triggered from cloud */
GENIE_EVT_HW_RESET_START, /* triggered from user */
GENIE_EVT_BT_READY,
GENIE_EVT_MESH_READY, // Used to sync device's state with cloud
GENIE_EVT_SDK_AIS_DISCON = 10,
GENIE_EVT_SDK_AIS_CONNECT,
GENIE_EVT_SDK_MESH_PBADV_START,
GENIE_EVT_SDK_MESH_PBADV_TIMEOUT,
GENIE_EVT_SDK_MESH_SILENT_START,
GENIE_EVT_SDK_MESH_PROV_START = 20,
GENIE_EVT_SDK_MESH_PROV_DATA,
GENIE_EVT_SDK_MESH_PROV_TIMEOUT,
GENIE_EVT_SDK_MESH_PROV_SUCCESS,
GENIE_EVT_SDK_MESH_PROV_FAIL,
GENIE_EVT_SDK_APPKEY_ADD = 30,
GENIE_EVT_SDK_APPKEY_DEL,
GENIE_EVT_SDK_APPKEY_UPDATE,
GENIE_EVT_SDK_NETKEY_ADD,
GENIE_EVT_SDK_NETKEY_DEL,
GENIE_EVT_SDK_NETKEY_UPDATE,
GENIE_EVT_SDK_HB_SET = 40,
#ifdef CONFIG_BT_MESH_CTRL_RELAY
GENIE_EVT_SDK_CTRL_RELAY_SET,
#endif
GENIE_EVT_SDK_SEQ_UPDATE,
GENIE_EVT_TIMEOUT = 50,
GENIE_EVT_DOWN_MSG,
GENIE_EVT_VENDOR_MODEL_MSG,
GENIE_EVT_SIG_MODEL_MSG,
GENIE_EVT_USER_TRANS_CYCLE,
GENIE_EVT_USER_ACTION_DONE
} genie_event_e;
typedef enum _genie_down_mesg_type
{
GENIE_DOWN_MESG_VENDOR_TYPE = 0,
GENIE_DOWN_MESG_SIG_TYPE
} genie_down_mesg_type;
typedef struct _sig_model_msg
{
uint8_t element_id;
uint16_t opcode;
uint16_t len;
uint8_t *data;
} sig_model_msg;
typedef struct _genie_down_msg_s
{
uint8_t element_id;
uint16_t len;
uint8_t *data;
} genie_down_msg_t;
/**
* @brief The handler for the underlying events. If necessary
* this handler dispatch the user events to applications.
* @param[in] event refers to the event details.
* @param[in] args refers to the additional information for the event.
*/
void genie_event(genie_event_e event, void *args);
int genie_down_msg(genie_down_mesg_type msg_type, uint32_t opcode, void *p_msg);
#endif
| YifuLiu/AliOS-Things | components/genie_service/core/inc/genie_event.h | C | apache-2.0 | 2,156 |
/*
* Copyright (C) 2018-2020 Alibaba Group Holding Limited
*/
#ifndef __GENIE_LPM_H__
#define __GENIE_LPM_H__
#define INTERRUPT_DELAY_TIME (50) //For debounce
#define DEFAULT_BOOTUP_DELAY_SLEEP_TIME (10000) //Unit:ms
#define PWR_STANDBY_BOOT_FLAG (0x1688)
#define PWR_BOOT_REASON (0x4000f034)
typedef enum _genie_lpm_status_e
{
STATUS_WAKEUP,
STATUS_SLEEP
} genie_lpm_status_e;
typedef enum _genie_lpm_wakeup_reason_e
{
WAKEUP_BY_IO,
WAKEUP_BY_TIMER,
WAKEUP_IS_WAKEUP
} genie_lpm_wakeup_reason_e;
typedef void (*genie_lpm_cb_t)(genie_lpm_wakeup_reason_e reason, genie_lpm_status_e status, void* arg);
typedef struct _genie_lpm_wakeup_io_config_s {
uint8_t port;
uint8_t io_pol;
}genie_lpm_wakeup_io_config_t;
#define GENIE_WAKEUP_PIN(_port, _pol) \
{ \
.port = (_port), \
.io_pol = (_pol), \
}
typedef struct _genie_lpm_wakeup_io_s {
uint8_t io_list_size;
genie_lpm_wakeup_io_config_t* io_config;
} genie_lpm_wakeup_io_t;
typedef struct _genie_lpm_io_status_s {
uint8_t port;
uint8_t trigger_flag;
uint8_t status;
}_genie_lpm_io_status_t;
typedef struct _genie_lpm_io_status_list_s {
_genie_lpm_io_status_t *io_status;
uint8_t size;
}_genie_lpm_io_status_list_t;
typedef struct _genie_lpm_conf_s
{
uint8_t lpm_wakeup_io; //0:then not wakeup by GPIO
genie_lpm_wakeup_io_t lpm_wakeup_io_config; //wakeup IO list config
uint8_t is_auto_enable; //1:auto enter sleep mode when bootup
uint32_t delay_sleep_time; //if auto enter sleep,delay some time then enter sleep mode
uint16_t sleep_ms; //sleep time
uint16_t wakeup_ms; //wakeup time
genie_lpm_cb_t genie_lpm_cb; //User callback
} genie_lpm_conf_t;
typedef struct _genie_lpm_ctx_s
{
genie_lpm_conf_t p_config;
uint8_t status;
uint8_t is_mesh_init;
uint8_t has_disabled;
aos_timer_t wakeup_timer;
aos_timer_t io_wakeup_timer;
aos_mutex_t mutex;
long long last_interrupt_time;
} genie_lpm_ctx_t;
void genie_lpm_init(genie_lpm_conf_t *lpm_conf);
int genie_lpm_start(void);
void genie_lpm_io_wakeup_handler(void *arg);
int genie_lpm_enable(bool force);
int genie_lpm_disable(void);
int genie_lpm_deep_sleep(void);
bool genie_lpm_get_wakeup_io_status(void);
#endif
| YifuLiu/AliOS-Things | components/genie_service/core/inc/genie_lpm.h | C | apache-2.0 | 2,299 |
/*
* Copyright (C) 2018-2020 Alibaba Group Holding Limited
*/
#ifndef __GENIE_MESH_H__
#define __GENIE_MESH_H__
#include <stddef.h>
#include <net/buf.h>
#include <mesh/access.h>
#include <mesh/main.h>
#include <mesh/cfg_srv.h>
#include <mesh/health_srv.h>
#include "genie_service.h"
#define CONFIG_MESH_VENDOR_COMPANY_ID (0x01A8)
#define CONFIG_MESH_VENDOR_MODEL_SRV 0x0000
#define CONFIG_MESH_VENDOR_MODEL_CLI 0x0001
#define GENIE_MESH_INIT_PHARSE_II_HW_RESET_DELAY (2000) //Unit:ms
#define GENIE_MESH_INIT_PHARSE_II_DELAY_START_MIN (1000) //Unit:ms
#define GENIE_MESH_INIT_PHARSE_II_DELAY_START_MAX (10 * 1000) //Unit:ms
#define GENIE_MESH_INIT_PHARSE_II_CHECK_APPKEY_INTERVAL (1000) //Unit:ms
#define GENIE_MESH_INIT_PHARSE_II_CHECK_APPKEY_TIMEOUT (30 * GENIE_MESH_INIT_PHARSE_II_CHECK_APPKEY_INTERVAL) //Unit:ms
#define ALI_MODEL_TAG "\t[ALI_MODEL]"
#define MODEL_D(f, ...) printf("%d " ALI_MODEL_TAG "[D] %s " f "\n", (bt_u32_t)aos_now_ms(), __func__, ##__VA_ARGS__)
#define MODEL_I(f, ...) printf(ALI_MODEL_TAG "[I] %s " f "\n", __func__, ##__VA_ARGS__)
#define MODEL_E(f, ...) printf(ALI_MODEL_TAG "[E] %s " f "\n", __func__, ##__VA_ARGS__)
typedef enum _genie_mesh_init_state_e
{
GENIE_MESH_INIT_STATE_PROVISION = 1,
GENIE_MESH_INIT_STATE_HW_RESET,
GENIE_MESH_INIT_STATE_NORMAL_BOOT,
} genie_mesh_init_state_e;
#if 0
typedef enum _genie_mesh_work_type_e
{
GENIE_MESH_WORK_TYPE_INVALID,
GENIE_MESH_WORK_TYPE_HW_RESET,
GENIE_MESH_WORK_TYPE_READY,
GENIE_MESH_WORK_TYPE_PROV_TIMEOUT,
} genie_mesh_work_type_e;
#endif
struct bt_mesh_elem *genie_mesh_get_primary_element(void);
int genie_mesh_init(struct bt_mesh_elem *p_mesh_elem, unsigned int mesh_elem_counts);
int genie_mesh_init_pharse_ii(void);
void genie_mesh_ready_checktimer_restart(uint32_t timeout);
int genie_mesh_suspend(bool force);
int genie_mesh_resume(void);
void genie_mesh_load_group_addr(void);
#endif
| YifuLiu/AliOS-Things | components/genie_service/core/inc/genie_mesh.h | C | apache-2.0 | 1,981 |
#ifndef __GENIE_OTA_H__
#define __GENIE_OTA_H__
//For pingpong OTA
enum
{
DFU_IMAGE_A = 0,
DFU_IMAGE_B,
DFU_IMAGE_TOTAL = DFU_IMAGE_B,
DFU_IMAGE_INVALID_ID,
};
#define OTA_RECV_BUF_SIZE (CONFIG_AIS_TOTAL_FRAME * 128)
#define OTA_RECV_MAX_ERR_COUNT 10
#define GENIE_OTA_IMAGE_ID_MAGIC (0xA5A5A5)
#define GENIE_OTA_IMAGE_ID_A (GENIE_OTA_IMAGE_ID_MAGIC << 8 | DFU_IMAGE_A)
#define GENIE_OTA_IMAGE_ID_B (GENIE_OTA_IMAGE_ID_MAGIC << 8 | DFU_IMAGE_B)
#define AIS_OTA_AUTH_TIMEOUT 10000 //10s
#define AIS_OTA_DISCONN_TIMEOUT 60000 //60s
#define AIS_OTA_REPORT_TIMEOUT (CONFIG_AIS_TOTAL_FRAME * 400)
#define AIS_OTA_REBOOT_TIMEOUT 3000 //3s
enum
{
OTA_FLAG_SILENT = 0x02,
AIS_OTA_VER_REQ = 0x20, //APP request get version info
AIS_OTA_VER_RESP = 0x21, //Response the version info request
AIS_OTA_FIRMWARE_REQ = 0x22, //APP push firmware info
AIS_OTA_UPD_RESP = 0x23, //Response to APP which can update or not and have received firmware size
AIS_OTA_STATUS = 0x24, //Response to APP that last frame number and have received firmware size
AIS_OTA_CHECK_REQ = 0x25, //APP download finish,then device check firmware
AIS_OTA_CHECK_RESP = 0x26, //Response to APP the result of firmeware check
AIS_OTA_DATA = 0x2f //This is ota firmware data
};
typedef struct genie_ota_ctx_s
{
uint8_t err_count;
uint8_t last_seq;
uint8_t total_frame;
uint8_t except_seq;
uint32_t rx_size;
uint8_t image_type;
uint32_t image_ver;
uint32_t image_size;
uint16_t image_crc16;
uint8_t ota_flag;
uint8_t flash_clean : 1;
uint8_t ota_ready : 1;
uint16_t rx_len;
uint8_t recv_buf[OTA_RECV_BUF_SIZE];
} genie_ota_ctx_t;
typedef struct
{
uint8_t image_type;
} __attribute__((packed)) ais_ota_ver_req_t;
typedef struct
{
uint8_t image_type;
uint32_t ver;
} __attribute__((packed)) ais_ota_ver_resp_t;
typedef struct
{
uint8_t image_type;
uint32_t ver;
uint32_t fw_size;
uint16_t crc16;
uint8_t ota_flag;
} __attribute__((packed)) ais_ota_upd_req_t;
typedef struct
{
uint8_t state;
uint32_t rx_size;
uint8_t total_frame;
} __attribute__((packed)) ais_ota_upd_resp_t;
typedef struct
{
uint8_t last_seq : 4;
uint8_t total_frame : 4;
uint32_t rx_size;
} __attribute__((packed)) ais_ota_status_report_t;
typedef struct
{
uint8_t state;
} __attribute__((packed)) ais_ota_check_req_t;
typedef struct
{
uint8_t state;
} __attribute__((packed)) ais_ota_check_resp_t;
bool genie_ota_handle_update_request(uint8_t msg_id, ais_ota_upd_req_t *p_ota_req, uint8_t encrypt);
bool genie_ota_handle_version_request(uint8_t msg_id, ais_ota_ver_req_t *p_ver_req, uint8_t encrypt);
bool genie_ota_parse_pdu(ais_pdu_t *p_msg);
bool genie_ota_check_firmware(uint8_t msg_id, ais_ota_check_req_t *p_check_req);
bool genie_ota_is_ready(void);
/**
* @brief get the ota indication flag from flash.
* @return the ota indication flag.
*/
bool genie_ota_get_indication(void);
void genie_ota_status_report(void);
bool genie_ota_is_updating(void);
int genie_ota_report_version(void);
int genie_ota_init(void);
#endif
| YifuLiu/AliOS-Things | components/genie_service/core/inc/genie_ota.h | C | apache-2.0 | 3,181 |
#ifndef __GENIE_PROVISION_H__
#define __GENIE_PROVISION_H__
#include <stdint.h>
#include <genie_storage.h>
#define GENIE_PROVISON_UUID_LEN (16)
#define UNPROV_ADV_FEATURE1_UUID_VERSION 0x02
#define UNPROV_ADV_FEATURE1_SILENT_ADV 0x01
#define UNPROV_ADV_FEATURE1_SILENT_UNMASK 0xFE
#define UNPROV_ADV_FEATURE2_GENIE_MESH_STACK_V1 0x10 //bit4-7
#define UNPROV_ADV_FEATURE2_GENIE_MESH_STACK_V2 0x20 //bit4-7
#define UNPROV_ADV_FEATURE2_GENIE_MESH_STACK_V3 0x30 //bit4-7
#define UNPROV_ADV_FEATURE2_ULTRA_PROV_FLAG 0x01 //bit0
#define UNPROV_ADV_FEATURE2_AUTH_FLAG 0x02 //bit1
#define MESH_PROVISIONING_TIMEOUT 60 * 1000
typedef enum _genie_provision_state_e
{
GENIE_PROVISION_UNPROV,
GENIE_PROVISION_START,
GENIE_PROVISION_SUCCESS
} genie_provision_state_e;
typedef struct _genie_provision_s
{
uint16_t addr;
uint32_t seq;
uint8_t devkey[16];
mesh_netkey_para_t netkey;
mesh_appkey_para_t appkey;
} genie_provision_t;
/**
* @brief get the trituple info formatted in uuid
* @return the string refering to uuid
*/
uint8_t *genie_provision_get_uuid(void);
void genie_provision_clear_silent_flag(void);
int genie_provision_set_state(genie_provision_state_e state);
genie_provision_state_e genie_provision_get_state(void);
int genie_provision_get_saved_data(genie_provision_t *p_genie_provision);
#ifdef GENIE_ULTRA_PROV
#define GENIE_PROV_ADV_TYPE (0xFF)
#define GENIE_PROV_FIXED_BYTE (0x0D)
typedef enum _genie_prov_status_e
{
GENIE_PROV_STATUS_RECV_RANDOM,
GENIE_PROV_STATUS_SEND_CONFIRM_DATA,
GENIE_PROV_STATUS_RECV_PROV_DATA,
GENIE_PROV_STATUS_SEND_COMPLETED
} genie_prov_status_e;
void genie_provision_ultra_prov_free(void);
int genie_provision_ultra_prov_handle(uint8_t frame_type, void *frame_buf);
#endif
/**
* @brief
*/
void genie_provision_pbadv_timer_start(uint32_t prov_timeout);
/**
* @brief
*/
void genie_provision_pbadv_timer_stop(void);
/**
* @brief
*/
void genie_provision_prov_timer_start(void);
/**
* @brief
*/
void genie_provision_prov_timer_stop(void);
/**
* @brief
*/
void genie_provision_start_slient_pbadv(void);
#endif
| YifuLiu/AliOS-Things | components/genie_service/core/inc/genie_provision.h | C | apache-2.0 | 2,126 |
/*
* Copyright (C) 2018-2020 Alibaba Group Holding Limited
*/
#ifndef __GENIE_RESET_H__
#define __GENIE_RESET_H__
#define GENIE_RESET_BY_REPEAT_COUNTER 4
#define GENIE_RESET_BY_REPEAT_TIMEOUT (3 * 1000)
#define GENIE_RESET_WAIT_TIMEOUT (3 * 1000)
uint8_t genie_reset_get_hw_reset_flag(void);
genie_event_e genie_reset_do_sw_reset(void);
genie_event_e genie_reset_do_hw_reset(bool is_only_report);
int genie_reset_provision(void);
int genie_reset_init(void);
#endif
| YifuLiu/AliOS-Things | components/genie_service/core/inc/genie_reset.h | C | apache-2.0 | 476 |
/*
* Copyright (C) 2018-2020 Alibaba Group Holding Limited
*/
#ifndef __GENIE_STORAGE_H__
#define __GENIE_STORAGE_H__
#include <bluetooth/bluetooth.h>
#include <api/mesh.h>
#include "net.h"
//#include "flash.h"
#define GENIE_KV_SEQ_KEY "seq"
#define GENIE_SEQ_MAGIC_NUMBER (0xA8)
#define GENIE_SEQ_SAVE_INTERVAL (100)
enum {
GENIE_STORAGE_INDEX_START = 0,
GFI_MESH_PARA,
GFI_MESH_TRITUPLE,
GFI_MESH_SADDR,
GFI_MESH_SEQ,
GFI_MESH_RESET_CNT,
GFI_MESH_POWERUP,
GFI_MESH_HB,
GFI_MESH_DEVKEY,
GFI_MESH_NETKEY,
GFI_MESH_APPKEY,
GFI_OTA_INDICAT,
GFI_OTA_IMAGE_ID,
GFI_USERDATA_START,
#ifdef CONFIG_BT_MESH_CTRL_RELAY
GFI_MESH_CTRL_RELAY,
#endif
};
typedef enum
{
GENIE_STORAGE_SUCCESS = 0,
GENIE_STORAGE_INIT_FAIL,
GENIE_STORAGE_MALLOC_FAIL,
GENIE_STORAGE_EARSE_FAIL,
GENIE_STORAGE_DATA_INVALID,
GENIE_STORAGE_ERASE_FAIL,
GENIE_STORAGE_READ_FAIL,
GENIE_STORAGE_WRITE_FAIL,
GENIE_STORAGE_DELETE_FAIL,
GENIE_STORAGE_INVALID_INDEX,
GENIE_STORAGE_SIZE_ERROR,
GENIE_STORAGE_CHECK_CRC_FAIL
} genie_storage_status_e;
typedef struct{
uint16_t dst;
uint8_t count;
uint8_t period;
uint8_t ttl;
uint16_t feat;
uint16_t net_idx;
} mesh_hb_para_t;
typedef struct{
uint16_t net_index;
uint8_t flag;
uint32_t ivi;
uint8_t key[16];
} mesh_netkey_para_t;
typedef struct{
uint16_t net_index;
uint16_t key_index;
uint8_t flag;
uint8_t key[16];
} mesh_appkey_para_t;
#ifdef CONFIG_BT_MESH_CTRL_RELAY
typedef struct
{
uint8_t enable;
uint8_t trd_n;
uint8_t rssi;
uint8_t sta_period;
uint8_t chk_period;
uint8_t req_period;
} mesh_ctrl_relay_para_t;
#endif
/**
* @brief iniatialize the flash for further operation
* @return the status of iniatializetion, 0 for successed.
*/
genie_storage_status_e genie_storage_init(void);
/**
* @brief read the date from flash and decrypt it.
* @param[in] index refers to the flash partition to be read.
* @param[out] p_buff: the data.
* @param[in] data_size: the size of the data.
* @return the status of reading operation.
*/
genie_storage_status_e genie_storage_read_reliable(uint16_t index, uint8_t *p_buff, uint16_t data_size);
/**
* @brief encrypt the data and write it into flash
* @param[in] index refers to the flash partition to be read.
* @param[out] p_buff: the data.
* @param[in] data_size: the size of the data.
* @return the status of writing operation.
*/
genie_storage_status_e genie_storage_write_reliable(uint16_t index, uint8_t *p_buff, uint16_t data_size);
/**
* @brief delete the contents saved at the partition refered by index.
* @param[in] index refers to the partition
* @return the status of the operation.
*/
genie_storage_status_e genie_storage_delete_reliable(uint16_t index);
/**
* @brief read the user raw date from flash
* @param[in] index refers to the flash partition to be read.
* @param[out] p_buff: the data.
* @param[in] data_size: the size of the data.
* @return the status of reading operation.
*/
genie_storage_status_e genie_storage_read_userdata(uint16_t index, uint8_t *p_buff, uint16_t data_size);
/**
* @brief write the date into flash
* @param[in] index refers to the flash partition to be read.
* @param[out] p_buff: the data.
* @param[in] data_size: the size of the data.
* @return the status of writing operation.
*/
genie_storage_status_e genie_storage_write_userdata(uint16_t index, uint8_t *p_buff, uint16_t data_size);
/**
* @brief delete the contents saved at the partition refered by index.
* @param[in] index refers to the partition
* @return the status of the operation.
*/
genie_storage_status_e genie_storage_delete_userdata(uint16_t index);
genie_storage_status_e genie_triple_write(uint32_t *p_pid, uint8_t *p_mac, uint8_t *p_key);
genie_storage_status_e genie_triple_read(uint32_t *p_pid, uint8_t *p_mac, uint8_t *p_key);
/**
* @brief save the subscription address to flash
* @param[in] p_sub: the list of subscription address
* @return the status of operation, 0 means successed.
*/
genie_storage_status_e genie_storage_write_sub(uint16_t *p_sub);
/**
* @brief read the subscription address from flash
* @param[out] p_sub: the list of subscription address
* @return the status of operation, 0 means successed.
*/
genie_storage_status_e genie_storage_read_sub(uint16_t *p_sub);
/**
* @brief save the parameters for mesh to flash
* @param[in] mesh_data: the parameters for mesh
* @return the status of operation, 0 means successed.
*/
genie_storage_status_e genie_storage_write_para(struct bt_mesh_net *mesh_data);
/**
* @brief read the parameters for mesh from flash
* @param[in] mesh_data: the parameters for mesh
* @return the status of operation, 0 means successed.
*/
genie_storage_status_e genie_storage_read_para(struct bt_mesh_net *mesh_data);
/**
* @brief save the address of peer mesh devices to flash
* @param[in] p_addr: address
* @return the status of operation, 0 means successed.
*/
genie_storage_status_e genie_storage_write_addr(uint16_t *p_addr);
/**
* @brief read the address of peer mesh devices from flash
* @param[out] p_addr: address
* @return the status of operation, 0 means successed.
*/
genie_storage_status_e genie_storage_read_addr(uint16_t *p_addr);
/**
* @brief write the heartbeat parameters to flash
* @param[in] p_para: heartbeat parameters
* @return the status of operation, 0 means successed.
*/
genie_storage_status_e genie_storage_write_hb(mesh_hb_para_t *p_para);
/**
* @brief read the heartbeat parameters from flash
* @param[out] p_para: heartbeat parameters
* @return the status of operation, 0 means successed.
*/
genie_storage_status_e genie_storage_read_hb(mesh_hb_para_t *p_para);
#ifdef CONFIG_BT_MESH_CTRL_RELAY
/**
* @brief write the ctrl relay parameters to flash
* @param[in] p_para: ctrl relay parameters
* @return the status of operation, 0 means successed.
*/
genie_storage_status_e genie_storage_write_ctrl_relay(mesh_ctrl_relay_para_t *p_para);
/**
* @brief read the ctrl relay parameters from flash
* @param[out] p_para: ctrl relay parameters
* @return the status of operation, 0 means successed.
*/
genie_storage_status_e genie_storage_read_ctrl_relay(mesh_ctrl_relay_para_t *p_para);
#endif
/**
* @brief save the devices key to flash
* @param[in] status: devcie key
* @return the status of operation, 0 means successed.
*/
genie_storage_status_e genie_storage_write_devkey(uint8_t *p_devkey);
/**
* @brief read the devices key from flash
* @param[out] status: devcie key
* @return the status of operation, 0 means successed.
*/
genie_storage_status_e genie_storage_read_devkey(uint8_t *p_devkey);
/**
* @brief save the net key to flash
* @param[in] status: net key
* @return the status of operation, 0 means successed.
*/
genie_storage_status_e genie_storage_write_netkey(mesh_netkey_para_t *p_netkey);
/**
* @brief read the net key from flash
* @param[out] status: net key
* @return the status of operation, 0 means successed.
*/
genie_storage_status_e genie_storage_read_netkey(mesh_netkey_para_t *p_netkey);
/**
* @brief save the app key to flash
* @param[in] status: app key
* @return the status of operation, 0 means successed.
*/
genie_storage_status_e genie_storage_write_appkey(mesh_appkey_para_t *p_appkey);
/**
* @brief read the app key from flash
* @param[out] status: app key
* @return the status of operation, 0 means successed.
*/
genie_storage_status_e genie_storage_read_appkey(mesh_appkey_para_t *p_appkey);
/**
* @brief save the seq number to flash
* @param[in] status: seq number
* @return the status of operation, 0 means successed.
*/
genie_storage_status_e genie_storage_write_seq(uint32_t *p_seq, bool force_write);
/**
* @brief read the seq number from flash
* @param[out] status: seq number
* @return the status of operation, 0 means successed.
*/
genie_storage_status_e genie_storage_read_seq(uint32_t *p_seq);
/**
* @brief delete the seq number from flash
* @return the status of operation, 0 means successed.
*/
genie_storage_status_e genie_storage_delete_seq(void);
/**
* @brief erase everyting on flash except the trituple info
* @return the status of operation, 0 means successed.
*/
genie_storage_status_e genie_storage_reset_system(void);
#endif/*--_GENIE_STORAGE_H_--*/
| YifuLiu/AliOS-Things | components/genie_service/core/inc/genie_storage.h | C | apache-2.0 | 8,376 |
/*
* Copyright (C) 2018-2020 Alibaba Group Holding Limited
*/
#ifndef __GENIE_TIME_H__
#define __GENIE_TIME_H__
#include <hal/hal.h>
#pragma pack(1)
typedef struct
{
uint16_t type;
uint8_t para;
} vendor_attr_data_t;
#pragma pack()
#define GENIE_TIME_HW_TEIMER_ID (0)
#define GENIE_TIME_HW_TEIMER_PERIOD (1000 * 1000)
#define DEF_SYNC_PERIOD 180
#define DEF_SYNC_DELAY 10
#define DEF_SYNC_DELAY_RETRY 10
//no update when init,because Genie will push UTC time when device bootup
//#define GENIE_TIME_UPDATE_WHEN_BOOTUP (1)
//#define GT_STORE
#define MINU 60
#define HOUR (60 * MINU)
#define DAY (24 * HOUR)
#define GENIE_TIME_MAX (40)
typedef int (*genie_time_event_func_t)(uint8_t event, uint8_t index, vendor_attr_data_t *data);
typedef enum
{
TIMER_OFF = 0,
TIMER_ON = 1,
TIMER_INVAILD = 0xf,
} vt_state;
typedef struct _genie_time_s
{
sys_snode_t next;
uint8_t index;
uint8_t state : 4;
uint8_t periodic : 1;
uint32_t periodic_time;
uint8_t schedule;
uint32_t unixtime_match;
vendor_attr_data_t attr_data;
} genie_time_t;
typedef struct _unixtime_sync_s
{
uint16_t period_time;
uint8_t retry_delay;
uint8_t retry_times;
} unixtime_sync_t;
typedef struct _genie_time_data_s
{
uint16_t magic;
int8_t timezone;
unixtime_sync_t timing_sync_config;
genie_time_t timer_data[GENIE_TIME_MAX];
} genie_time_data_t;
typedef struct _genie_time_timer_s
{
uint8_t init : 1;
uint8_t update : 1;
timer_dev_t timer;
sys_slist_t timer_list_active;
sys_slist_t timer_list_idle;
uint32_t unix_time;
uint32_t unix_time_sync_match;
uint8_t unix_time_sync_retry_times;
genie_time_event_func_t genie_time_event_cb;
struct k_work work;
struct k_sem lock;
} genie_time_timer_t;
typedef struct _utc_time_s
{
uint16_t year; // 2019+
uint8_t month; // 0-11
uint8_t day; // 1-31
uint8_t seconds; // 0-59
uint8_t minutes; // 0-59
uint8_t hour; // 0-23
uint8_t weekday; // 0 means sunday
} utc_time_t;
typedef enum
{
GT_OK = 0,
GT_E_INIT,
GT_E_LOCALTIME_NOTSET,
GT_E_INDEX,
GT_E_PARAM,
GT_E_NORESOURCE,
GT_E_OTHER,
} genie_time_errno;
enum
{
GT_TIMEOUT = 0,
GT_TIMING_SYNC = 1,
};
int genie_time_init(void);
int genie_time_finalize(void);
int genie_time_handle_model_mesg(genie_transport_model_param_t *p_msg);
#endif
| YifuLiu/AliOS-Things | components/genie_service/core/inc/genie_time.h | C | apache-2.0 | 2,411 |
#ifndef __GENIE_TRANSPORT_H__
#define __GENIE_TRANSPORT_H__
#include "misc/dlist.h"
#define RECV_MSG_TID_QUEUE_SIZE 5
#define GENIE_TRANSPORT_DEDUPLICATE_DURATION (6000) //unit ms
#define TMALL_GENIE_UADDR_START 0x0001
#define TMALL_GENIE_UADDR_END 0x0010
#define GENIE_TRANSPORT_TID_MIN (0x80)
#define GENIE_TRANSPORT_TID_MAX (0xBF)
#define GENIE_TRANSPORT_DEFAULT_TTL (3)
#ifdef CONFIG_GENIE_MESH_GLP
#define GENIE_TRANSPORT_DEFAULT_RETRY_COUNT (5) //Total six times
#else
#define GENIE_TRANSPORT_DEFAULT_RETRY_COUNT (2) //Total three times
#endif
#define GENIE_TRANSPORT_EACH_PDU_TIMEOUT (600) //Unit ms
#define GENIE_TRANSPORT_EACH_PDU_SIZE (12)
#ifndef CONFIG_VENDOR_SEND_MSG_MAX
#define CONFIG_VENDOR_SEND_MSG_MAX 8
#endif
typedef struct _genie_transport_tid_queue_s
{
uint8_t tid;
uint8_t elemid;
uint16_t addr;
uint32_t time;
} genie_transport_tid_queue_t;
typedef enum
{
MESH_SUCCESS = 0,
MESH_TID_REPEAT,
MESH_ANALYZE_SIZE_ERROR,
MESH_ANALYZE_ARGS_ERROR,
MESH_SET_TRANSTION_ERROR,
} E_MESH_ERROR_TYPE;
/**
* p_elem: pointer to the element which the messsage want to be sent to
* retry: retry counts before desired confirm message received
* * fill negative value if retransmission is not necessary
* * fill positive value if retransmission is needed
* * * will be round in this scope - [VENDOR_MODEL_MSG_DFT_RETRY_TIMES, VENDOR_MODEL_MSG_MAX_RETRY_TIMES]
* retry_period: wait for retry_period before retransmit the message, in unit of ms
* opid: hightest byte in Opcode defined in the vendor model spec designed by Alibaba IoT Group
* * e.g. for Vendor Message Attr Get message, Opcode is 0xD001A8, corresponding opid is 0xD0
* * refer to the marco named VENDOR_OP_ATTR_xxxx
* tid:
* * if the message is with type of VENDOR_OP_ATTR_CONFIME or VENDOR_OP_ATTR_CONFIME_TG,
* * tid should be filled with the replied message's tid
* len: payload length
* data: pointer to the vendor message's payload
* */
typedef enum _transport_result_e
{
SEND_RESULT_SUCCESS = 0,
SEND_RESULT_TIMEOUT
} transport_result_e;
typedef int (*transport_result_cb)(transport_result_e result);
typedef struct _genie_transport_model_param_s
{
struct bt_mesh_elem *p_elem;
struct bt_mesh_model *p_model; //It is current model
transport_result_cb result_cb;
uint8_t retry;
uint8_t opid;
uint8_t tid;
uint16_t dst_addr;
uint16_t retry_period;
uint16_t len;
uint8_t *data;
} genie_transport_model_param_t;
typedef struct _genie_transport_node_s
{
sys_dnode_t node;
uint8_t left_retry;
long long timeout;
genie_transport_model_param_t msg;
} genie_transport_node_t;
typedef struct _genie_transport_payload_s
{
uint8_t opid;
uint8_t tid;
uint8_t retry_cnt;
uint16_t dst_addr;
uint8_t *p_payload;
uint16_t payload_len;
transport_result_cb result_cb;
} genie_transport_payload_param_t;
/**
* @brief check whether there is this tid in record, and record it if not.
* @param[in] src_addr indicates the device which hold this tid.
* @param[in] tid
* @return MESH_SUCCESS means successed, otherwise failed.
*/
E_MESH_ERROR_TYPE
genie_transport_check_tid(uint16_t src_addr, uint8_t tid, uint8_t elem_id);
void genie_transport_src_addr_set(uint16_t src_addr);
uint16_t genie_transport_src_addr_get();
/**
* @brief send the vendor model message
* @param[in] p_vendor_msg refers to the message to be sent
* @return 0 for success; negative for failure
*/
int genie_transport_send_model(genie_transport_model_param_t *p_vendor_msg);
int genie_transport_send_payload(genie_transport_payload_param_t *payload_param);
uint8_t genie_transport_gen_tid(void);
uint8_t genie_transport_get_seg_count(uint16_t msg_len);
bool genie_transport_tx_in_progress(void);
/** @def genie_transport_ack
*
* @brief check received vendor message's tid
*
* @param pointer to send_list, tid of the received vendor model message
*
* @return 0 for success; negative for failure
*/
int genie_transport_ack(uint8_t tid);
void genie_transport_init(void);
#endif
| YifuLiu/AliOS-Things | components/genie_service/core/inc/genie_transport.h | C | apache-2.0 | 4,084 |
/*
* Copyright (C) 2018-2020 Alibaba Group Holding Limited
*/
#ifndef __GENIE_TRIPLE_H__
#define __GENIE_TRIPLE_H__
#define GENIE_TRIPLE_PID_SIZE 4
#define GENIE_TRIPLE_KEY_SIZE 16
#define GENIE_TRIPLE_MAC_SIZE 6
#define GENIE_TRIPLE_CRC_LEN 2
#define GENIE_SIZE_TRI_TRUPLE (GENIE_TRIPLE_PID_SIZE + GENIE_TRIPLE_KEY_SIZE + GENIE_TRIPLE_MAC_SIZE + GENIE_TRIPLE_CRC_LEN)
#define GENIE_TRIPLE_CRC_MAGIC (0xA5A6)
typedef struct _genie_triple_s
{
uint32_t pid;
uint8_t key[GENIE_TRIPLE_KEY_SIZE];
uint8_t mac[GENIE_TRIPLE_MAC_SIZE];
} genie_triple_t;
/**
* @brief writes the trituple info into flash.
* @param[in] p_pid: product ID
* @param[in] p_mac: device address
* @param[in] p_key: secret key
* @return the status of the writing operation, 0 for success.
*/
genie_storage_status_e genie_triple_write(uint32_t *p_pid, uint8_t *p_mac, uint8_t *p_key);
/**
* @brief get the trituple info from flash.
* @param[in] p_pid
* @param[in] p_mac
* @param[in] p_key
* @return the status of the reading operation, 0 for success.
*/
genie_storage_status_e genie_triple_read(uint32_t *p_pid, uint8_t *p_mac, uint8_t *p_key);
/**
* @brief load the trituple info from flash.
* @return 0 for success, otherwise failed.
*/
int8_t genie_triple_init(void);
genie_triple_t *genie_triple_get(void);
uint8_t *genie_triple_get_mac(void);
#endif | YifuLiu/AliOS-Things | components/genie_service/core/inc/genie_triple.h | C | apache-2.0 | 1,357 |
/*
* Copyright (C) 2018-2020 Alibaba Group Holding Limited
*/
#ifndef __GENIE_VENDOR_MODEL_H__
#define __GENIE_VENDOR_MODEL_H__
#define VENDOR_OP_ATTR_GET_STATUS 0xD0
#define VENDOR_OP_ATTR_SET_ACK 0xD1
#define VENDOR_OP_ATTR_SET_UNACK 0xD2
#define VENDOR_OP_ATTR_STATUS 0xD3
#define VENDOR_OP_ATTR_INDICATE 0xD4
#define VENDOR_OP_ATTR_CONFIME 0xD5
#define VENDOR_OP_ATTR_INDICATE_TG 0xDE
#define VENDOR_OP_ATTR_CONFIME_TG 0xDF
#define VENDOR_OP_ATTR_TRANS_MSG 0xCF
#define VENDOR_OP_ATTR_TRANS_INDICATE 0xCE
#define VENDOR_OP_ATTR_TRANS_ACK 0xCD
#define ATTR_TYPE_REPORT_VERSION 0xFF01
#define ATTR_TYPE_DEVICE_EVENT 0xF009
#define ATTR_TYPE_VOLTAGE_LEVEL 0x0105
#define VENDOR_MODEL_VERSION 10 //vendor model version:1.0
#define SDK_VERSION 13 //SDK version:1.3
/* Event List - Refer to Device Event List */
#define EL_FAULT_T 0x00 /* malfunction event */
#define EL_LOW_BAT_T 0x01 /* low battery event */
#define EL_DEV_UP_T 0x03 /* device power up */
#define EL_HW_RESET_T 0x23 /* hardware reset event */
/* Vendor timer error code */
#define ERR_CODE_UNIXTIME 0x80
#define ERR_CODE_NOTSUP_ATTR_OP 0x82
#define ERR_CODE_NOTSUP_ATTR_PARAM 0x83
#define ERR_CODE_TIMER_SETTING 0x84
#define ERR_CODE_TIMER_INDEX 0x85
#define ERR_CODE_TIMER_FULL 0x86
#define ERR_CODE_TIMER_PRIORDIC_PARAM 0x87
/* Vendor timer ali attr type */
#define ERROR_CODE_T 0x0000
#define TIMING_TIMEOUT_T 0xF009
#define TIMING_SETTING_T 0xF010
#define TIMING_PERIODIC_SETTING_T 0xF011
#define TIMING_DELETE_T 0xF012
#define TIMING_SYNC_T 0xF01D
#define TIMEZONE_SETTING_T 0xF01E
#define UNIX_TIME_T 0xF01F
#define EL_TIMING_TIMEOUT_T 0x11 /* timer timeout event */
#ifndef VENDOR_MODEL_MSG_MAX_RETRY_TIMES
#define VENDOR_MODEL_MSG_DFT_RETRY_TIMES 45
#endif
#ifndef VENDOR_MODEL_MSG_MAX_RETRY_TIMES
#define VENDOR_MODEL_MSG_MAX_RETRY_TIMES 45
#endif
#ifndef VENDOR_MODEL_MSG_RETRY_PERIOD
#define VENDOR_MODEL_MSG_RETRY_PERIOD 400
#endif
#define GENIE_MODEL_SEG_COUNT 8
#define GENIE_MODEL_MTU (GENIE_MODEL_SEG_COUNT * 12)
#define CONFIG_MESH_VENDOR_MODEL_SRV 0x0000
#define VENDOR_MODEL_OPC_NUM 9
extern struct bt_mesh_model_pub genie_model_pub;
extern const struct bt_mesh_model_op genie_model_op[VENDOR_MODEL_OPC_NUM];
#define MESH_MODEL_VENDOR_SRV(_user_data) BT_MESH_MODEL_VND(CONFIG_MESH_VENDOR_COMPANY_ID, CONFIG_MESH_VENDOR_MODEL_SRV, \
genie_model_op, &genie_model_pub, _user_data)
int genie_model_handle_mesg(genie_transport_model_param_t *p_msg);
#endif
| YifuLiu/AliOS-Things | components/genie_service/core/inc/genie_vendor_model.h | C | apache-2.0 | 2,533 |
#ifndef __GENIE_VERSION_H__
#define __GENIE_VERSION_H__
uint32_t genie_version_appver_get(void);
const char *genie_version_sysver_get(void);
int genie_version_appver_string_get(char *version, int len);
#endif
| YifuLiu/AliOS-Things | components/genie_service/core/inc/genie_version.h | C | apache-2.0 | 213 |
#ifndef __SIG_MODEL_H__
#define __SIG_MODEL_H__
#define ATTR_TYPE_GENERIC_ONOFF 0x0100
#define ATTR_TYPE_LIGHTNESS 0x0121
#define ATTR_TYPE_COLOR_TEMPERATURE 0x0122
#define ATTR_TYPE_SENCE 0xF004
typedef enum
{
TYPE_PRESENT = 0,
TYPE_TARGET,
TYPE_NUM,
} E_VALUE_TYPE;
typedef struct
{
#ifdef CONFIG_MESH_MODEL_GEN_ONOFF_SRV
u8_t onoff[TYPE_NUM];
#endif
#ifdef CONFIG_MESH_MODEL_LIGHTNESS_SRV
u16_t lightness[TYPE_NUM];
#endif
#ifdef CONFIG_MESH_MODEL_CTL_SRV
u16_t color_temperature[TYPE_NUM];
#endif
#ifdef CONFIG_MESH_MODEL_SCENE_SRV
u16_t scene[TYPE_NUM];
#endif
u8_t delay; //unit:5ms
struct k_timer delay_timer;
#ifdef CONFIG_MESH_MODEL_TRANS
u8_t trans; //unit:100ms
bt_u32_t trans_start_time;
bt_u32_t trans_end_time;
struct k_timer trans_timer;
#endif
} sig_model_state_t;
typedef struct
{
#ifdef CONFIG_MESH_MODEL_GEN_ONOFF_SRV
u8_t last_onoff;
#endif
#ifdef CONFIG_MESH_MODEL_LIGHTNESS_SRV
u16_t last_lightness;
#endif
#ifdef CONFIG_MESH_MODEL_CTL_SRV
u16_t last_color_temperature;
#endif
#ifdef CONFIG_MESH_MODEL_SCENE_SRV
u16_t last_scene;
#endif
} __packed sig_model_powerup_t;
typedef struct
{
u8_t element_id;
sig_model_state_t state;
sig_model_powerup_t powerup;
void *user_data;
} sig_model_element_state_t;
#ifdef CONFIG_MESH_MODEL_GEN_ONOFF_SRV
#include "sig_model_onoff_srv.h"
#include "sig_model_bind_ops.h"
#endif
#ifdef CONFIG_MESH_MODEL_LIGHTNESS_SRV
#include "sig_model_lightness_srv.h"
#endif
#ifdef CONFIG_MESH_MODEL_CTL_SRV
#include "sig_model_light_ctl_srv.h"
#endif
#ifdef CONFIG_MESH_MODEL_SCENE_SRV
#include "sig_model_scene.h"
#endif
#include "sig_model_transition.h"
#include "sig_model_opcode.h"
#include "sig_model_event.h"
#endif
| YifuLiu/AliOS-Things | components/genie_service/core/inc/sig_models/sig_model.h | C | apache-2.0 | 1,766 |
/*
* Copyright (C) 2018-2020 Alibaba Group Holding Limited
*/
#ifndef __SIG_MODEL_BIND_OPS_H__
#define __SIG_MODEL_BIND_OPS_H__
#ifdef CONFIG_MESH_MODEL_GEN_ONOFF_SRV
u16_t sig_model_generic_onoff_bind_ops(sig_model_element_state_t *p_elem);
#endif
#ifdef CONFIG_MESH_MODEL_LIGHTNESS_SRV
u16_t sig_model_generic_lightness_bind_ops(sig_model_element_state_t *p_elem, u8_t type);
#endif
#ifdef CONFIG_MESH_MODEL_CTL_SRV
u16_t sig_model_generic_color_temperature_bind_ops(sig_model_element_state_t *p_elem);
#endif
#endif
| YifuLiu/AliOS-Things | components/genie_service/core/inc/sig_models/sig_model_bind_ops.h | C | apache-2.0 | 526 |
#ifndef __SIG_MODEL_EVENT_H__
#define __SIG_MODEL_EVENT_H__
#define SIG_MODEL_INDICATE_PAYLOAD_MAX_LEN (20)
typedef enum _indicate_flag
{
SIG_MODEL_INDICATE_GEN_ONOFF,
SIG_MODEL_INDICATE_GEN_LIGHTNESS,
SIG_MODEL_INDICATE_GEN_CTL,
SIG_MODEL_INDICATE_GEN_SCENE,
SIG_MODEL_INDICATE_FLAGS
} sig_model_indicate_flag_e;
typedef enum
{
SIG_MODEL_EVT_NONE = 0,
SIG_MODEL_EVT_ANALYZE_MSG,
SIG_MODEL_EVT_TIME_OUT,
SIG_MODEL_EVT_DOWN_MSG,
SIG_MODEL_EVT_ACTION_DONE,
SIG_MODEL_EVT_INDICATE,
SIG_MODEL_EVT_DELAY_START = 10,
SIG_MODEL_EVT_DELAY_END,
#ifdef CONFIG_MESH_MODEL_TRANS
SIG_MODEL_EVT_TRANS_START,
SIG_MODEL_EVT_TRANS_CYCLE,
SIG_MODEL_EVT_TRANS_END,
#endif
SIG_MODEL_EVT_GENERIC_MESG = 20,
} sig_model_event_e;
void sig_model_event_set_indicate(int indicate);
void sig_model_event(sig_model_event_e event, void *p_arg);
#endif
| YifuLiu/AliOS-Things | components/genie_service/core/inc/sig_models/sig_model_event.h | C | apache-2.0 | 900 |
/*
* Copyright (C) 2018-2020 Alibaba Group Holding Limited
*/
#ifndef __SIG_MODEL_LIGHT_CTL_SRV_H__
#define __SIG_MODEL_LIGHT_CTL_SRV_H__
#define COLOR_TEMPERATURE_MIN 800
#define COLOR_TEMPERATURE_MAX 20000
#define COLOR_TEMPERATURE_DEFAULT COLOR_TEMPERATURE_MAX
#define LIGHT_CTL_OPCODE_NUM 4
#define MESH_MODEL_CTL_SRV(_user_data) BT_MESH_MODEL(BT_MESH_MODEL_ID_LIGHT_CTL_SRV, \
g_ctl_srv_op, &g_ctl_srv_pub, _user_data)
extern struct bt_mesh_model_pub g_ctl_srv_pub;
extern const struct bt_mesh_model_op g_ctl_srv_op[LIGHT_CTL_OPCODE_NUM];
void sig_model_light_ctl_update_by_onoff(sig_model_element_state_t *p_elem);
#endif
| YifuLiu/AliOS-Things | components/genie_service/core/inc/sig_models/sig_model_light_ctl_srv.h | C | apache-2.0 | 690 |
/*
* Copyright (C) 2018-2020 Alibaba Group Holding Limited
*/
#ifndef __SIG_MODEL_LIGHTNESS_SRV_H__
#define __SIG_MODEL_LIGHTNESS_SRV_H__
#define LIGHTNESS_OPC_NUM 4
#define LIGHTNESS_DEFAULT 0xE666 //90%
#define LIGHTNESS_MAX_VALUE 0xFFFF //100%
#define MESH_MODEL_LIGHTNESS_SRV(_user_data) BT_MESH_MODEL(BT_MESH_MODEL_ID_LIGHT_LIGHTNESS_SRV, \
g_lightness_op, &g_lightness_pub, _user_data)
extern struct bt_mesh_model_pub g_lightness_pub;
extern const struct bt_mesh_model_op g_lightness_op[LIGHTNESS_OPC_NUM];
void sig_model_lightness_update_by_onoff(sig_model_element_state_t *p_elem);
#endif
| YifuLiu/AliOS-Things | components/genie_service/core/inc/sig_models/sig_model_lightness_srv.h | C | apache-2.0 | 666 |
/*
* Copyright (C) 2018-2020 Alibaba Group Holding Limited
*/
#ifndef _ALI_MODEL_GEN_ONOFF_SRV_H_
#define _ALI_MODEL_GEN_ONOFF_SRV_H_
#include "genie_service.h"
#define GEN_ONOFF_OPC_NUM 4
#define GEN_ONOFF_DEFAULT 1
#define MESH_MODEL_GEN_ONOFF_SRV(_user_data) BT_MESH_MODEL(BT_MESH_MODEL_ID_GEN_ONOFF_SRV, \
g_gen_onoff_op, &g_gen_onoff_pub, _user_data)
extern struct bt_mesh_model_pub g_gen_onoff_pub;
extern const struct bt_mesh_model_op g_gen_onoff_op[GEN_ONOFF_OPC_NUM];
/**
* @brief generic on/off model publication
* @param[in] p_model: model details
*/
void gen_onoff_publication(struct bt_mesh_model *p_model);
/**
* @brief bind the on/off element with lightness app.
* @param[in] p_elem refer to the element to be bound.
* @param[in] type TYPE_PRESENT or TYPE_TARGET
*/
void sig_model_onoff_update_by_lightness(sig_model_element_state_t *p_elem, E_VALUE_TYPE type);
#ifdef CONFIG_MESH_MODEL_CTL_SRV
void sig_model_onoff_update_by_color_temperature(sig_model_element_state_t *p_elem);
#endif
#endif // _ALI_MODEL_GEN_ONOFF_SRV_H_
| YifuLiu/AliOS-Things | components/genie_service/core/inc/sig_models/sig_model_onoff_srv.h | C | apache-2.0 | 1,117 |
#ifndef __SIG_MODEL_OPCODE_H__
#define __SIG_MODEL_OPCODE_H__
#define OP_GENERIC_ONOFF_GET BT_MESH_MODEL_OP_2(0x82, 0x01)
#define OP_GENERIC_ONOFF_SET BT_MESH_MODEL_OP_2(0x82, 0x02)
#define OP_GENERIC_ONOFF_SET_UNACK BT_MESH_MODEL_OP_2(0x82, 0x03)
#define OP_GENERIC_ONOFF_STATUS BT_MESH_MODEL_OP_2(0x82, 0x04)
#define OP_GENERIC_LEVEL_GET BT_MESH_MODEL_OP_2(0x82, 0x05)
#define OP_GENERIC_LEVEL_SET BT_MESH_MODEL_OP_2(0x82, 0x06)
#define OP_GENERIC_LEVEL_SET_UNACK BT_MESH_MODEL_OP_2(0x82, 0x07)
#define OP_GENERIC_LEVEL_STATUS BT_MESH_MODEL_OP_2(0x82, 0x08)
#define OP_GENERIC_DALTA_SET BT_MESH_MODEL_OP_2(0x82, 0x09)
#define OP_GENERIC_DALTA_SET_UNACK BT_MESH_MODEL_OP_2(0x82, 0x0a)
#define OP_GENERIC_MOVE_SET BT_MESH_MODEL_OP_2(0x82, 0x0b)
#define OP_GENERIC_MOVE_SET_UNACK BT_MESH_MODEL_OP_2(0x82, 0x0c)
#define OP_GENERIC_SCENE_GET BT_MESH_MODEL_OP_2(0x82, 0x41)
#define OP_GENERIC_SCENE_SET BT_MESH_MODEL_OP_2(0x82, 0x42)
#define OP_GENERIC_SCENE_SET_UNACK BT_MESH_MODEL_OP_2(0x82, 0x43)
#define OP_GENERIC_SCENE_STATUS BT_MESH_MODEL_OP_1(0x5E)
#define OP_GENERIC_LIGHTNESS_GET BT_MESH_MODEL_OP_2(0x82, 0x4b)
#define OP_GENERIC_LIGHTNESS_SET BT_MESH_MODEL_OP_2(0x82, 0x4c)
#define OP_GENERIC_LIGHTNESS_SET_UNACK BT_MESH_MODEL_OP_2(0x82, 0x4d)
#define OP_GENERIC_LIGHTNESS_STATUS BT_MESH_MODEL_OP_2(0x82, 0x4e)
#define OP_GENERIC_LIGHT_CTL_GET BT_MESH_MODEL_OP_2(0x82, 0x5d)
#define OP_GENERIC_LIGHT_CTL_SET BT_MESH_MODEL_OP_2(0x82, 0x5e)
#define OP_GENERIC_LIGHT_CTL_SET_UNACK BT_MESH_MODEL_OP_2(0x82, 0x5f)
#define OP_GENERIC_LIGHT_CTL_STATUS BT_MESH_MODEL_OP_2(0x82, 0x60)
#endif
| YifuLiu/AliOS-Things | components/genie_service/core/inc/sig_models/sig_model_opcode.h | C | apache-2.0 | 1,596 |
/*
* Copyright (C) 2018-2020 Alibaba Group Holding Limited
*/
#ifndef __GENIE_MODEL_SCENE_H__
#define __GENIE_MODEL_SCENE_H__
#define GENIE_SCENE_OP_NUM 4
typedef enum _genie_scene_e
{
GENIE_SCENE_NORMAL,
GENIE_SCENE_READ = 3,
GENIE_SCENE_CINEMA,
GENIE_SCENE_WARM,
GENIE_SCENE_NIGHT
} genie_scene_e;
#define SCENE_DEFAULT GENIE_SCENE_NORMAL
extern struct bt_mesh_model_pub g_scene_pub;
extern const struct bt_mesh_model_op g_scene_op[GENIE_SCENE_OP_NUM];
#define MESH_MODEL_SCENE_SRV(_user_data) BT_MESH_MODEL(BT_MESH_MODEL_ID_SCENE_SRV, g_scene_op, &g_scene_pub, _user_data)
#endif
| YifuLiu/AliOS-Things | components/genie_service/core/inc/sig_models/sig_model_scene.h | C | apache-2.0 | 611 |
#ifndef __SIG_MODEL_TRANSITION_H__
#define __SIG_MODEL_TRANSITION_H__
#define SIG_MODEL_TRANSITION_INTERVAL 20
#define TRANSITION_TIME_UNIT_1 (100) //Unit:ms
#define TRANSITION_TIME_UNIT_2 (1000) //Unit:ms
#define TRANSITION_TIME_UNIT_3 (10 * 1000) //Unit:ms
#define TRANSITION_TIME_UNIT_4 (10 * 60 * 1000) //Unit:ms
#define TRANSITION_TIME_UNIT_BIT(unit_value) ((unit_value) << 6)
#define TRANSITION_TIME_VALUE_MIN (0)
#define TRANSITION_TIME_VALUE_MAX (0x3E)
#define TRANSITION_TIME_VALUE_INVALID (0x3F)
#define TRANSITION_TIME_VALUE_MASK (0x3F)
#define TRANSITION_DEFAULT_VALUE (0x41)
#define DELAY_DEFAULT_VAULE (100)
#define DELAY_TIME_UNIT (5)
void sig_model_transition_timer_stop(sig_model_element_state_t *p_elem);
bt_u32_t sig_model_transition_get_transition_time(uint8_t byte);
uint8_t sig_model_transition_get_remain_time_byte(sig_model_state_t *p_state, bool is_ack);
void sig_model_transition_state_reset(sig_model_element_state_t *p_elem);
uint8_t sig_model_transition_update(sig_model_element_state_t *p_elem);
#endif
| YifuLiu/AliOS-Things | components/genie_service/core/inc/sig_models/sig_model_transition.h | C | apache-2.0 | 1,070 |
/*
* Copyright (C) 2018-2020 Alibaba Group Holding Limited
*/
#include <port/mesh_hal_ble.h>
//#include "multi_adv.h"
#define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_MESH_DEBUG_OTA)
#include "common/log.h"
#include "bt_mesh_custom_log.h"
#include "genie_service.h"
#include "ali_dfu_port.h"
#define DEBUG_AIS_DETAIL_DATA 1
static genie_ais_ctx_t genie_ais_ctx;
extern genie_ota_ctx_t genie_ota_ctx;
static struct bt_gatt_attr _ais_srv_attrs[];
static int _ais_decrypt(uint8_t *payload, uint8_t len)
{
uint8_t dec[16];
if (genie_crypto_decrypt(payload, dec) != 0)
{
printf("ais decrypt:%s fail\r\n", bt_hex(payload, len));
return -1;
}
memcpy(payload, dec, 16);
return 0;
}
static void _ais_indicate_rsp(struct bt_conn *conn, const struct bt_gatt_attr *attr, u8_t err, void *p_params)
{
struct bt_gatt_indicate_params *p_indicate = (struct bt_gatt_indicate_params *)p_params;
printf("ais rsp err(%d) p_ind(%p)\r\n", err, p_indicate);
if (p_indicate)
{
aos_free(p_indicate);
p_indicate = NULL;
}
}
static void _ais_server_indicate(uint8_t msg_id, uint8_t cmd, uint8_t *p_msg, uint16_t len)
{
int ret = 0;
ais_pdu_t msg;
struct bt_gatt_indicate_params *p_indicate = NULL;
p_indicate = aos_malloc(sizeof(struct bt_gatt_indicate_params));
if (!p_indicate)
{
BT_ERR("no mem");
return;
}
memset(&msg, 0, sizeof(msg));
if (genie_ais_ctx.state == AIS_STATE_IDLE)
{
msg.header.enc = 1;
}
else
{
msg.header.enc = 0;
}
msg.header.msg_id = msg_id;
msg.header.cmd = cmd;
msg.header.payload_len = len;
if (p_msg)
{
memcpy(msg.payload, p_msg, len);
}
BT_DBG("len %d: %s", len + 4, bt_hex(&msg, len + 4));
//indicate._req
p_indicate->attr = &_ais_srv_attrs[6];
p_indicate->func = _ais_indicate_rsp;
p_indicate->data = &msg;
p_indicate->len = len + 4;
if (genie_ais_ctx.p_conn)
{
#ifdef DEBUG_AIS_DETAIL_DATA
printf("ais ind msgid:%d cmd:%02x p_ind:%p len:%d data:%s\r\n", msg_id, cmd, p_indicate, len, bt_hex(&msg, len + 4));
#else
printf("ais ind msgid:%d cmd:%02x p_ind:%p len:%d\r\n", msg_id, cmd, p_indicate, len);
#endif
ret = bt_gatt_indicate(genie_ais_ctx.p_conn, p_indicate);
if (ret < 0)
{
printf("ais bt_gatt_indicate err:%d\r\n", ret);
aos_free(p_indicate);
}
}
else
{
printf("ais not connect\r\n");
aos_free(p_indicate);
}
}
void genie_ais_notify(uint8_t msg_id, uint8_t cmd, uint8_t *p_msg, uint16_t len)
{
ais_pdu_t msg;
memset(&msg, 0, sizeof(msg));
if (genie_ais_ctx.state >= AIS_STATE_IDLE && genie_ais_ctx.state <= AIS_STATE_REBOOT)
{
msg.header.enc = 1;
}
else
{
msg.header.enc = 0;
}
msg.header.cmd = cmd;
msg.header.msg_id = msg_id;
msg.header.payload_len = len;
if (p_msg)
{
memcpy(msg.payload, p_msg, len);
}
BT_DBG("len %d: %s", len + 4, bt_hex(&msg, len + 4));
if (genie_ais_ctx.p_conn)
{
#ifdef DEBUG_AIS_DETAIL_DATA
printf("ais notify msgid:%d cmd:%02x len:%d data:%s\r\n", msg_id, cmd, len, bt_hex(&msg, len + 4));
#else
printf("ais notify msgid:%d cmd:%02x len:%d\r\n", msg_id, cmd, len);
#endif
bt_gatt_notify(genie_ais_ctx.p_conn, &_ais_srv_attrs[11], &msg, len + 4);
}
}
static void handle_ais_disconnect(void)
{
if (genie_ais_ctx.p_conn)
{
BT_DBG("ais handle disconn:%p\r\n", genie_ais_ctx.p_conn);
bt_conn_disconnect(genie_ais_ctx.p_conn, BT_HCI_ERR_REMOTE_USER_TERM_CONN);
genie_ais_ctx.p_conn = NULL;
}
}
void genie_ais_disconnect(uint8_t reason)
{
BT_DBG("ais disconn 0x%x, state %d\r\n", reason, genie_ais_ctx.state);
if (genie_ais_ctx.state != AIS_STATE_REBOOT)
{
k_timer_stop(&genie_ais_ctx.state_update_timer);
handle_ais_disconnect();
genie_ais_ctx.state = AIS_STATE_DISCON;
/* Flash is dirty, need erase */
if (genie_ota_ctx.flash_clean == 1 &&
genie_ota_ctx.ota_ready == 0)
{
erase_dfu_flash();
genie_ota_ctx.flash_clean = 0;
}
/* restart adv */
genie_event(GENIE_EVT_SDK_AIS_DISCON, NULL);
}
else
{
if (genie_ota_ctx.ota_flag != OTA_FLAG_SILENT || genie_sal_ota_is_allow_reboot())
{
//clear image change
BT_WARN("OTA Reboot!");
genie_storage_delete_reliable(GFI_OTA_IMAGE_ID);
dfu_reboot();
}
}
}
static void genie_ais_state_update(void)
{
if (genie_ais_ctx.state != AIS_STATE_OTA)
{
BT_DBG("ais update state:%d", genie_ais_ctx.state);
}
if (genie_ais_ctx.p_conn == NULL)
{
BT_WARN("proxy is disconnected");
return;
}
switch (genie_ais_ctx.state)
{
case AIS_STATE_DISCON:
k_timer_stop(&genie_ais_ctx.state_update_timer);
handle_ais_disconnect();
break;
case AIS_STATE_CONNECT:
case AIS_STATE_IDLE:
//no disconnect after one minute
//k_timer_start(&genie_ais_ctx.state_update_timer, AIS_OTA_DISCONN_TIMEOUT);
break;
case AIS_STATE_AUTH:
k_timer_start(&genie_ais_ctx.state_update_timer, AIS_OTA_AUTH_TIMEOUT);
break;
case AIS_STATE_OTA:
k_timer_start(&genie_ais_ctx.state_update_timer, AIS_OTA_REPORT_TIMEOUT);
break;
case AIS_STATE_REBOOT:
k_timer_start(&genie_ais_ctx.state_update_timer, AIS_OTA_REBOOT_TIMEOUT);
k_timer_start(&genie_ais_ctx.disconnect_timer, AIS_DISCONNECT_TIMEOUT);
break;
default:
break;
}
}
static void state_update_timer_cb(void *p_timer, void *args)
{
BT_DBG(" %d", genie_ais_ctx.state);
switch (genie_ais_ctx.state)
{
case AIS_STATE_CONNECT:
case AIS_STATE_IDLE:
{
genie_ais_ctx.state = AIS_STATE_DISCON;
}
break;
case AIS_STATE_AUTH:
{
genie_ais_reset();
genie_ais_ctx.state = AIS_STATE_CONNECT;
}
break;
case AIS_STATE_OTA:
{
if (genie_ota_ctx.err_count++ >= OTA_RECV_MAX_ERR_COUNT)
{
BT_ERR("OTA failed");
genie_ais_ctx.state = AIS_STATE_IDLE;
genie_ota_ctx.rx_len = 0;
_ais_server_indicate(0, AIS_RESP_ERR, NULL, 0);
}
else
{
genie_ota_status_report();
}
}
break;
case AIS_STATE_REBOOT:
{
printf("ais ota update done,do reboot ...\r\n");
dfu_reboot();
}
break;
default:
break;
}
genie_ais_state_update();
}
void genie_ais_connect(struct bt_conn *p_conn)
{
BT_DBG("ais connect state:%d conn:%p", genie_ais_ctx.state, p_conn);
if (genie_ais_ctx.state != AIS_STATE_REBOOT)
{
BT_DBG("status %d", genie_ais_ctx.state);
genie_ais_ctx.p_conn = p_conn;
genie_ais_ctx.state = AIS_STATE_CONNECT;
genie_ais_state_update();
genie_event(GENIE_EVT_SDK_AIS_CONNECT, NULL);
}
}
static void _ais_dis_timer_cb(void *p_timer, void *args)
{
printf("ais timeout disconnect\r\n");
handle_ais_disconnect();
}
static bool _ais_scrt_random(uint8_t msg_id, ais_scrt_random_t *p_scrt_random)
{
uint8_t cipher[16];
genie_ais_ctx.state = AIS_STATE_AUTH;
genie_ais_get_cipher(p_scrt_random->random, cipher);
_ais_server_indicate(msg_id, AIS_SCRT_CIPHER, cipher, 16);
return true;
}
static bool _ais_scrt_result(uint8_t msg_id, ais_scrt_result_t *p_scrt_result)
{
uint8_t ack = 0;
if (p_scrt_result->result == 1)
{
genie_ais_reset();
genie_ais_ctx.state = AIS_STATE_CONNECT;
}
else
{
genie_ais_ctx.state = AIS_STATE_IDLE;
}
_ais_server_indicate(msg_id, AIS_SCRT_ACK, &ack, 1);
return true;
}
static bool _ais_link_ack(uint8_t msg_id, ais_scrt_result_t *p_scrt_result)
{
uint8_t plaine_data[GENIE_CRYPTO_UNIT_SIZE];
uint8_t encrypt_data[GENIE_CRYPTO_UNIT_SIZE];
if (p_scrt_result->result == 0)
{
genie_ais_reset();
genie_ais_ctx.state = AIS_STATE_CONNECT;
}
memset(plaine_data, 0x0F, sizeof(plaine_data));
plaine_data[0] = 1;
genie_crypto_encrypt(plaine_data, encrypt_data);
_ais_server_indicate(msg_id, AIS_LINK_ACK, encrypt_data, GENIE_CRYPTO_UNIT_SIZE);
return true;
}
static bool _ais_msg_check_header(ais_header_t *p_msg_header)
{
//check seq & total, in ota case, the seq & total must be 0
if (p_msg_header->total_frame != 0 || p_msg_header->seq != 0 || p_msg_header->ver != 0 || p_msg_header->seq > p_msg_header->total_frame)
{
BT_ERR("fail %s", bt_hex(p_msg_header, sizeof(ais_header_t)));
return false;
}
return true;
}
static void _ais_server_msg_handle(struct bt_conn *p_conn, ais_pdu_t *p_msg, uint16_t len)
{
bool timer_refresh = false;
if (p_msg->header.cmd != AIS_OTA_DATA && !_ais_msg_check_header((ais_header_t *)p_msg))
{
printf("ais invalid msg, ignore");
}
if (p_msg->header.cmd != AIS_OTA_DATA)
{
#ifdef DEBUG_AIS_DETAIL_DATA
printf("ais cmd:0x%02x state:%d len:%d data:%s\r\n", p_msg->header.cmd, genie_ais_ctx.state, len, bt_hex(p_msg, len));
#else
printf("ais cmd:0x%02x state:%d len:%d\r\n", p_msg->header.cmd, genie_ais_ctx.state, len);
#endif
}
switch (p_msg->header.cmd)
{
case AIS_SCRT_RANDOM:
{
//len = 4+16
if (len == 20) //At any state we can negotiation the cipher again
{
timer_refresh = _ais_scrt_random(p_msg->header.msg_id,
(ais_scrt_random_t *)p_msg->payload);
}
}
break;
case AIS_SCRT_RESULT:
{
//len = 4+1
if (len == 5) //Allow duplicating of this message
{
k_timer_stop(&genie_ais_ctx.state_update_timer);
timer_refresh = _ais_scrt_result(p_msg->header.msg_id, (ais_scrt_result_t *)p_msg->payload);
}
}
break;
case AIS_LINK_STATUS:
{
//len = 4+16
if (len == 20) //Allow duplicating of this message
{
if (0 == _ais_decrypt(p_msg->payload, 16))
{
timer_refresh = _ais_link_ack(p_msg->header.msg_id, (ais_scrt_result_t *)p_msg->payload);
}
}
}
break;
case AIS_OTA_VER_REQ:
{
if (len == 20) //This is encrypted data
{
if (0 == _ais_decrypt(p_msg->payload, 16))
{
timer_refresh = genie_ota_handle_version_request(p_msg->header.msg_id, (ais_ota_ver_req_t *)p_msg->payload, 1);
}
}
else if (len == 5)
{
timer_refresh = genie_ota_handle_version_request(p_msg->header.msg_id, (ais_ota_ver_req_t *)p_msg->payload, 0);
}
}
break;
case AIS_OTA_FIRMWARE_REQ:
{
//len = 4+16
if (len == 20) //Encrypted data
{
if (0 == _ais_decrypt(p_msg->payload, 16))
{
timer_refresh = genie_ota_handle_update_request(p_msg->header.msg_id, (ais_ota_upd_req_t *)p_msg->payload, 1);
}
}
else if (len == 16) //Plain data
{
timer_refresh = genie_ota_handle_update_request(p_msg->header.msg_id, (ais_ota_upd_req_t *)p_msg->payload, 0);
}
}
break;
case AIS_OTA_DATA:
{
if ((len == sizeof(ais_header_t) + p_msg->header.payload_len) && p_msg->header.ver == 0)
{
timer_refresh = genie_ota_parse_pdu(p_msg);
}
}
break;
case AIS_OTA_CHECK_REQ:
{
if (len == 20 && genie_ais_ctx.state == AIS_STATE_OTA)
{
if (0 == _ais_decrypt(p_msg->payload, 16))
{
timer_refresh = genie_ota_check_firmware(p_msg->header.msg_id, (ais_ota_check_req_t *)p_msg->payload);
}
}
}
break;
default:
{
/* recv some unsupport cmd, just return */
BT_WARN("ais unsupport cmd %x\r\n", p_msg->header.cmd);
}
return;
}
if (timer_refresh)
{
genie_ais_state_update();
}
else
{
if (genie_ais_ctx.state != AIS_STATE_OTA)
{
printf("ais err state:%d cmd:0x%02x len:%d\r\n", genie_ais_ctx.state, p_msg->header.cmd, len);
_ais_server_indicate(p_msg->header.msg_id, AIS_RESP_ERR, NULL, 0);
}
}
}
static ssize_t _ais_server_read(struct bt_conn *p_conn, const struct bt_gatt_attr *p_attr,
void *buf, u16_t len, u16_t offset)
{
u16_t *value = p_attr->user_data;
BT_DBG("len %d: %s", len, bt_hex(buf, len));
return bt_gatt_attr_read(p_conn, p_attr, buf, len, offset, value, sizeof(*value));
}
static ssize_t _ais_service_write(struct bt_conn *p_conn, const struct bt_gatt_attr *p_attr,
const void *p_buf, u16_t len, u16_t offset, u8_t flags)
{
//BT_DBG("len %d: %s", len, bt_hex(p_buf, len));
if (len != 0)
{
_ais_server_msg_handle(p_conn, (ais_pdu_t *)p_buf, len);
}
return len;
}
static ssize_t _ais_service_write_nr(struct bt_conn *p_conn, const struct bt_gatt_attr *p_attr,
const void *p_buf, u16_t len, u16_t offset, u8_t flags)
{
//BT_DBG("len %d: %s", len, bt_hex(p_buf, len));
return _ais_service_write(p_conn, p_attr, p_buf, len, offset, flags);
}
static void _ais_service_ccc_cfg_changed(const struct bt_gatt_attr *p_attr, uint16_t value)
{
}
/* AIS OTA Service Declaration */
static struct bt_gatt_attr _ais_srv_attrs[] = {
BT_GATT_PRIMARY_SERVICE(AIS_SERVICE_UUID),
BT_GATT_CHARACTERISTIC(AIS_READ_UUID, BT_GATT_CHRC_READ, BT_GATT_PERM_READ, _ais_server_read, NULL, NULL),
BT_GATT_CHARACTERISTIC(AIS_WRITE_UUID, BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE, BT_GATT_PERM_WRITE,
NULL, _ais_service_write, NULL),
BT_GATT_CHARACTERISTIC(AIS_INDICATE_UUID, BT_GATT_CHRC_READ | BT_GATT_CHRC_INDICATE,
BT_GATT_PERM_READ | BT_GATT_PERM_WRITE, _ais_server_read, NULL, NULL),
BT_GATT_CCC(_ais_service_ccc_cfg_changed, BT_GATT_PERM_READ | BT_GATT_PERM_WRITE),
BT_GATT_CHARACTERISTIC(AIS_WRITE_WO_RESP_UUID, BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE_WITHOUT_RESP,
BT_GATT_PERM_WRITE, NULL, _ais_service_write_nr, NULL),
BT_GATT_CHARACTERISTIC(AIS_NOTIFY_UUID, BT_GATT_CHRC_READ | BT_GATT_CHRC_NOTIFY,
BT_GATT_PERM_READ | BT_GATT_PERM_WRITE, _ais_server_read, NULL, NULL),
BT_GATT_CCC(_ais_service_ccc_cfg_changed, BT_GATT_PERM_READ | BT_GATT_PERM_WRITE),
};
static struct bt_gatt_service _ais_srv = BT_GATT_SERVICE(_ais_srv_attrs);
#ifdef CONFIG_BT_MESH_MULTIADV
static u8_t g_ais_adv_data[14] = {
0xa8, 0x01, //taobao
0x85, //vid & sub
0x15, //FMSK
0x15, 0x11, 0x22, 0x33, //PID
0xAA, 0xBB, 0xCC, 0x11, 0x22, 0x33 //MAC
};
struct bt_data g_ais_adv[] = {
BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)),
BT_DATA_BYTES(BT_DATA_UUID16_SOME, 0xB3, 0xFE),
BT_DATA(BT_DATA_MANUFACTURER_DATA, g_ais_adv_data, 14),
};
static const struct bt_data g_ais_sd[] = {
BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)),
BT_DATA(BT_DATA_NAME_COMPLETE, CONFIG_BT_DEVICE_NAME, (sizeof(CONFIG_BT_DEVICE_NAME) - 1)),
};
struct bt_le_adv_param fast_adv_param = {
.options = (BT_LE_ADV_OPT_CONNECTABLE | BT_LE_ADV_OPT_ONE_TIME),
.interval_min = BT_GAP_ADV_FAST_INT_MIN_2,
.interval_max = BT_GAP_ADV_FAST_INT_MAX_2,
.own_addr = NULL,
};
#endif
int genie_ais_state_set(uint8_t state)
{
genie_ais_ctx.state = state;
return 0;
}
uint8_t genie_ais_state_get(void)
{
return genie_ais_ctx.state;
}
#ifdef CONFIG_BT_MESH_MULTIADV
int g_multiadv_instant_id;
static int multi_adv_init(void)
{
int err = -1;
genie_crypto_adv_create(g_ais_adv_data, 0);
err = bt_le_multi_adv_start(&fast_adv_param, g_ais_adv, ARRAY_SIZE(g_ais_adv), g_ais_sd, ARRAY_SIZE(g_ais_sd), &g_multiadv_instant_id);
if (err)
{
BT_ERR("Multi Advertising failed to start (err %d)\n", err);
}
return err;
}
#endif
int genie_ais_init(void)
{
#ifdef CONFIG_BT_MESH_MULTIADV
multi_adv_init();
#endif
bt_gatt_service_register(&_ais_srv);
k_timer_init(&genie_ais_ctx.state_update_timer, state_update_timer_cb, NULL);
k_timer_init(&genie_ais_ctx.disconnect_timer, _ais_dis_timer_cb, NULL);
printf("ais init\r\n");
return 0;
}
int genie_ais_pre_init(void)
{
printf("ais pre init\r\n");
memset(&genie_ais_ctx, 0, sizeof(genie_ais_ctx));
return 0;
}
| YifuLiu/AliOS-Things | components/genie_service/core/src/genie_ais.c | C | apache-2.0 | 16,949 |
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#include <stdlib.h>
//#include <aos/aos.h>
#include <aos/kernel.h>
#include <port/mesh_hal_ble.h>
#include "mesh.h"
#include "common/log.h"
#include "flash.h"
#include "genie_service.h"
#include "genie_sal_uart.h"
#define at_debug printf
static const at_cmd_t genie_at_commands[] = {
//AT+CMD AT+CMD=? AT+CMD?
{BLE_MESH_ADV, genie_at_cmd_adv_start, "AT+" BLE_MESH_ADV "=<mode>", genie_at_cmd_adv_query},
{BLE_MESH_RESET, genie_at_cmd_mesh_reset, "AT+" BLE_MESH_RESET, NULL},
{BLE_MESH_REBOOT, genie_at_cmd_reboot, "AT+" BLE_MESH_REBOOT, NULL},
{BLE_MESH_INFO, NULL, "AT+" BLE_MESH_INFO, genie_at_cmd_mesh_info},
{BLE_MESH_VER, NULL, "AT+" BLE_MESH_VER, genie_at_cmd_mesh_ver},
{BLE_MESH_MAC, NULL, "AT+" BLE_MESH_MAC, genie_at_cmd_mesh_mac},
{BLE_MESH_FACTY_TEST, genie_at_cmd_facty_test, "AT+" BLE_MESH_FACTY_TEST, NULL},
{BLE_MESH_LOG, genie_at_cmd_mesh_log, "AT+" BLE_MESH_LOG "=<mode>", genie_at_cmd_mesh_log_query},
{BLE_MESH_TEST, genie_at_cmd_mesh_test, "AT+" BLE_MESH_TEST "=<opcode>,[param]", NULL},
{BLE_MESH_GROUP, genie_at_cmd_mesh_group, "AT+" BLE_MESH_GROUP "=<addr1>,[addr2]...", genie_at_cmd_mesh_group_query},
{BLE_MESH_MSG_TX, genie_at_cmd_mesh_trans_send, "AT+" BLE_MESH_MSG_TX "=<data>", NULL},
{BLE_MESH_EVENT, NULL, "+" BLE_MESH_EVENT ":<state>", NULL},
{BLE_MESH_MSG_RX, NULL, "+" BLE_MESH_MSG_RX ":<len>,<data>", NULL},
{NULL, NULL, NULL, NULL},
};
static u8_t g_current_adv_mode = MESH_ADV_START;
static uint8_t test_dev_mac[6] = {0};
static char *str_chr(char *d, char *s, int c)
{
int i = 0;
char *q = d;
char *p = s;
for (i = 0; *(s + i) != (char)c; i++)
{
*(q++) = *(p++);
if (*(s + i) == '\0')
{
return NULL;
}
}
*(q++) = '\0';
return d;
}
static char *char_cut(char *d, char *s, int b, int e)
{
char *stc;
if (b == '\0')
{
return NULL;
}
stc = strchr(s, b);
if (stc == NULL)
{
at_debug("not execute\r\n");
return NULL;
}
stc++;
str_chr(d, stc, e);
return d; //(char *)d;
}
static int char2_hex(const char *c, uint8_t *x)
{
if (*c >= '0' && *c <= '9')
{
*x = *c - '0';
}
else if (*c >= 'a' && *c <= 'f')
{
*x = *c - 'a' + 10;
}
else if (*c >= 'A' && *c <= 'F')
{
*x = *c - 'A' + 10;
}
else
{
return -EINVAL;
}
return 0;
}
static int str2_char(const char *str, uint8_t *addr)
{
int i, j;
uint8_t tmp;
if (strlen(str) != 17)
{
return -EINVAL;
}
for (i = 0, j = 1; *str != '\0'; str++, j++)
{
if (!(j % 3) && (*str != ':'))
{
return -EINVAL;
}
else if (*str == ':')
{
i++;
continue;
}
addr[i] = addr[i] << 4;
if (char2_hex(str, &tmp) < 0)
{
return -EINVAL;
}
addr[i] |= tmp;
}
return 0;
}
static int argv_type(char *s)
{
int flag = 0;
flag |= AT_CMD_NO_ADD;
for (int i = 0; *(s + i) != '\0'; i++)
{
if (*(s + i) == '+')
{
flag = flag & (~0x1);
flag |= AT_CMD_ADD; //+ no =
}
if (*(s + i) == '=')
{ //, or not ,
if (*(s + i + 1) == '?')
{
return AT_CMD_FIND;
}
else if (*(s + i + 1) != '\0')
{
return AT_CMD_DOU;
}
else
{
return 0;
}
}
if (*(s + i) == '?')
{
flag = flag & (~0x2); //no +
flag |= AT_CMD_QUERY;
}
}
return flag;
}
static int argc_len(char *s)
{
int i = 0;
int j = 0;
for (i = 0; *(s + i) != '\0'; i++)
{
if ((*(s + i) == ',') || (*(s + i) == '?') || (*(s + i) == '='))
{
j++;
}
}
return j;
}
static void cmd_cli_func(int type, int argc, char **argv)
{
int i = 0;
int err;
if (argc < 2)
{
genie_sal_uart_send_str("AT support commands\r\n");
for (i = 0; genie_at_commands[i].cmd_name != NULL; i++)
{
genie_sal_uart_send_str("%s %s\r\n", genie_at_commands[i].cmd_name, genie_at_commands[i].help);
}
return;
}
for (i = 0; genie_at_commands[i].cmd_name != NULL; i++)
{
if (strlen(genie_at_commands[i].cmd_name) == strlen(argv[1]) &&
!strncmp(genie_at_commands[i].cmd_name, argv[1], strlen(genie_at_commands[i].cmd_name)))
{
if (type == AT_OP_EXECUTE)
{
if (genie_at_commands[i].cb)
{
err = genie_at_commands[i].cb(argc - 1, &argv[1]);
if (err == 0)
{
genie_sal_uart_send_str(AT_OK_STR);
}
else
{
genie_sal_uart_send_str(AT_CME_ERROR_STR, err);
}
}
else
{
genie_sal_uart_send_str(AT_CME_ERROR_STR, AT_ERR_NOT_FOUND);
}
}
else if (type == AT_OP_FCURRENT)
{
if (genie_at_commands[i].fcb)
{
err = genie_at_commands[i].fcb(argc - 1, &argv[1]);
if (err == 0)
{
genie_sal_uart_send_str(AT_OK_STR);
}
else
{
genie_sal_uart_send_str(AT_CME_ERROR_STR, err);
}
}
else
{
genie_sal_uart_send_str(AT_CME_ERROR_STR, AT_ERR_NOT_FOUND);
}
}
else
{ //HLOOKUP
if (genie_at_commands[i].help)
{
genie_sal_uart_send_str("%s\n", genie_at_commands[i].help);
genie_sal_uart_send_str(AT_OK_STR);
}
}
break;
}
}
if ((i + 1) == ARRAY_SIZE(genie_at_commands))
{
genie_sal_uart_send_str(AT_CME_ERROR_STR, AT_ERR_NOT_FOUND);
}
}
static int is_at_cmd(char *data)
{
if (strlen(data) < 2)
{
return 1;
}
if (((*data == 'A') || (*data == 'a')) && ((*(data + 1) == 'T') || (*(data + 1) == 't')))
{
return 0;
}
return 1;
}
int genie_at_cmd_parser(char data[])
{
char argv[AT_MAX_ARGC][AT_MAX_ARGV_LEN];
char *hcc;
char *argqv[AT_MAX_ARGC];
if (is_at_cmd(data))
{
return -1;
}
memset(argv, 0, sizeof(argv));
int ustype = argv_type(data);
argv[0][0] = 'A';
argv[0][1] = 'T';
argv[0][2] = '\0';
//at_debug("ustype: %d, data: %s\n", ustype, data);
switch (ustype)
{
case AT_CMD_NO_ADD:
cmd_cli_func(AT_OP_HELP, 1, NULL);
genie_sal_uart_send_str(AT_OK_STR);
break;
case AT_CMD_ADD: //execute
if (char_cut(argv[1], data, '+', '\0') == NULL)
{
return -1;
}
argqv[0] = (char *)(&argv[0]);
argqv[1] = (char *)(&argv[1]);
cmd_cli_func(AT_OP_EXECUTE, 2, (char **)(&argqv));
break;
case AT_CMD_QUERY: //?
if (char_cut((char *)argv[1], data, '+', '?') == NULL)
{
return -1;
}
argqv[0] = (char *)(&argv[0]);
argqv[1] = (char *)(&argv[1]);
cmd_cli_func(AT_OP_FCURRENT, 2, (char **)(&argqv));
break;
case AT_CMD_DOU:
if (char_cut((char *)argv[1], data, '+', '=') == NULL)
{
return -1;
}
hcc = strchr(data, '=');
int num = argc_len(hcc);
//at_debug("num:%d, len:%d\n", num, strlen(hcc));
if ((num > AT_MAX_ARGC - 2) || (strlen(hcc) > (AT_MAX_ARGC * AT_MAX_ARGV_LEN)))
{
at_debug("argv out of the max len\r\n");
return -1;
}
if (num == 0)
{
at_debug("num:err 0\r\n");
return -1;
}
if (num == 1)
{
char_cut((char *)argv[2], hcc, '=', '\0');
argqv[2] = (char *)(&argv[2]);
}
else
{
char_cut((char *)argv[2], hcc, '=', ',');
argqv[2] = (char *)(&argv[2]);
for (int i = 1; i < num; i++)
{
hcc = strchr(hcc, ',');
char_cut((char *)argv[2 + i], hcc, ',', ',');
argqv[2 + i] = (char *)(&argv[2 + i]);
hcc++;
}
}
argqv[0] = (char *)(&argv[0]);
argqv[1] = (char *)(&argv[1]);
cmd_cli_func(AT_OP_EXECUTE, num + 2, (char **)(&argqv));
break;
case AT_CMD_FIND: //=?
hcc = strrchr(data, '+');
hcc++;
str_chr(argv[1], hcc, '=');
argqv[0] = (char *)(&argv[0]);
argqv[1] = (char *)(&argv[1]);
cmd_cli_func(AT_OP_HLOOKUP, 2, (char **)(&argqv));
break;
default:
at_debug("unknow type:%d\r\n", ustype);
return -1;
}
return 0;
}
int genie_at_cmd_reboot(int argc, char *argv[])
{
/* AT+REBOOT */
if (argc > 1)
{
return AT_ERR_FORMAT;
}
genie_sal_uart_send_str("OK\r\n");
aos_msleep(30);
aos_reboot();
return 0;
}
int genie_at_cmd_mesh_reset(int argc, char *argv[])
{
/* AT+MESHRST */
if (argc > 1)
{
return AT_ERR_FORMAT;
}
genie_sal_uart_send_str("OK\r\n");
genie_event(GENIE_EVT_HW_RESET_START, NULL);
return 0;
}
int genie_at_cmd_adv_start(int argc, char *argv[])
{
/* AT+MESHADV=<mode> */
uint8_t mode = 0;
if (argc != 2)
{
return AT_ERR_FORMAT;
}
mode = strtoul(argv[1], NULL, 0);
if (mode == MESH_ADV_CLOSE)
{
/* close adv */
bt_mesh_adv_stop();
bt_mesh_prov_disable(BT_MESH_PROV_GATT | BT_MESH_PROV_ADV);
}
else if (mode == MESH_ADV_START)
{
/* start adv */
bt_mesh_adv_stop();
bt_mesh_prov_enable(BT_MESH_PROV_GATT | BT_MESH_PROV_ADV);
genie_event(GENIE_EVT_SDK_MESH_PBADV_START, NULL);
}
else if (mode == MESH_ADV_SILENT)
{
/* start silent adv */
genie_event(GENIE_EVT_SDK_MESH_PBADV_TIMEOUT, NULL);
}
else
{
return AT_ERR_FORMAT;
}
g_current_adv_mode = mode;
return 0;
}
int genie_at_cmd_adv_query(int argc, char *argv[])
{
/* AT+MESHADV? */
if (argc > 1)
{
return AT_ERR_FORMAT;
}
genie_sal_uart_send_str(AT_RESPONSE_STR "%d\r\n", BLE_MESH_ADV, g_current_adv_mode);
return 0;
}
int genie_at_cmd_mesh_log(int argc, char *argv[])
{
/* AT+MESHLOG=<mode> */
uint8_t mode = 0;
if (argc != 2)
{
return AT_ERR_FORMAT;
}
mode = strtoul(argv[1], NULL, 0);
if ((mode == 1) || (mode == 0))
{
g_mesh_log_mode = mode;
if (!g_mesh_log_mode)
{
genie_sal_uart_send_str("OK\r\n");
aos_set_log_level(LOG_EMERG);
}
else
{
aos_set_log_level(GENIE_MESH_DEFAULT_LOG_LEVEL);
}
return 0;
}
else
{
return AT_ERR_FORMAT;
}
}
int genie_at_cmd_mesh_log_query(int argc, char *argv[])
{
/* AT+MESHLOG? */
if (argc > 1)
{
return AT_ERR_FORMAT;
}
genie_sal_uart_send_str("+%s:%d\r\n", BLE_MESH_LOG, g_mesh_log_mode);
return 0;
}
int genie_at_cmd_mesh_info(int argc, char *argv[])
{
bool status;
/* AT+MESHINF? */
if (argc > 1)
{
return AT_ERR_FORMAT;
}
status = bt_mesh_is_provisioned();
genie_sal_uart_send_str(AT_RESPONSE_STR "%d\r\n", BLE_MESH_INFO, status);
return 0;
}
int genie_at_cmd_mesh_ver(int argc, char *argv[])
{
/* AT+MESHVER? */
if (argc > 1)
{
return AT_ERR_FORMAT;
}
genie_sal_uart_send_str(AT_RESPONSE_STR "%08x\r\n", BLE_MESH_VER, genie_version_appver_get());
return 0;
}
int genie_at_cmd_mesh_mac(int argc, char *argv[])
{
uint8_t addr[6] = {0};
/* AT+MESHMAC? */
if (argc > 1)
{
return AT_ERR_FORMAT;
}
hal_flash_read_mac_params(addr, sizeof(addr));
genie_sal_uart_send_str(AT_RESPONSE_STR " %02x:%02x:%02x:%02x:%02x:%02x\r\n", BLE_MESH_MAC, addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
return 0;
}
int genie_at_cmd_facty_test(int argc, char *argv[])
{
int ret = -1;
/* AT+FACTYTEST */
if (argc > 1)
{
return AT_ERR_FORMAT;
}
ret = genie_sal_ble_set_factory_flag();
if (ret != 0)
{
return AT_ERR_EXE;
}
genie_sal_uart_send_str("OK\r\n");
aos_reboot();
return 0;
}
static int8_t get_rssi_result = 0;
static void get_ble_rssi_cb(uint8_t mac[6], int16_t rssi)
{
if (memcmp(test_dev_mac, mac, sizeof(test_dev_mac)) == 0)
{
get_rssi_result = 0;
memset(test_dev_mac, 0, sizeof(test_dev_mac));
genie_sal_uart_send_str(AT_RESPONSE_STR "%d,%d\r\n", BLE_MESH_TEST, MESH_TEST_RSSI, rssi);
}
else
{
get_rssi_result = -1;
at_debug("cann't find mac: %s rssi\n", bt_hex(test_dev_mac, sizeof(test_dev_mac)));
}
}
int genie_at_cmd_mesh_test(int argc, char *argv[])
{
uint32_t opcode;
int err;
/* AT+MESHTEST=<opcode>,[param] */
if (argc < 2)
{
return AT_ERR_FORMAT;
}
opcode = strtoul(argv[1], NULL, 0);
switch (opcode)
{
case MESH_TEST_RSSI:
if (argc < 3) {
return AT_ERR_FORMAT;
}
err = str2_char(argv[2], test_dev_mac);
//at_debug("test_dev_mac: %s\n", bt_hex(test_dev_mac, sizeof(test_dev_mac)));
if (err != 0)
{
at_debug("invalid address\n");
return AT_ERR_FORMAT;
}
/* start scan,find the dev and get rssi */
err = genie_sal_ble_get_rssi(test_dev_mac, (genie_sal_ble_get_rssi_cb)get_ble_rssi_cb, 5000);
if (err != 0)
{
at_debug("start scan error\n");
return AT_ERR_EXE;
}
break;
default:
return AT_ERR_FORMAT;
}
return get_rssi_result;
}
int genie_at_cmd_mesh_group(int argc, char *argv[])
{
u16_t group_list[CONFIG_BT_MESH_MODEL_GROUP_COUNT] = {0};
int group_num = argc - 1;
/* AT+MESHGRP=<addr1>,[addr2]... */
if (argc > (CONFIG_BT_MESH_MODEL_GROUP_COUNT + 1) || argc < 2)
{
return AT_ERR_FORMAT;
}
for (int i = 0; i < group_num; i++)
{
group_list[i] = strtoul(argv[i + 1], NULL, 0);
if (group_list[i] < GENIE_ADDR_MIN || group_list[i] > GENIE_ADDR_MAX)
{
return AT_ERR_FORMAT;
}
}
/* set group addr */
if (genie_storage_write_sub(group_list) != GENIE_STORAGE_SUCCESS)
{
return AT_ERR_EXE;
}
/* get group addr */
if (genie_storage_read_sub(g_sub_list) != GENIE_STORAGE_SUCCESS)
{
return AT_ERR_EXE;
}
return 0;
}
int genie_at_cmd_mesh_group_query(int argc, char *argv[])
{
u16_t group_list[CONFIG_BT_MESH_MODEL_GROUP_COUNT] = {0};
char result[100] = {0};
int len = 0;
/* AT+MESHGRP? */
if (argc > 2)
{
return AT_ERR_FORMAT;
}
/* get group addr */
if (genie_storage_read_sub(group_list) != GENIE_STORAGE_SUCCESS)
{
return AT_ERR_EXE;
}
len = snprintf(result, sizeof(result), AT_RESPONSE_STR, BLE_MESH_GROUP);
for (int i = 0; i < CONFIG_BT_MESH_MODEL_GROUP_COUNT; i++)
{
if (len < (sizeof(result) - 5) && group_list[i] != 0x0000)
{
len += snprintf(result + len, sizeof(result) - len, "0x%04X,", group_list[i]);
}
}
result[len - 1] = '\0';
genie_sal_uart_send_str("%s\r\n", result);
return 0;
}
static int _send_trans_msg(char *data)
{
uint8_t count = 0;
uint8_t msg_b[GENIE_HAL_BLE_SEND_MAX_DATA_LEN];
uint8_t ret = 0;
count = strlen(data) >> 1;
if (count > GENIE_HAL_BLE_SEND_MAX_DATA_LEN)
{
at_debug("data out of the max len\n");
return AT_ERR_FORMAT;
}
memset(msg_b, 0x0, sizeof(msg_b));
ret = stringtohex(data, msg_b, count);
if (ret == 0)
{
at_debug("stringtohex error\n");
return AT_ERR_FORMAT;
}
if (genie_sal_ble_send_msg(0, msg_b, count))
{
return AT_ERR_EXE;
}
return 0;
}
int genie_at_cmd_mesh_trans_send(int argc, char *argv[])
{
/* AT+MESHMSGTX=<data> */
if (argc < 2)
{
return AT_ERR_FORMAT;
}
return _send_trans_msg(argv[1]);
}
int genie_at_cmd_send_data_to_mcu(uint8_t *p_data, uint16_t data_len)
{
int i = 0;
int len = 0;
char *p_send_buff = NULL;
uint16_t send_buff_len = 0;
send_buff_len = strlen(BLE_MESH_MSG_RX) + 2 * data_len + 10;
p_send_buff = (char *)aos_malloc(send_buff_len);
if (NULL == p_send_buff)
{
return -1;
}
memset(p_send_buff, '\0', send_buff_len);
len = snprintf(p_send_buff, send_buff_len, "\r\n" AT_RESPONSE_STR "%d,", BLE_MESH_MSG_RX, data_len);
for (i = 0; i < data_len; i++)
{
len += snprintf(p_send_buff + len, send_buff_len - len, "%02X", p_data[i]);
}
genie_sal_uart_send_str("%s\r\n", p_send_buff);
aos_free(p_send_buff);
return 0;
}
int genie_at_output_event(genie_event_e event, void *p_arg)
{
char result[100] = {0};
int len = 0;
/* +MESHEVT:<state> */
len = snprintf(result, sizeof(result), AT_RESPONSE_STR, BLE_MESH_EVENT);
if (event == GENIE_EVT_MESH_READY)
{
len += snprintf(result + len, sizeof(result) - len, "0x%02X", MESH_EVENT_DEV_READY);
}
else if (event == GENIE_EVT_SDK_MESH_PROV_SUCCESS)
{
len += snprintf(result + len, sizeof(result) - len, "0x%02X", MESH_EVENT_PROV_SUCCESS);
g_current_adv_mode = MESH_ADV_CLOSE;
}
else if (event == GENIE_EVT_SDK_MESH_PROV_FAIL)
{
len += snprintf(result + len, sizeof(result) - len, "0x%02X", MESH_EVENT_PROV_FAILED);
}
else
{
if (event == GENIE_EVT_SDK_MESH_SILENT_START)
{
g_current_adv_mode = MESH_ADV_SILENT;
}
return 0;
}
genie_sal_uart_send_str("%s\r\n", result);
return 0;
}
| YifuLiu/AliOS-Things | components/genie_service/core/src/genie_at.c | C | apache-2.0 | 18,546 |
#include <stdint.h>
#include "genie_service.h"
#include "genie_sal_ble.h"
#include "genie_sal_uart.h"
static uint8_t g_rssi_mac[GENIE_BLE_MAC_LEN];
static void genie_bin_cmds_send(uint16_t opcode, uint8_t *p_data, uint16_t len)
{
uint8_t checksum = 0;
genie_sal_uart_send_one_byte(opcode >> 8);
genie_sal_uart_send_one_byte(opcode & 0xff);
genie_sal_uart_send_one_byte(len >> 8);
genie_sal_uart_send_one_byte(len & 0xff);
checksum += len >> 8;
checksum += (len & 0xff);
while (len--)
{
checksum += *p_data;
genie_sal_uart_send_one_byte(*p_data++);
}
genie_sal_uart_send_one_byte(checksum);
}
static void genie_bin_cmds_error(uint8_t err_code)
{
uint8_t code = err_code;
genie_bin_cmds_send(GENIE_BIN_OPCODE_ERR, &code, 1);
}
static uint16_t mesh_adv_ctl(uint8_t ctl, uint8_t *resp)
{
resp[0] = 0x01;
resp[1] = ctl;
switch (ctl)
{
case 0x00:
{
bt_mesh_adv_stop();
bt_mesh_prov_disable(BT_MESH_PROV_GATT | BT_MESH_PROV_ADV);
}
break;
case 0x01:
{
bt_mesh_adv_stop();
bt_mesh_prov_enable(BT_MESH_PROV_GATT | BT_MESH_PROV_ADV);
genie_event(GENIE_EVT_SDK_MESH_PBADV_START, NULL);
}
break;
case 0x02:
{
genie_event(GENIE_EVT_SDK_MESH_PBADV_TIMEOUT, NULL);
}
break;
default:
break;
}
return 2;
}
static uint16_t reset_prov_info(uint8_t *resp)
{
resp[0] = 0x03;
resp[1] = 0x01;
resp[2] = 0x01;
genie_event(GENIE_EVT_HW_RESET_START, NULL);
return 3;
}
static void _send_rssi_msg(int8_t rssi)
{
uint8_t resp[9];
resp[0] = 0x03;
resp[1] = 0x02;
//get mac
memcpy(resp + 2, g_rssi_mac, GENIE_BLE_MAC_LEN);
//get rssi
resp[8] = rssi;
genie_bin_cmds_send(GENIE_BIN_OPCODE_CMD, resp, 9);
}
static uint16_t get_device_info(uint8_t type, uint8_t *resp)
{
switch (type)
{
case 0x00:
{ //Get provision info
resp[0] = 0x03;
resp[1] = 0x03;
if (bt_mesh_is_provisioned())
{
resp[2] = 0x01;
}
else
{
resp[2] = 0x00;
}
return 3;
}
case 0x01:
{ //Get device version
uint32_t app_version = genie_version_appver_get();
resp[0] = GENIE_CTL_DEVIE_INFO_AND_EVENT;
resp[1] = 0x06;
resp[2] = (uint8_t)(app_version >> 24);
resp[3] = (uint8_t)(app_version >> 16);
resp[4] = (uint8_t)(app_version >> 8);
resp[5] = (uint8_t)(app_version);
return 6;
}
default:
break;
}
return 0;
}
static void genie_bin_cmd_type_data(uint8_t *p_data)
{
uint16_t len = p_data[3] + (p_data[2] << 8);
if (genie_sal_ble_send_msg(0, &p_data[4], len))
{
genie_bin_cmds_error(GENIE_BINARY_CMD_TRANSPARENT_ERR);
}
}
static void get_ble_rssi_cb(uint8_t mac[6], int8_t rssi)
{
if (memcmp(g_rssi_mac, mac, GENIE_BLE_MAC_LEN) == 0)
{
_send_rssi_msg(rssi);
memset(g_rssi_mac, 0, GENIE_BLE_MAC_LEN);
}
else
{
genie_bin_cmds_error(GENIE_BINARY_CMD_GET_RSSI_MAC_NOT_MATCH_ERR);
}
}
static int genie_bin_cmd_update_group_addr(uint8_t *addr_list, int addr_len)
{
int index = 0;
uint8_t group_addr_list[CONFIG_BT_MESH_MODEL_GROUP_COUNT * 2] = {0};
if ((addr_len > CONFIG_BT_MESH_MODEL_GROUP_COUNT * 2) || ((addr_len % 2) != 0))
{
return -1;
}
memset(group_addr_list, 0, CONFIG_BT_MESH_MODEL_GROUP_COUNT * 2);
memcpy(group_addr_list, addr_list, addr_len);
for (index = 0; index < addr_len; index++)
{
if ((index % 2) == 0)
{
if ((group_addr_list[index + 1] & 0xC0) != 0xC0) //invalid group address
{
return -2;
}
}
}
/* set group addr */
if (genie_storage_write_sub((uint16_t *)group_addr_list) != GENIE_STORAGE_SUCCESS)
{
return -3;
}
/* get group addr */
if (genie_storage_read_sub((uint16_t *)g_sub_list) != GENIE_STORAGE_SUCCESS)
{
return -3;
}
return 0;
}
static int get_mesh_group_addr(uint8_t *response)
{
int i = 0;
int j = 0;
uint8_t group_addr_list[CONFIG_BT_MESH_MODEL_GROUP_COUNT * 2] = {0};
/* get group addr */
if (genie_storage_read_sub((uint16_t *)group_addr_list) != GENIE_STORAGE_SUCCESS)
{
return -1;
}
for (i = 0; i < CONFIG_BT_MESH_MODEL_GROUP_COUNT * 2; i++)
{
if (i % 2 == 0)
{
if ((group_addr_list[i + 1] & 0xC0) == 0xC0) //valid group address
{
response[j] = group_addr_list[i];
response[j + 1] = group_addr_list[i + 1];
j += 2;
}
}
}
return j;
}
static void genie_bin_cmd_type_command(uint8_t *p_data)
{
uint8_t *p_u8 = p_data;
uint16_t len = p_u8[3] + (p_u8[2] << 8);
uint8_t resp[20];
uint16_t resp_len = 0;
switch (p_u8[4])
{
case GENIE_CTL_MESH_ADV:
if (len == 2)
{
resp_len = mesh_adv_ctl(p_u8[5], resp);
}
break;
case GENIE_CTL_CLEAR_PROV_INFO:
if (len == 1)
{
resp_len = reset_prov_info(resp);
}
break;
case GENIE_CTL_TEST_MODE:
if (len == 8)
{
if (p_u8[5] == 0x00)
{
memcpy(g_rssi_mac, &p_u8[6], GENIE_BLE_MAC_LEN); //backup mac addr
if (genie_sal_ble_get_rssi(g_rssi_mac, (genie_sal_ble_get_rssi_cb)get_ble_rssi_cb, 5000) < 0)
{
return genie_bin_cmds_error(GENIE_BINARY_CMD_GET_RSSI_BLE_ERR);
}
}
else
{
return genie_bin_cmds_error(GENIE_BINARY_CMD_GET_RSSI_INPUT_ERR);
}
}
else
{
return genie_bin_cmds_error(GENIE_BINARY_CMD_GET_RSSI_INPUT_ERR);
}
break;
case GENIE_CTL_DEVICE_INFO:
if (len == 2)
{
resp_len = get_device_info(p_u8[5], resp);
}
break;
case GENIE_CTL_REBOOT_DEVICE:
if (len == 1)
{
aos_reboot();
}
break;
case GENIE_CTL_UPDATE_GROUP_ADDR:
{
int ret = 0;
resp[0] = GENIE_CTL_UPDATE_GROUP_ADDR_RESPONSE;
ret = genie_bin_cmd_update_group_addr(&p_u8[5], len - 1);
if (0 == ret)
{
resp[1] = 0x00; //successful
resp_len = 2;
}
else if (-1 == ret)
{
return genie_bin_cmds_error(GENIE_BINARY_CMD_UPDATE_GROUP_ADDR_LEN_ERR);
}
else if (-2 == ret)
{
return genie_bin_cmds_error(GENIE_BINARY_CMD_UPDATE_GROUP_ADDR_INVALID_ERR);
}
else if (-3 == ret)
{
return genie_bin_cmds_error(GENIE_BINARY_CMD_UPDATE_GROUP_ADDR_FLASH_ERR);
}
}
break;
case GENIE_CTL_GET_GROUP_ADDR:
{
if (len == 1)
{
resp[0] = GENIE_CTL_GET_GOURP_ADDR_RESPONSE;
resp_len = get_mesh_group_addr(&resp[2]);
if (resp_len > 0) //Have valid group addr
{
resp[1] = 0x00;
resp_len += 2;
}
else //Have no valid group addr
{
resp[1] = 0x01;
resp_len = 2;
}
}
}
break;
case GENIE_CTL_FACTORY_TEST:
{
if (genie_sal_ble_set_factory_flag() != 0)
{
return genie_bin_cmds_error(GENIE_BINARY_CMD_START_FACTORY_ERR);
}
else
{
resp[0] = GENIE_CTL_FACTORY_TEST;
resp[1] = 0x00;
resp_len = 2;
genie_bin_cmds_send(GENIE_BIN_OPCODE_CMD, resp, resp_len);
aos_msleep(1000);
aos_reboot();
}
}
break;
case GENIE_CTL_SWITCH_DEBUG:
{
if (len == 2)
{
if (p_u8[5] > 0)
{
g_mesh_log_mode = 1;
aos_set_log_level(GENIE_MESH_DEFAULT_LOG_LEVEL);
}
else
{
g_mesh_log_mode = 0;
aos_set_log_level(LOG_EMERG);
}
resp[0] = GENIE_CTL_SWITCH_DEBUG;
resp[1] = 0x00;
resp_len = 2;
}
else
{
resp[0] = GENIE_CTL_SWITCH_DEBUG;
resp[1] = 0x01;
resp_len = 2;
}
}
break;
default:
break;
}
//if resp_len = 0 do nothing
if (resp_len > 0) //need response
{
genie_bin_cmds_send(GENIE_BIN_OPCODE_CMD, resp, resp_len);
}
else if (resp_len < 0)
{
genie_bin_cmds_error(GENIE_BINARY_CMD_UNKNOW_ERR);
}
}
int genie_bin_cmds_handle(uint8_t *p_data, uint8_t data_len)
{
uint16_t len = 0;
uint16_t index = 0;
uint8_t checksum = 0;
if ((data_len > 0) && (p_data[0] != 0xFF) && (p_data[0] != 0xFE))
{
return 0; //Don't send any data by UART
}
if (data_len < GENIE_BIN_MIN_DATA_LEN)
{
genie_bin_cmds_error(GENIE_BINARY_CMD_TOTAL_LEN_ERR);
return -1;
}
len = p_data[3] + (p_data[2] << 8);
if (len != (data_len - 5))
{
genie_bin_cmds_error(GENIE_BINARY_CMD_DATA_LEN_ERR);
return -1;
}
checksum += p_data[2];
checksum += p_data[3];
while (index < len)
{
checksum += p_data[4 + index];
index++;
}
if (checksum != p_data[data_len - 1])
{
genie_bin_cmds_error(GENIE_BINARY_CMD_CRC_ERR);
return -1;
}
if (((p_data[0] << 8) | p_data[1]) == GENIE_BIN_OPCODE_DATA)
{
genie_bin_cmd_type_data(p_data);
}
else if (((p_data[0] << 8) | p_data[1]) == GENIE_BIN_OPCODE_CMD)
{
genie_bin_cmd_type_command(p_data);
}
return 0;
}
int genie_bin_cmd_handle_event(genie_event_e event, void *p_arg)
{
uint8_t report_data[2];
uint8_t report_data_len = 0;
if (event == GENIE_EVT_MESH_READY)
{
report_data[0] = 0x03;
report_data[1] = 0x04;
report_data_len = 2;
}
else if (event == GENIE_EVT_SDK_MESH_PROV_SUCCESS)
{
report_data[0] = 0x03;
report_data[1] = 0x00;
report_data_len = 2;
}
else if (event == GENIE_EVT_SDK_MESH_PROV_FAIL)
{
report_data[0] = 0x03;
report_data[1] = 0x05;
report_data_len = 2;
}
if (report_data_len > 0)
{
genie_bin_cmds_send(GENIE_BIN_OPCODE_CMD, report_data, report_data_len);
}
return 0;
}
void genie_bin_cmds_send_data_to_mcu(uint8_t *p_data, uint8_t len)
{
genie_bin_cmds_send(GENIE_BIN_OPCODE_DATA, p_data, len);
}
| YifuLiu/AliOS-Things | components/genie_service/core/src/genie_bin_cmds.c | C | apache-2.0 | 10,795 |
/*
* Copyright (C) 2018-2020 Alibaba Group Holding Limited
*/
//#include <aos/aos.h>
#include <aos/cli.h>
#include <hal/hal.h>
#include <stdlib.h> //for atol
#include "hal/flash.h"
#include "common/log.h"
#include "mesh/access.h"
#include "net.h"
#include "access.h"
#include <aos/kernel.h>
#include "genie_service.h"
#include "genie_sal_uart.h"
extern uint8_t g_mesh_log_mode;
static bool send_mesg_working = false;
static aos_timer_t mesg_send_timer;
#define MAC_LEN (6)
#define TIMER_SEND_MODE (255)
#define TIMEOUT_SEND_MODE (254)
#define USER_TIMER_SEND_MODE (253)
#ifndef SYSINFO_PRODUCT_MODEL
#define SYSINFO_PRODUCT_MODEL "ALI_AOS_XXXX"
#endif
static void _get_triple(char *pwbuf, int blen, int argc, char **argv)
{
uint8_t i;
genie_triple_t genie_triple;
genie_storage_status_e ret;
memset(&genie_triple, 0, sizeof(genie_triple_t));
ret = genie_triple_read(&genie_triple.pid, genie_triple.mac, genie_triple.key);
if (ret != GENIE_STORAGE_SUCCESS)
{
GENIE_LOG_ERR("read triple fail(%d)", ret);
return;
}
printk("%d ", (unsigned int)genie_triple.pid);
for (i = 0; i < 16; i++)
{
printk("%02x", genie_triple.key[i]);
}
printk(" ");
for (i = 0; i < 6; i++)
{
printk("%02x", genie_triple.mac[i]);
}
printk("\n");
}
static int genie_cli_set_triple(char *pwbuf, int blen, int argc, char **argv)
{
uint32_t pid;
uint8_t mac[MAC_LEN], read_mac[MAC_LEN];
uint8_t key[16];
uint8_t ret;
if (argc != 4)
{
GENIE_LOG_ERR("para err");
return -1;
}
//pro_id
pid = atol(argv[1]);
if (pid == 0)
{
GENIE_LOG_ERR("pid err");
return -1;
}
//key
if (strlen(argv[2]) != 32)
{
GENIE_LOG_ERR("key len err");
return -1;
}
ret = stringtohex(argv[2], key, 16);
if (ret == 0)
{
GENIE_LOG_ERR("key format err");
return -1;
}
//addr
if (strlen(argv[3]) != 12)
{
GENIE_LOG_ERR("mac len err");
return -1;
}
ret = stringtohex(argv[3], mac, MAC_LEN);
if (ret == 0)
{
GENIE_LOG_ERR("mac format err");
return -1;
}
#if 0
hal_flash_write_mac_params(mac, MAC_LEN);
memset(read_mac, 0xFF, MAC_LEN);
hal_flash_read_mac_params(read_mac, MAC_LEN);
if (memcmp(mac, read_mac, MAC_LEN))
{
GENIE_LOG_ERR("write mac fail");
return -1;
}
#endif
#if 0
printk("step1: triple : %d\t", pid);
int i = 0;
for (i = 0; i < 16; i++)
{
printk("%02x", key[i]);
}
printk(" ");
for (i = 0; i < 6; i++)
{
printk("%02x", mac[i]);
}
printk("\n");
#endif
ret = genie_triple_write(&pid, mac, key);
return ret;
}
static void _set_triple(char *pwbuf, int blen, int argc, char **argv)
{
genie_cli_set_triple(pwbuf, blen, argc, argv);
_get_triple(pwbuf, blen, argc, argv);
}
static void xtalcap_handle(char *pwbuf, int blen, int argc, char **argv)
{
int xtalcap = 0;
if (!strncmp(argv[1], "set", 3))
{
xtalcap = atoi((char *)(argv[2]));
if (xtalcap < 0 || xtalcap > 64)
{
GENIE_LOG_ERR("input int value[0,64]");
return;
}
if (hal_flash_write_xtalcap_params(&xtalcap, sizeof(xtalcap)) != 0)
{
GENIE_LOG_ERR("write freq failed");
return;
}
}
else if (!strncmp(argv[1], "get", 3))
{
hal_flash_read_xtalcap_params(&xtalcap, sizeof(xtalcap));
GENIE_LOG_INFO("xtalcap:%d", xtalcap);
}
}
static void sn_number_handle(char *pwbuf, int blen, int argc, char **argv)
{
int32_t ret = 0;
uint8_t count = 0;
uint8_t read_sn[24];
if (!strncmp(argv[1], "set", 3))
{
if (argc != 3)
{
GENIE_LOG_ERR("param err");
return;
}
count = strlen(argv[2]);
if (count != CUSTOM_SN_LEN)
{
GENIE_LOG_ERR("sn len error");
return;
}
ret = hal_flash_write_sn_params(argv[2], count);
if (ret != 0)
{
GENIE_LOG_ERR("write sn failed(%d)", ret);
return;
}
memset(read_sn, 0, sizeof(read_sn));
hal_flash_read_sn_params(read_sn, count);
if (memcmp(argv[2], read_sn, count))
{
GENIE_LOG_ERR("write sn failed");
return;
}
}
else if (!strncmp(argv[1], "get", 3))
{
memset(read_sn, 0, sizeof(read_sn));
ret = hal_flash_read_sn_params(read_sn, CUSTOM_SN_LEN);
if (ret != 0)
{
GENIE_LOG_ERR("read sn failed(%d)", ret);
return;
}
if ((read_sn[0] & 0xFF) == 0xFF)
{
GENIE_LOG_INFO("SN:");
return;
}
GENIE_LOG_INFO("SN:%s", read_sn);
}
}
static void _reboot_handle(char *pwbuf, int blen, int argc, char **argv)
{
aos_reboot();
}
static void genie_cli_print_sysinfo(void)
{
uint8_t write_mac[MAC_LEN];
char appver[16];
genie_version_appver_string_get(appver, 16);
printf("\r\nDEVICE:%s\r\n", CONFIG_BT_DEVICE_NAME);
printf("APP VER:%s\r\n", appver);
printf("GenieSDK:V%s\r\n", genie_version_sysver_get());
printf("PROUDUCT:%s\r\n", SYSINFO_PRODUCT_MODEL);
memset(write_mac, 0xFF, MAC_LEN);
hal_flash_read_mac_params(write_mac, MAC_LEN);
printf("MAC:%02X:%02X:%02X:%02X:%02X:%02X\r\n", write_mac[0], write_mac[1], write_mac[2], write_mac[3], write_mac[4], write_mac[5]);
}
static void _get_sw_info(char *pwbuf, int blen, int argc, char **argv)
{
genie_cli_print_sysinfo();
}
static void _get_mm_info(char *pwbuf, int blen, int argc, char **argv)
{
#if RHINO_CONFIG_MM_DEBUG
int total = 0, used = 0, mfree = 0, peak = 0;
aos_get_mminfo(&total, &used, &mfree, &peak);
printf(" total used free peak \r\n");
printf("memory usage: %10d%10d%10d%10d\r\n\r\n",
total, used, mfree, peak);
#endif
}
static uint8_t retry_mode = 0;
static uint8_t *p_payload = NULL;
static genie_transport_payload_param_t *p_transport_payload_param = NULL;
static void mesg_send_timer_cb(void *time, void *args)
{
genie_transport_payload_param_t *p_transport_payload_param = (genie_transport_payload_param_t *)args;
if (p_transport_payload_param == NULL || send_mesg_working == false)
{
aos_timer_stop(&mesg_send_timer);
if (p_payload)
{
hal_free(p_payload);
p_payload = NULL;
}
if (p_transport_payload_param)
{
hal_free(p_transport_payload_param);
p_transport_payload_param = NULL;
}
GENIE_LOG_INFO("stop send timer");
return;
}
genie_transport_send_payload(p_transport_payload_param);
}
static int send_mesg_cb(transport_result_e result_e)
{
GENIE_LOG_INFO("%s(%p)", result_e == 0 ? "success" : "timeout", p_transport_payload_param);
if (retry_mode == TIMEOUT_SEND_MODE) //This is timeout send mode
{
//if (mesg_send_timer.hdl == NULL)
//{
aos_timer_new(&mesg_send_timer, mesg_send_timer_cb, p_transport_payload_param, 10, 0);
//}
aos_timer_stop(&mesg_send_timer);
aos_timer_start(&mesg_send_timer);
}
return 0;
}
static void _send_msg(char *pwbuf, int blen, int argc, char **argv)
{
uint8_t count;
uint8_t ret = 0;
uint8_t opid = 0;
if (argc == 2 && !strncmp(argv[1], "stop", 4))
{
send_mesg_working = false;
GENIE_LOG_INFO("send stop");
return;
}
if (argc != 5)
{
GENIE_LOG_ERR("param err");
return;
}
if (strlen(argv[3]) != 4)
{
GENIE_LOG_ERR("addr len error");
return;
}
if (stringtohex(argv[1], &opid, 1) > 0)
{
retry_mode = atoi(argv[2]);
count = strlen(argv[4]) >> 1;
if (p_payload == NULL)
{
p_payload = hal_malloc(count);
if (p_payload == NULL)
{
GENIE_LOG_ERR("malloc(%d) fail", count);
return;
}
}
else //remalloc
{
hal_free(p_payload);
p_payload = NULL;
p_payload = hal_malloc(count);
if (p_payload == NULL)
{
GENIE_LOG_ERR("malloc(%d) fail", count);
return;
}
}
ret = stringtohex(argv[4], p_payload, count);
if (ret == 0)
{
hal_free(p_payload);
p_payload = NULL;
return;
}
if (p_transport_payload_param == NULL)
{
p_transport_payload_param = hal_malloc(sizeof(genie_transport_payload_param_t));
if (p_transport_payload_param == NULL)
{
hal_free(p_payload);
p_payload = NULL;
GENIE_LOG_ERR("malloc(%d) fail", sizeof(genie_transport_payload_param_t));
return;
}
}
memset(p_transport_payload_param, 0, sizeof(genie_transport_payload_param_t));
p_transport_payload_param->opid = opid;
p_transport_payload_param->p_payload = p_payload;
p_transport_payload_param->payload_len = count;
p_transport_payload_param->retry_cnt = retry_mode;
p_transport_payload_param->result_cb = send_mesg_cb;
ret = stringtohex(argv[3], (uint8_t *)&p_transport_payload_param->dst_addr, 2);
if (ret == 0)
{
hal_free(p_payload);
p_payload = NULL;
hal_free(p_transport_payload_param);
p_transport_payload_param = NULL;
return;
}
//swap addr
uint8_t upper = p_transport_payload_param->dst_addr >> 8;
p_transport_payload_param->dst_addr = upper | (p_transport_payload_param->dst_addr << 8);
if (retry_mode == TIMER_SEND_MODE) //This is auto send mode
{
send_mesg_working = true;
p_transport_payload_param->retry_cnt = 0;
//if (mesg_send_timer.hdl == NULL)
//{
aos_timer_new(&mesg_send_timer, mesg_send_timer_cb, p_transport_payload_param, 1000, 1);
//}
aos_timer_stop(&mesg_send_timer);
aos_timer_start(&mesg_send_timer);
return;
}
else if (retry_mode == USER_TIMER_SEND_MODE && p_transport_payload_param->payload_len > 1) //This is auto send mode
{
send_mesg_working = true;
p_transport_payload_param->retry_cnt = 0;
//if (mesg_send_timer.hdl == NULL)
{
int interval = p_transport_payload_param->p_payload[0];
if (interval == 0)
{
interval = 1;
}
interval = interval * 100; //Unit is 100ms
//skip p_transport_payload_param->p_payload[0]
p_transport_payload_param->p_payload = &p_transport_payload_param->p_payload[1];
p_transport_payload_param->payload_len -= 1;
aos_timer_new(&mesg_send_timer, mesg_send_timer_cb, p_transport_payload_param, interval, 1);
}
aos_timer_stop(&mesg_send_timer);
aos_timer_start(&mesg_send_timer);
return;
}
else if (retry_mode == TIMEOUT_SEND_MODE) //This is timeout send mode
{
send_mesg_working = true;
p_transport_payload_param->retry_cnt = 0;
genie_transport_send_payload(p_transport_payload_param);
return;
}
genie_transport_send_payload(p_transport_payload_param);
if (p_payload)
{
hal_free(p_payload);
p_payload = NULL;
}
if (p_transport_payload_param)
{
hal_free(p_transport_payload_param);
p_transport_payload_param = NULL;
}
}
}
static void genie_system_reset(char *pwbuf, int blen, int argc, char **argv)
{
genie_event(GENIE_EVT_HW_RESET_START, NULL);
}
static void genie_log_onoff(char *pwbuf, int blen, int argc, char **argv)
{
if (argc != 2)
{
GENIE_LOG_ERR("para err");
return;
}
if (!strncmp(argv[1], "on", 2))
{
g_mesh_log_mode = 1;
aos_set_log_level(GENIE_MESH_DEFAULT_LOG_LEVEL);
}
else if (!strncmp(argv[1], "off", 3))
{
g_mesh_log_mode = 0;
aos_set_log_level(LOG_EMERG);
}
else
{
GENIE_LOG_ERR("para err");
return;
}
return;
}
static const struct cli_command genie_cmds[] = {
{"get_tt", "get tri truple", _get_triple},
{"set_tt", "set_tt pid key mac", _set_triple},
{"xtalcap", "xtalcap set 16|xtalcap get", xtalcap_handle},
{"sn", "sn set <value>|sn get", sn_number_handle},
{"reboot", "reboot", _reboot_handle},
{"reset", "reset system", genie_system_reset},
{"log", "log on|off", genie_log_onoff},
{"get_info", "get sw info", _get_sw_info},
{"mm_info", "get mm info", _get_mm_info},
{"mesg", "mesg d4 1 f000 010203", _send_msg},
};
void genie_cli_init(void)
{
#ifdef CONFIG_AOS_CLI
aos_cli_register_commands(&genie_cmds[0], sizeof(genie_cmds) / sizeof(genie_cmds[0]));
#endif
genie_cli_print_sysinfo();
}
| YifuLiu/AliOS-Things | components/genie_service/core/src/genie_cli.c | C | apache-2.0 | 13,431 |
/*
* Copyright (C) 2018-2020 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
//#include <aos/aos.h>
#include <misc/printk.h>
#include <misc/byteorder.h>
#include <tinycrypt/sha256.h>
#include <tinycrypt/constants.h>
#include <port/mesh_hal_sec.h>
#define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_MESH_DEBUG_GENIE_CRYPTO)
#include "common/log.h"
#include "genie_service.h"
static uint8_t g_auth[32];
static uint8_t g_ble_key[32];
uint8_t *genie_crypto_get_auth(const uint8_t random[16])
{
int ret;
genie_triple_t *p_genie_triple = genie_triple_get();
char mac_str[(GENIE_TRIPLE_MAC_SIZE << 1) + 1] = "";
char key_str[(GENIE_TRIPLE_KEY_SIZE << 1) + 1] = "";
char static_str[88] = ""; // pid + ',' + mac + ',' + secret = 8+1+12+1+32+1+32'\0'
char rad_str[33] = "";
struct tc_sha256_state_struct sha256_ctx;
hextostring(p_genie_triple->mac, mac_str, GENIE_TRIPLE_MAC_SIZE);
hextostring(p_genie_triple->key, key_str, GENIE_TRIPLE_KEY_SIZE);
hextostring(random, rad_str, 16);
#ifdef GENIE_OLD_AUTH
sprintf(static_str, "%08x,%s,%s", p_genie_triple->pid, mac_str, key_str);
#else
sprintf(static_str, "%08x,%s,%s,%s", p_genie_triple->pid, mac_str, key_str, rad_str);
#endif
BT_DBG("static oob: %s", static_str);
/* calculate the sha256 of oob info and
* fetch the top 16 bytes as static value
*/
ret = tc_sha256_init(&sha256_ctx);
if (ret != TC_CRYPTO_SUCCESS)
{
BT_ERR("sha256 init fail\n");
}
ret = tc_sha256_update(&sha256_ctx, (const uint8_t *)static_str, strlen(static_str));
if (ret != TC_CRYPTO_SUCCESS)
{
BT_ERR("sha256 udpate fail\n");
}
ret = tc_sha256_final(g_auth, &sha256_ctx);
if (ret != TC_CRYPTO_SUCCESS)
{
BT_ERR("sha256 final fail\n");
}
else
{
BT_DBG("auth: %s", bt_hex((char *)g_auth, 16));
}
return g_auth;
}
int genie_crypto_encrypt(const uint8_t data_in[16], uint8_t data_out[16])
{
uint8_t i = 0;
uint8_t local_data[16];
uint8_t aes_iv[16] = {0x31, 0x32, 0x33, 0x61, 0x71, 0x77, 0x65, 0x64,
0x23, 0x2a, 0x24, 0x21, 0x28, 0x34, 0x6a, 0x75};
memcpy(local_data, data_in, 16);
while (i < 16)
{
local_data[i] ^= aes_iv[i];
i++;
}
return bt_mesh_aes_encrypt(g_ble_key, local_data, data_out);
}
int genie_crypto_decrypt(const uint8_t data_in[16], uint8_t data_out[16])
{
int ret = bt_mesh_aes_decrypt(g_ble_key, data_in, data_out);
uint8_t aes_iv[16] = {0x31, 0x32, 0x33, 0x61, 0x71, 0x77, 0x65, 0x64,
0x23, 0x2a, 0x24, 0x21, 0x28, 0x34, 0x6a, 0x75};
uint8_t i = 0;
while (i < 16)
{
data_out[i] ^= aes_iv[i];
i++;
}
return ret;
}
void genie_ais_get_cipher(const uint8_t random[16], uint8_t *cipher)
{
int ret;
genie_triple_t *p_genie_triple = genie_triple_get();
char mac_str[(GENIE_TRIPLE_MAC_SIZE << 1) + 1] = "";
char key_str[(GENIE_TRIPLE_KEY_SIZE << 1) + 1] = "";
char static_str[72] = ""; // random + ',' + pid + ',' + mac + ',' + secret = 16+1+8+1+12+1+32'\0'
struct tc_sha256_state_struct sha256_ctx;
hextostring(p_genie_triple->mac, mac_str, GENIE_TRIPLE_MAC_SIZE);
hextostring(p_genie_triple->key, key_str, GENIE_TRIPLE_KEY_SIZE);
memcpy(static_str, random, 16);
sprintf(static_str + 16, ",%08x,%s,%s", p_genie_triple->pid, mac_str, key_str);
BT_DBG("string: %s", static_str);
/* calculate the sha256 of oob info and
* fetch the top 16 bytes as static value
*/
ret = tc_sha256_init(&sha256_ctx);
if (ret != TC_CRYPTO_SUCCESS)
{
BT_ERR("sha256 init fail\n");
}
ret = tc_sha256_update(&sha256_ctx, (const uint8_t *)static_str, strlen(static_str));
if (ret != TC_CRYPTO_SUCCESS)
{
BT_ERR("sha256 udpate fail\n");
}
ret = tc_sha256_final(g_ble_key, &sha256_ctx);
if (ret != TC_CRYPTO_SUCCESS)
{
BT_ERR("sha256 final fail\n");
}
else
{
BT_DBG("auth: %s", bt_hex((char *)g_ble_key, 16));
}
genie_crypto_encrypt(random, cipher);
BT_DBG("cipher: %s", bt_hex((char *)cipher, 16));
}
void genie_ais_reset(void)
{
memset(g_ble_key, 0, 32);
}
void genie_crypto_adv_create(uint8_t ad_structure[14], uint8_t is_silent)
{
genie_triple_t *p_genie_triple = genie_triple_get();
ad_structure[3] |= 0x08; //FMSK auth enable
if (is_silent)
{
ad_structure[3] |= 0x20;
}
else
{
ad_structure[3] &= ~0x20;
}
memcpy(ad_structure + GENIE_TRIPLE_PID_SIZE, &p_genie_triple->pid, GENIE_TRIPLE_PID_SIZE);
// mac addr
for (int i = 0; i < GENIE_TRIPLE_MAC_SIZE; i++)
{
ad_structure[8 + i] = p_genie_triple->mac[GENIE_TRIPLE_MAC_SIZE - 1 - i];
}
}
| YifuLiu/AliOS-Things | components/genie_service/core/src/genie_crypto.c | C | apache-2.0 | 4,846 |
/*
* Copyright (C) 2018-2020 Alibaba Group Holding Limited
*/
#include "genie_service.h"
#include "mesh_hal_ble.h"
#include "mesh/cfg_srv.h"
#include "mesh.h"
#include "prov.h"
#define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_MESH_DEBUG_EVENT)
#include "common/log.h"
extern void genie_appkey_register(u16_t net_idx, u16_t app_idx, const u8_t val[16], bool update);
static genie_event_e _genie_event_handle_mesh_init(void)
{
#ifndef CONFIG_BT_SETTINGS
genie_provision_t genie_provision;
if (genie_provision_get_saved_data(&genie_provision) == 0)
{
bt_mesh_provision(genie_provision.netkey.key, genie_provision.netkey.net_index, genie_provision.netkey.flag, genie_provision.netkey.ivi, genie_provision.addr, genie_provision.devkey);
genie_appkey_register(genie_provision.appkey.net_index, genie_provision.appkey.key_index, genie_provision.appkey.key, genie_provision.appkey.flag);
/* check hb */
mesh_hb_para_t hb_para = {.count = 0};
if (genie_storage_read_hb(&hb_para) == GENIE_STORAGE_READ_FAIL)
{
extern u8_t genie_heartbeat_set(mesh_hb_para_t * p_para);
genie_heartbeat_set(&hb_para);
}
return GENIE_EVT_NONE;
}
else
{
bt_mesh_prov_enable(BT_MESH_PROV_GATT | BT_MESH_PROV_ADV);
return GENIE_EVT_SDK_MESH_PBADV_START; //prov start
}
#else
if (bt_mesh_is_provisioned())
{
genie_mesh_load_group_addr();
genie_mesh_setup();
return GENIE_EVT_NONE;
}
else
{
bt_mesh_prov_enable(BT_MESH_PROV_GATT | BT_MESH_PROV_ADV);
return GENIE_EVT_SDK_MESH_PBADV_START; //prov start
}
#endif
}
static genie_event_e _genie_event_handle_pbadv_start(void)
{
genie_service_ctx_t *p_context = NULL;
#ifdef CONFIG_PM_SLEEP
genie_lpm_disable();
#endif
genie_provision_clear_silent_flag();
extern void genie_set_silent_unprov_beacon_interval(bool is_silent);
genie_set_silent_unprov_beacon_interval(false);
p_context = genie_service_get_context();
if (p_context)
{
genie_provision_pbadv_timer_start(p_context->prov_timeout);
}
return GENIE_EVT_NONE;
}
static genie_event_e _genie_event_handle_pbadv_timeout(void)
{
#ifdef CONFIG_PM_SLEEP
genie_lpm_enable(true);
#endif
genie_provision_pbadv_timer_stop();
bt_mesh_prov_disable(BT_MESH_PROV_GATT | BT_MESH_PROV_ADV);
return GENIE_EVT_SDK_MESH_SILENT_START; //Enter silent provision mode
}
static genie_event_e _genie_event_handle_silent_start(void)
{
genie_provision_start_slient_pbadv();
return GENIE_EVT_NONE;
}
static genie_event_e _genie_event_handle_prov_start(void)
{
if (genie_provision_get_state() == GENIE_PROVISION_UNPROV)
{
genie_provision_set_state(GENIE_PROVISION_START);
/* disable adv timer */
genie_provision_pbadv_timer_stop();
/* enable prov timer */
genie_provision_prov_timer_start();
}
return GENIE_EVT_NONE;
}
static genie_event_e _genie_event_handle_prov_data(uint16_t *p_addr)
{
#ifndef CONFIG_BT_SETTINGS
genie_storage_write_addr(p_addr);
#endif
return GENIE_EVT_NONE;
}
static genie_event_e _genie_event_handle_prov_timeout(void)
{
return GENIE_EVT_SDK_MESH_PROV_FAIL;
}
static genie_event_e _genie_event_handle_prov_success(void)
{
genie_provision_pbadv_timer_stop();
return GENIE_EVT_NONE;
}
static genie_event_e _genie_event_handle_prov_fail(void)
{
/* reset prov */
genie_provision_set_state(GENIE_PROVISION_UNPROV);
genie_reset_provision();
/* restart adv */
bt_mesh_prov_enable(BT_MESH_PROV_GATT | BT_MESH_PROV_ADV);
return GENIE_EVT_SDK_MESH_PBADV_START;
}
static void _genie_event_save_mesh_data(uint8_t *p_status)
{
if (*p_status == 0)
{
#ifndef CONFIG_BT_SETTINGS
genie_storage_write_para(&bt_mesh);
#endif
}
}
static genie_event_e _genie_event_handle_appkey_add(uint8_t *p_status)
{
if (genie_provision_get_state() == GENIE_PROVISION_START)
{
/* disable prov timer */
genie_provision_prov_timer_stop();
if (*p_status == 0)
{
#ifndef CONFIG_BT_SETTINGS
//genie_storage_write_para(&bt_mesh);
uint8_t devkey[16];
mesh_netkey_para_t netkey;
mesh_appkey_para_t appkey;
memcpy(devkey, bt_mesh.dev_key, 16);
memset(&netkey, 0, sizeof(netkey));
memcpy(netkey.key, bt_mesh.sub[0].keys[0].net, 16);
memset(&appkey, 0, sizeof(appkey));
memcpy(appkey.key, bt_mesh.app_keys[0].keys[0].val, 16);
genie_storage_write_devkey(devkey);
genie_storage_write_netkey(&netkey);
genie_storage_write_appkey(&appkey);
#endif
genie_provision_set_state(GENIE_PROVISION_SUCCESS);
genie_mesh_ready_checktimer_restart(GENIE_PROV_SUCCESS_REPORT_TIMEOUT);
return GENIE_EVT_SDK_MESH_PROV_SUCCESS;
}
else
{
return GENIE_EVT_SDK_MESH_PROV_FAIL;
}
}
else
{
_genie_event_save_mesh_data(p_status);
return GENIE_EVT_NONE;
}
}
static genie_event_e _genie_event_handle_hb_set(mesh_hb_para_t *p_para)
{
#ifndef CONFIG_BT_SETTINGS
BT_DBG("save");
genie_storage_write_hb(p_para);
#endif
return GENIE_EVT_NONE;
}
#ifdef CONFIG_BT_MESH_CTRL_RELAY
static genie_event_e _genie_event_handle_ctrl_relay_set(mesh_ctrl_relay_para_t *p_para)
{
printf("save ctrl relay param\n");
genie_storage_write_ctrl_relay(p_para);
return GENIE_EVT_NONE;
}
#endif
static genie_event_e _genie_event_handle_seq_update(void)
{
#ifndef CONFIG_BT_SETTINGS
uint32_t seq = bt_mesh.seq;
genie_storage_write_seq(&seq, false);
#endif
return GENIE_EVT_NONE;
}
static genie_event_e _genie_event_handle_ais_discon(void)
{
if (0 == bt_mesh_prov_enable(BT_MESH_PROV_GATT | BT_MESH_PROV_ADV))
{
return GENIE_EVT_SDK_MESH_PBADV_START;
}
else
{
return GENIE_EVT_NONE;
}
}
static genie_event_e _genie_event_handle_vnd_msg(genie_transport_model_param_t *p_msg)
{
BT_DBG("vendor message received");
genie_model_handle_mesg(p_msg);
return GENIE_EVT_NONE;
}
int genie_down_msg(genie_down_mesg_type msg_type, uint32_t opcode, void *p_msg)
{
uint8_t *p_data = NULL;
uint16_t data_len = 0;
genie_service_ctx_t *p_context = NULL;
#ifdef CONIFG_GENIE_MESH_USER_CMD
uint8_t element_id = 0;
genie_down_msg_t down_msg;
#endif
p_context = genie_service_get_context();
if (p_msg == NULL || !p_context || !p_context->event_cb)
{
GENIE_LOG_ERR("param err");
return -1;
}
if (GENIE_DOWN_MESG_VENDOR_TYPE == msg_type)
{
genie_transport_model_param_t *p_vnd_mesg = (genie_transport_model_param_t *)p_msg;
data_len = 4 + p_vnd_mesg->len;
p_data = (uint8_t *)aos_malloc(data_len);
if (p_data == NULL)
{
return -1;
}
p_data[0] = p_vnd_mesg->opid;
p_data[1] = opcode;
p_data[2] = opcode >> 8;
p_data[3] = p_vnd_mesg->tid;
if (p_vnd_mesg->len > 0)
{
memcpy(&p_data[4], p_vnd_mesg->data, p_vnd_mesg->len);
}
#ifdef CONIFG_GENIE_MESH_USER_CMD
sig_model_element_state_t *p_elem_state = (sig_model_element_state_t *)p_vnd_mesg->p_model->user_data;
if (p_elem_state)
{
element_id = p_elem_state->element_id;
}
#endif
}
else
{
sig_model_msg *p_net_buf = (sig_model_msg *)p_msg;
p_context->event_cb(GENIE_EVT_SIG_MODEL_MSG, (void *)p_msg);
if (opcode < 0x7F) //one byte opcode
{
data_len = 1 + p_net_buf->len;
p_data = (uint8_t *)aos_malloc(data_len);
if (p_data == NULL)
{
return -1;
}
p_data[0] = opcode & 0xFF;
memcpy(&p_data[1], p_net_buf->data, p_net_buf->len);
}
else
{
data_len = 2 + p_net_buf->len;
p_data = (uint8_t *)aos_malloc(data_len);
if (p_data == NULL)
{
return -1;
}
p_data[0] = (opcode >> 8) & 0xFF;
p_data[1] = opcode & 0xFF;
memcpy(&p_data[2], p_net_buf->data, p_net_buf->len);
}
#ifdef CONIFG_GENIE_MESH_USER_CMD
element_id = p_net_buf->element_id;
#endif
}
#ifdef CONFIG_GENIE_MESH_AT_CMD
genie_at_cmd_send_data_to_mcu(p_data, data_len);
#endif
#ifdef CONIFG_GENIE_MESH_BINARY_CMD
genie_bin_cmds_send_data_to_mcu(p_data, data_len);
#endif
#ifdef CONIFG_GENIE_MESH_USER_CMD
down_msg.len = data_len;
down_msg.data = p_data;
down_msg.element_id = element_id;
p_context->event_cb(GENIE_EVT_DOWN_MSG, (void *)&down_msg);
#endif
aos_free(p_data);
return 0;
}
#ifdef MESH_MODEL_VENDOR_TIMER
static genie_event_e genie_model_notify_onoff_msg(vendor_attr_data_t *attr_data) //notify MCU
{
genie_transport_model_param_t msg;
uint8_t payload[3] = {0};
BT_DBG("type:%04x data:%04x\r\n", attr_data->type, attr_data->para);
if (attr_data->type == ATTR_TYPE_GENERIC_ONOFF)
{
payload[0] = 0x00;
payload[1] = 0x01;
payload[2] = attr_data->para;
memset(&msg, 0, sizeof(genie_transport_model_param_t));
msg.opid = VENDOR_OP_ATTR_SET_UNACK;
msg.tid = genie_transport_gen_tid();
msg.data = payload;
msg.len = sizeof(payload);
genie_down_msg(GENIE_DOWN_MESG_VENDOR_TYPE, CONFIG_MESH_VENDOR_COMPANY_ID, (void *)&msg);
}
return GENIE_EVT_NONE;
}
#endif
void genie_event(genie_event_e event, void *p_arg)
{
genie_event_e next_event = event;
uint8_t ignore_user_event = 0;
genie_service_ctx_t *p_context = NULL;
p_context = genie_service_get_context();
if (!p_context || !p_context->event_cb)
{
return;
}
if ((event != GENIE_EVT_SDK_SEQ_UPDATE) && (event != GENIE_EVT_USER_TRANS_CYCLE))
{
GENIE_LOG_INFO("GenieE:%d\r\n", event);
}
switch (event)
{
case GENIE_EVT_SW_RESET:
{
//call user_event first
p_context->event_cb(GENIE_EVT_SW_RESET, p_arg);
ignore_user_event = 1;
next_event = genie_reset_do_sw_reset();
}
break;
case GENIE_EVT_HW_RESET_START:
{
if (p_arg == NULL)
{
next_event = genie_reset_do_hw_reset(false);
}
else
{
bool is_only_report = *(bool *)p_arg;
next_event = genie_reset_do_hw_reset(is_only_report);
}
}
break;
case GENIE_EVT_BT_READY:
{
next_event = _genie_event_handle_mesh_init();
}
break;
case GENIE_EVT_SDK_AIS_DISCON:
{
next_event = _genie_event_handle_ais_discon();
}
break;
case GENIE_EVT_SDK_MESH_PBADV_START:
{
next_event = _genie_event_handle_pbadv_start();
}
break;
case GENIE_EVT_SDK_MESH_PBADV_TIMEOUT:
{
next_event = _genie_event_handle_pbadv_timeout();
}
break;
case GENIE_EVT_SDK_MESH_SILENT_START:
{
next_event = _genie_event_handle_silent_start();
}
break;
case GENIE_EVT_SDK_MESH_PROV_START:
{
next_event = _genie_event_handle_prov_start();
}
break;
case GENIE_EVT_SDK_MESH_PROV_DATA:
{
next_event = _genie_event_handle_prov_data((uint16_t *)p_arg);
}
break;
case GENIE_EVT_SDK_MESH_PROV_TIMEOUT:
{
next_event = _genie_event_handle_prov_timeout();
}
break;
case GENIE_EVT_SDK_MESH_PROV_FAIL:
{
next_event = _genie_event_handle_prov_fail();
}
break;
case GENIE_EVT_SDK_MESH_PROV_SUCCESS:
{
next_event = _genie_event_handle_prov_success();
}
break;
case GENIE_EVT_MESH_READY:
{
p_context->event_cb(GENIE_EVT_MESH_READY, p_arg); //Report user bootup data at first
ignore_user_event = 1;
genie_mesh_init_pharse_ii();
next_event = GENIE_EVT_NONE;
}
break;
case GENIE_EVT_SDK_APPKEY_ADD:
{
next_event = _genie_event_handle_appkey_add((uint8_t *)p_arg);
}
break;
case GENIE_EVT_SDK_APPKEY_DEL:
case GENIE_EVT_SDK_APPKEY_UPDATE:
case GENIE_EVT_SDK_NETKEY_ADD:
case GENIE_EVT_SDK_NETKEY_DEL:
case GENIE_EVT_SDK_NETKEY_UPDATE:
{
//TODO:Support key update
//_genie_event_save_mesh_data((uint8_t *)p_arg);
next_event = GENIE_EVT_NONE;
}
break;
case GENIE_EVT_SDK_HB_SET:
{
next_event = _genie_event_handle_hb_set((mesh_hb_para_t *)p_arg);
}
break;
#ifdef CONFIG_BT_MESH_CTRL_RELAY
case GENIE_EVT_SDK_CTRL_RELAY_SET:
{
next_event = _genie_event_handle_ctrl_relay_set((mesh_ctrl_relay_para_t *)p_arg);
}
break;
#endif
case GENIE_EVT_SDK_SEQ_UPDATE:
{
next_event = _genie_event_handle_seq_update();
}
break;
case GENIE_EVT_VENDOR_MODEL_MSG:
{
next_event = _genie_event_handle_vnd_msg((genie_transport_model_param_t *)p_arg);
}
break;
#ifdef MESH_MODEL_VENDOR_TIMER
case GENIE_EVT_TIMEOUT:
{
next_event = genie_model_notify_onoff_msg((vendor_attr_data_t *)p_arg);
}
break;
#endif
default:
{
next_event = GENIE_EVT_NONE;
}
break;
}
if (!ignore_user_event)
{
p_context->event_cb(event, p_arg);
}
#ifdef CONFIG_GENIE_MESH_AT_CMD
genie_at_output_event(event, p_arg);
#endif
#ifdef CONIFG_GENIE_MESH_BINARY_CMD
genie_bin_cmd_handle_event(event, p_arg);
#endif
if (next_event != GENIE_EVT_NONE)
{
genie_event(next_event, p_arg);
}
}
| YifuLiu/AliOS-Things | components/genie_service/core/src/genie_event.c | C | apache-2.0 | 13,766 |
/*
* Copyright (C) 2018-2020 Alibaba Group Holding Limited
*/
#define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_MESH_DEBUG_GLP)
#include <stdio.h>
#include <string.h>
#include <ctype.h>
//#include <aos/aos.h>
#include <aos/kernel.h>
#include <hal/hal.h>
#include <aos/hal/gpio.h>
#include <genie_sal_lpm.h>
#include <genie_lpm.h>
#if defined(BOARD_TG7100B)
#include "pm.h"
#endif
#include "common/log.h"
#include "genie_service.h"
static genie_lpm_ctx_t genie_lpm_ctx;
#ifndef GENIE_WAKE_UP_IO_NUM_MAX
#define GENIE_WAKE_UP_IO_NUM_MAX 5
#endif
genie_lpm_wakeup_io_config_t g_wakeup_io[GENIE_WAKE_UP_IO_NUM_MAX];
static uint8_t g_wakeup_io_num = 0;
#ifndef CONFIG_GENIE_MESH_ENABLE_SLEEP_WHEN_NOT_PROV
#define CONFIG_GENIE_MESH_ENABLE_SLEEP_WHEN_NOT_PROV 0
#endif
static void _genie_lpm_timer_irq_handler(void *p_timer, void *args)
{
int ret = 0;
BT_DBG("[%u]cur status: %d\n", k_uptime_get_32(), genie_lpm_ctx.status);
if (genie_lpm_ctx.has_disabled == 1)
{
BT_DBG("lpm already disable, stop timer\n");
aos_timer_stop(&genie_lpm_ctx.wakeup_timer);
return;
}
if (STATUS_WAKEUP == genie_lpm_ctx.status)
{
BT_DBG("[%u]sleep and suspend mesh stack\n", k_uptime_get_32());
ret = genie_mesh_suspend(false);
if (0 == ret || -EALREADY == ret)
{
genie_lpm_ctx.status = STATUS_SLEEP;
if (!genie_lpm_ctx.p_config.genie_lpm_cb)
{
genie_lpm_ctx.p_config.genie_lpm_cb(WAKEUP_BY_TIMER, genie_lpm_ctx.status, NULL);
}
aos_timer_stop(&genie_lpm_ctx.wakeup_timer);
aos_timer_change(&genie_lpm_ctx.wakeup_timer, genie_lpm_ctx.p_config.sleep_ms);
aos_timer_start(&genie_lpm_ctx.wakeup_timer);
}
else
{
aos_timer_stop(&genie_lpm_ctx.wakeup_timer);
aos_timer_change(&genie_lpm_ctx.wakeup_timer, genie_lpm_ctx.p_config.wakeup_ms);
aos_timer_start(&genie_lpm_ctx.wakeup_timer);
}
}
else if (STATUS_SLEEP == genie_lpm_ctx.status)
{
BT_DBG("[%u]wake up and resume mesh stack\n", k_uptime_get_32());
ret = genie_mesh_resume();
if (0 == ret || -EALREADY == ret)
{
genie_lpm_ctx.status = STATUS_WAKEUP;
genie_lpm_ctx.p_config.genie_lpm_cb(WAKEUP_BY_TIMER, genie_lpm_ctx.status, NULL);
aos_timer_stop(&genie_lpm_ctx.wakeup_timer);
aos_timer_change(&genie_lpm_ctx.wakeup_timer, genie_lpm_ctx.p_config.wakeup_ms);
aos_timer_start(&genie_lpm_ctx.wakeup_timer);
}
else
{
aos_timer_stop(&genie_lpm_ctx.wakeup_timer);
aos_timer_change(&genie_lpm_ctx.wakeup_timer, genie_lpm_ctx.p_config.sleep_ms);
aos_timer_start(&genie_lpm_ctx.wakeup_timer);
}
}
}
/*
static void _genie_lpm_io_wakeup_timer_irq_handler(void *p_timer, void *args)
{
int ret = 0;
BT_DBG("[%u]wakeup by i/o\n", k_uptime_get_32());
aos_timer_stop(&genie_lpm_ctx.io_wakeup_timer);
BT_DBG("[%u]cur status: %d\n", k_uptime_get_32(), genie_lpm_ctx.status);
if (STATUS_SLEEP == genie_lpm_ctx.status)
{
BT_DBG("[%u]wake up and resume mesh stack\n", k_uptime_get_32());
ret = genie_mesh_resume();
if (0 == ret)
{
genie_lpm_ctx.status = STATUS_WAKEUP;
genie_lpm_ctx.p_config.genie_lpm_cb(WAKEUP_BY_IO, genie_lpm_ctx.status);
}
}
else
{
genie_lpm_ctx.p_config.genie_lpm_cb(WAKEUP_IS_WAKEUP, genie_lpm_ctx.status);
}
}*/
__attribute__((section(".__sram.code"))) void genie_lpm_io_wakeup_handler(void *arg)
{
if (genie_lpm_ctx.p_config.lpm_wakeup_io != 0)
{
uint8_t trigger_found = 0;
_genie_lpm_io_status_t g_io_status[GENIE_WAKE_UP_IO_NUM_MAX];
long long interrupt_time = aos_now_ms();
if ((interrupt_time - genie_lpm_ctx.last_interrupt_time < INTERRUPT_DELAY_TIME))
{
return; //for debounce
}
genie_lpm_ctx.last_interrupt_time = interrupt_time;
for (int i = 0; i < g_wakeup_io_num; i++)
{
bool status = genie_sal_sleep_wakeup_io_get_status(g_wakeup_io[i].port);
if (((g_wakeup_io[i].io_pol == FALLING || g_wakeup_io[i].io_pol == ACT_LOW) && status == false) || ((g_wakeup_io[i].io_pol == RISING || g_wakeup_io[i].io_pol == ACT_HIGH) && status == true))
{
g_io_status[i].port = g_wakeup_io[i].port;
g_io_status[i].trigger_flag = 1;
g_io_status[i].status = status;
trigger_found = 1;
}
}
if (trigger_found)
{
BT_DBG("[%u]wakeup by i/o\n", k_uptime_get_32());
BT_DBG("[%u]cur status: %d\n", k_uptime_get_32(), genie_lpm_ctx.status);
if (STATUS_SLEEP == genie_lpm_ctx.status)
{
int ret = 0;
BT_DBG("[%u]wake up and resume mesh stack\n", k_uptime_get_32());
ret = genie_mesh_resume();
if (0 == ret)
{
genie_lpm_ctx.status = STATUS_WAKEUP;
_genie_lpm_io_status_list_t list;
list.size = g_wakeup_io_num;
list.io_status = g_io_status;
genie_lpm_ctx.p_config.genie_lpm_cb(WAKEUP_BY_IO, genie_lpm_ctx.status, &list);
}
}
else
{
genie_lpm_ctx.p_config.genie_lpm_cb(WAKEUP_IS_WAKEUP, genie_lpm_ctx.status, NULL);
}
}
}
}
static void _genie_lpm_io_wakeup_init(genie_lpm_wakeup_io_t config)
{
if (config.io_list_size > GENIE_WAKE_UP_IO_NUM_MAX)
{
GENIE_LOG_ERR("Wakeup i/o num should no more than %d", GENIE_WAKE_UP_IO_NUM_MAX);
}
g_wakeup_io_num = GENIE_WAKE_UP_IO_NUM_MAX < config.io_list_size ? GENIE_WAKE_UP_IO_NUM_MAX : config.io_list_size;
memcpy(g_wakeup_io, config.io_config, sizeof(genie_lpm_wakeup_io_config_t) * g_wakeup_io_num);
for (int i = 0; i < g_wakeup_io_num; i++)
{
genie_sal_sleep_wakup_io_set(g_wakeup_io[i].port, g_wakeup_io[i].io_pol);
}
genie_sal_io_wakeup_cb_register(genie_lpm_io_wakeup_handler);
}
/*
static void _genie_lpm_io_wakeup_timer_init(void)
{
aos_timer_new(&genie_lpm_ctx.io_wakeup_timer, _genie_lpm_io_wakeup_timer_irq_handler, NULL, 10, 0);
aos_timer_stop(&genie_lpm_ctx.io_wakeup_timer);
}*/
static void _genie_lpm_wakeup_timer_init(void)
{
aos_timer_new(&genie_lpm_ctx.wakeup_timer, _genie_lpm_timer_irq_handler, NULL, genie_lpm_ctx.p_config.delay_sleep_time, 0);
aos_timer_stop(&genie_lpm_ctx.wakeup_timer);
}
int genie_lpm_disable(void)
{
GENIE_LOG_INFO("lpm disable");
if (genie_lpm_ctx.is_mesh_init == 1)
{
genie_mesh_resume();
}
genie_lpm_ctx.has_disabled = 1;
genie_lpm_ctx.status = STATUS_WAKEUP;
aos_timer_stop(&genie_lpm_ctx.wakeup_timer);
genie_sal_sleep_disable();
return 0;
}
int genie_lpm_enable(bool force)
{
GENIE_LOG_INFO("lpm enable");
if (genie_lpm_ctx.is_mesh_init == 1)
{
genie_mesh_suspend(force);
}
genie_lpm_ctx.has_disabled = 0;
genie_sal_sleep_enable();
genie_lpm_ctx.status = STATUS_SLEEP;
if (force)
{
aos_timer_stop(&genie_lpm_ctx.wakeup_timer);
}
else
{
aos_timer_stop(&genie_lpm_ctx.wakeup_timer);
aos_timer_change(&genie_lpm_ctx.wakeup_timer, genie_lpm_ctx.p_config.sleep_ms);
aos_timer_start(&genie_lpm_ctx.wakeup_timer);
}
return 0;
}
int genie_lpm_deep_sleep(void)
{
*(volatile uint32_t *)PWR_BOOT_REASON = PWR_STANDBY_BOOT_FLAG;
return genie_sal_sleep_enter_standby();
}
void genie_lpm_init(genie_lpm_conf_t *lpm_conf)
{
uint32_t *p_boot_reason = (uint32_t *)PWR_BOOT_REASON;
memcpy(&genie_lpm_ctx.p_config, lpm_conf, sizeof(genie_lpm_conf_t));
if (genie_lpm_ctx.p_config.genie_lpm_cb == NULL)
{
GENIE_LOG_ERR("lpm param err");
return;
}
if (genie_lpm_ctx.p_config.delay_sleep_time == 0)
{
genie_lpm_ctx.p_config.delay_sleep_time = DEFAULT_BOOTUP_DELAY_SLEEP_TIME;
}
genie_lpm_ctx.status = STATUS_WAKEUP;
GENIE_LOG_INFO("io_wakeup:%d, sleep:%dms, wakeup:%dms, after:%dms", genie_lpm_ctx.p_config.lpm_wakeup_io, genie_lpm_ctx.p_config.sleep_ms, genie_lpm_ctx.p_config.wakeup_ms, genie_lpm_ctx.p_config.delay_sleep_time);
if (genie_lpm_ctx.p_config.lpm_wakeup_io != 0 && genie_lpm_ctx.p_config.lpm_wakeup_io_config.io_list_size != 0)
{
_genie_lpm_io_wakeup_init(lpm_conf->lpm_wakeup_io_config);
//_genie_lpm_io_wakeup_timer_init(); //Do things in the timer when wakeup by IO
}
if ((genie_lpm_ctx.p_config.sleep_ms != 0) && (genie_lpm_ctx.p_config.wakeup_ms != 0))
{
_genie_lpm_wakeup_timer_init();
}
#if !(CONFIG_GENIE_MESH_ENABLE_SLEEP_WHEN_NOT_PROV)
genie_sal_sleep_disable();
#endif
if (*p_boot_reason == PWR_STANDBY_BOOT_FLAG)
{
GENIE_LOG_INFO("standy boot flag");
*(volatile uint32_t *)PWR_BOOT_REASON = 0;
}
}
int genie_lpm_start(void)
{
genie_lpm_ctx.is_mesh_init = 1;
BT_DBG("genie lpm mesh ready");
if (genie_lpm_ctx.p_config.is_auto_enable == 1)
{
genie_lpm_ctx.has_disabled = 0;
genie_sal_sleep_enable();
genie_lpm_ctx.status = STATUS_SLEEP;
aos_timer_stop(&genie_lpm_ctx.wakeup_timer);
aos_timer_start(&genie_lpm_ctx.wakeup_timer);
}
else
{
if (genie_lpm_ctx.p_config.delay_sleep_time > 0)
{
genie_lpm_ctx.has_disabled = 0;
aos_timer_start(&genie_lpm_ctx.wakeup_timer);
}
}
return 0;
}
| YifuLiu/AliOS-Things | components/genie_service/core/src/genie_lpm.c | C | apache-2.0 | 9,791 |
/*
* Copyright (C) 2018-2020 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
//#include <aos/aos.h>
#include <aos/kernel.h>
#include <misc/printk.h>
//#include <hal/hal.h>
#include <ble_os.h>
#include <bluetooth/bluetooth.h>
#include <api/mesh.h>
#include "net.h"
//#include "transport.h"
#include "genie_service.h"
#define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_MESH_DEBUG_MODEL)
#include "common/log.h"
static struct bt_mesh_prov genie_mesh_provision;
static struct bt_mesh_comp genie_composition;
static aos_timer_t do_mesh_ready_timer;
uint8_t g_mesh_log_mode = 1;
struct bt_mesh_elem *genie_mesh_get_primary_element(void)
{
return genie_composition.elem;
}
void genie_mesh_load_group_addr(void)
{
if (genie_storage_read_sub(g_sub_list) == GENIE_STORAGE_SUCCESS)
{
BT_INFO("g_sub_list %s", bt_hex(g_sub_list, sizeof(g_sub_list)));
}
}
static int report_poweron_callback(transport_result_e result)
{
#ifdef CONFIG_PM_SLEEP
genie_lpm_start();
#endif
return 0;
}
static int genie_mesh_report_poweron(void)
{
uint8_t payload[3];
genie_transport_payload_param_t transport_payload_param;
payload[0] = ATTR_TYPE_DEVICE_EVENT & 0xFF;
payload[1] = (ATTR_TYPE_DEVICE_EVENT >> 8) & 0xFF;
payload[2] = EL_DEV_UP_T;
memset(&transport_payload_param, 0, sizeof(genie_transport_payload_param_t));
transport_payload_param.opid = VENDOR_OP_ATTR_INDICATE;
transport_payload_param.p_payload = payload;
transport_payload_param.payload_len = sizeof(payload);
transport_payload_param.retry_cnt = GENIE_TRANSPORT_DEFAULT_RETRY_COUNT;
transport_payload_param.result_cb = report_poweron_callback;
return genie_transport_send_payload(&transport_payload_param);
}
int genie_mesh_init_pharse_ii(void)
{
#ifdef CONFIG_GENIE_OTA
genie_ota_init();
#endif
#ifdef MESH_MODEL_VENDOR_TIMER
genie_time_init();
#endif
genie_mesh_report_poweron();
#if defined(CONFIG_BT_MESH_CTRL_RELAY) && !defined(CONFIG_PM_SLEEP)
/* check ctrl relay */
extern uint8_t genie_ctrl_relay_conf_set(mesh_ctrl_relay_para_t * p_para);
mesh_ctrl_relay_para_t cr_para;
genie_storage_status_e cr_ret = GENIE_STORAGE_SUCCESS;
memset(&cr_para, 0, sizeof(mesh_ctrl_relay_para_t));
cr_ret = genie_storage_read_ctrl_relay(&cr_para);
if (cr_ret == GENIE_STORAGE_SUCCESS)
{
GENIE_LOG_INFO("proved, use save ctrl relay config");
genie_ctrl_relay_conf_set(&cr_para);
}
else
{
GENIE_LOG_INFO("proved, use default ctrl relay config");
genie_ctrl_relay_conf_set(NULL);
}
#endif
return 0;
}
static void do_mesh_ready_timer_cb(void *p_timer, void *args)
{
char mesh_init_state = *(char *)args;
GENIE_LOG_INFO("mesh init state:%d\n", mesh_init_state);
if (mesh_init_state == GENIE_MESH_INIT_STATE_PROVISION)
{
if (genie_provision_get_state() != GENIE_PROVISION_SUCCESS)
{
GENIE_LOG_INFO("wait app key timeout");
genie_event(GENIE_EVT_SDK_MESH_PROV_TIMEOUT, NULL);
return;
}
}
else if (mesh_init_state == GENIE_MESH_INIT_STATE_HW_RESET)
{
return genie_event(GENIE_EVT_HW_RESET_START, NULL);
}
genie_event(GENIE_EVT_MESH_READY, NULL);
}
void genie_mesh_ready_checktimer_restart(uint32_t timeout)
{
aos_timer_stop(&do_mesh_ready_timer);
aos_timer_change_once(&do_mesh_ready_timer, timeout);
aos_timer_start(&do_mesh_ready_timer);
}
static void mesh_provision_complete(u16_t net_idx, u16_t addr)
{
uint8_t rand;
uint16_t random_time;
static char mesh_init_state = 0; //1:now is provision 2:hw reset 3:normal boot
//This time is in provision
if (genie_provision_get_state() != GENIE_PROVISION_UNPROV)
{
GENIE_LOG_INFO("is in prov");
mesh_init_state = GENIE_MESH_INIT_STATE_PROVISION;
aos_timer_new(&do_mesh_ready_timer, do_mesh_ready_timer_cb, &mesh_init_state, GENIE_MESH_INIT_PHARSE_II_CHECK_APPKEY_TIMEOUT, 0);
}
else
{
if (genie_reset_get_hw_reset_flag())
{
GENIE_LOG_INFO("hw reset");
mesh_init_state = GENIE_MESH_INIT_STATE_HW_RESET;
aos_timer_new(&do_mesh_ready_timer, do_mesh_ready_timer_cb, &mesh_init_state, GENIE_MESH_INIT_PHARSE_II_HW_RESET_DELAY, 0);
}
else
{
bt_rand(&rand, 1);
//Random range[GENIE_MESH_INIT_PHARSE_II_DELAY_START_MIN-GENIE_MESH_INIT_PHARSE_II_DELAY_START_MAX]
random_time = GENIE_MESH_INIT_PHARSE_II_DELAY_START_MIN + (GENIE_MESH_INIT_PHARSE_II_DELAY_START_MAX - GENIE_MESH_INIT_PHARSE_II_DELAY_START_MIN) * rand / 255;
GENIE_LOG_INFO("Rand delay:%dms", random_time);
aos_timer_new(&do_mesh_ready_timer, do_mesh_ready_timer_cb, &mesh_init_state, random_time, 0);
}
}
#ifdef CONFIG_BT_MESH_SHELL
extern void genie_prov_complete_notify(u16_t net_idx, u16_t addr);
genie_prov_complete_notify(net_idx, addr);
#endif
}
static void mesh_provision_reset(void)
{
BT_INFO("reset genie_mesh_provision");
#ifdef MESH_MODEL_VENDOR_TIMER
genie_time_finalize();
#endif
}
static void bt_ready_cb(int err)
{
if (err)
{
BT_ERR("BT init err %d", err);
return;
}
#if 0
k_work_init(&genie_mesh_work, do_genie_mesh_work);
#endif
BT_INFO(">>>Mesh initialized<<<");
err = bt_mesh_init(&genie_mesh_provision, &genie_composition, NULL);
if (err)
{
BT_ERR("mesh init err %d", err);
return;
}
#ifdef CONFIG_GENIE_MESH_PORT
extern int genie_mesh_port_init(void);
genie_mesh_port_init();
#endif
//send event
genie_event(GENIE_EVT_BT_READY, NULL);
}
int genie_mesh_init(struct bt_mesh_elem *p_mesh_elem, unsigned int mesh_elem_counts)
{
int ret;
uint8_t random[16] = {0};
BT_INFO(">>>init genie<<<");
genie_mesh_provision.uuid = genie_provision_get_uuid();
genie_mesh_provision.static_val = genie_crypto_get_auth(random);
genie_mesh_provision.static_val_len = STATIC_OOB_LENGTH;
genie_mesh_provision.complete = mesh_provision_complete;
genie_mesh_provision.reset = mesh_provision_reset;
genie_composition.cid = CONFIG_MESH_VENDOR_COMPANY_ID;
genie_composition.pid = 0;
genie_composition.vid = 1; // firmware version for ota
genie_composition.elem = p_mesh_elem;
genie_composition.elem_count = mesh_elem_counts;
genie_sal_ble_init();
ret = bt_enable(NULL);
//BT_INFO("the return of bt_enable is %d\n", ret);
bt_ready_cb(ret);
return ret;
}
int genie_mesh_suspend(bool force)
{
BT_INFO("[%u]%s, force:%d", k_uptime_get_32(), __func__, force);
return bt_mesh_suspend(force);
}
int genie_mesh_resume(void)
{
BT_INFO("[%u]%s", k_uptime_get_32(), __func__);
return bt_mesh_resume();
}
| YifuLiu/AliOS-Things | components/genie_service/core/src/genie_mesh.c | C | apache-2.0 | 6,870 |
/*
* Copyright (C) 2018-2020 Alibaba Group Holding Limited
*/
#include <port/mesh_hal_ble.h>
#define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_MESH_DEBUG_OTA)
#include "common/log.h"
#include "bt_mesh_custom_log.h"
#include "genie_service.h"
#include "ali_dfu_port.h"
genie_ota_ctx_t genie_ota_ctx;
bool genie_ota_is_ready(void)
{
return genie_ota_ctx.ota_ready;
}
bool genie_ota_get_indication(void)
{
uint8_t ota_indicat = 0xFF;
genie_storage_status_e ret;
ret = genie_storage_read_userdata(GFI_OTA_INDICAT, &ota_indicat, sizeof(ota_indicat));
if (ret == GENIE_STORAGE_SUCCESS && ota_indicat == 1)
{
return 1;
}
return 0;
}
#ifdef CONFIG_GENIE_OTA_PINGPONG
void ota_check_image_id(void)
{
uint32_t saved_ota_image_id = 0;
uint8_t ota_image_id = DFU_IMAGE_INVALID_ID;
genie_storage_status_e ret;
ret = genie_storage_read_reliable(GFI_OTA_IMAGE_ID, (uint8_t *)&saved_ota_image_id, sizeof(saved_ota_image_id));
if (ret == GENIE_STORAGE_SUCCESS)
{
ota_image_id = saved_ota_image_id & 0xFF;
if ((saved_ota_image_id >> 8) == GENIE_OTA_IMAGE_ID_MAGIC && ota_image_id < DFU_IMAGE_INVALID_ID)
{
if (ota_image_id != genie_sal_ota_get_current_image_id())
{
BT_INFO("switch to %d", ota_image_id);
if (genie_sal_ota_change_image_id(ota_image_id) == ota_image_id)
{
genie_storage_delete_reliable(GFI_OTA_IMAGE_ID);
hal_reboot();
}
}
}
BT_DBG("del change %d", ota_image_id);
genie_storage_delete_reliable(GFI_OTA_IMAGE_ID);
}
}
#endif
static void _ais_set_ota_change(void)
{
uint8_t ota_indicat = 1;
#ifdef CONFIG_GENIE_OTA_PINGPONG
uint32_t ota_image_id = GENIE_OTA_IMAGE_ID_A;
#endif
genie_storage_write_userdata(GFI_OTA_INDICAT, &ota_indicat, sizeof(ota_indicat));
#ifdef CONFIG_GENIE_OTA_PINGPONG
if (genie_sal_ota_get_current_image_id() == DFU_IMAGE_A)
{
ota_image_id = GENIE_OTA_IMAGE_ID_B;
}
else
{
ota_image_id = GENIE_OTA_IMAGE_ID_A;
}
BT_DBG("switch to %d", ota_image_id & 0xFF);
genie_storage_write_reliable(GFI_OTA_IMAGE_ID, (uint8_t *)&ota_image_id, sizeof(ota_image_id));
#endif
genie_ota_ctx.ota_ready = 1;
}
void genie_ota_status_report(void)
{
uint8_t plaine_data[GENIE_CRYPTO_UNIT_SIZE];
uint8_t encrypt_data[GENIE_CRYPTO_UNIT_SIZE];
ais_ota_status_report_t *p_status_report = (ais_ota_status_report_t *)plaine_data;
memset(plaine_data, 11, sizeof(plaine_data));
p_status_report->last_seq = genie_ota_ctx.last_seq;
p_status_report->total_frame = genie_ota_ctx.total_frame;
p_status_report->rx_size = genie_ota_ctx.rx_size;
printf("ota last[%d] total[%d] size[%d] err[%d]\r\n", p_status_report->last_seq, p_status_report->total_frame, p_status_report->rx_size, genie_ota_ctx.err_count);
genie_crypto_encrypt(plaine_data, encrypt_data);
genie_ais_notify(0, AIS_OTA_STATUS, encrypt_data, GENIE_CRYPTO_UNIT_SIZE);
}
bool genie_ota_handle_version_request(uint8_t msg_id, ais_ota_ver_req_t *p_ver_req, uint8_t encrypt)
{
uint8_t plaine_data[GENIE_CRYPTO_UNIT_SIZE];
uint8_t encrypt_data[GENIE_CRYPTO_UNIT_SIZE];
ais_ota_ver_resp_t *p_ver_resp = (ais_ota_ver_resp_t *)plaine_data;
if (p_ver_req->image_type == 0)
{
memset(plaine_data, 11, sizeof(plaine_data));
p_ver_resp->image_type = 0;
p_ver_resp->ver = genie_version_appver_get();
if (encrypt > 0)
{
genie_crypto_encrypt(plaine_data, encrypt_data);
genie_ais_notify(msg_id, AIS_OTA_VER_RESP, encrypt_data, GENIE_CRYPTO_UNIT_SIZE);
}
else
{
genie_ais_notify(msg_id, AIS_OTA_VER_RESP, plaine_data, 5); //5=sizeof(ais_ota_ver_resp_t)
}
return true;
}
return false;
}
bool genie_ota_handle_update_request(uint8_t msg_id, ais_ota_upd_req_t *p_ota_req, uint8_t encrypt)
{
uint8_t plaine_data[GENIE_CRYPTO_UNIT_SIZE];
uint8_t encrypt_data[GENIE_CRYPTO_UNIT_SIZE];
ais_ota_upd_resp_t *p_upd_resp = (ais_ota_upd_resp_t *)plaine_data;
printf("ota ver:0x%08x imgT:%d imgS:%d maxS:%d\r\n", p_ota_req->ver, p_ota_req->image_type, p_ota_req->fw_size, ali_dfu_get_ota_partition_max_size());
memset(plaine_data, 10, sizeof(plaine_data));
if (p_ota_req->image_type != 0 || p_ota_req->ver <= genie_version_appver_get() ||
ali_dfu_get_ota_partition_max_size() < p_ota_req->fw_size || 0 == p_ota_req->fw_size) //Is illeagal
{
p_upd_resp->state = 0;
p_upd_resp->rx_size = 0;
}
else
{
genie_ais_state_set(AIS_STATE_OTA);
memset(&genie_ota_ctx, 0, sizeof(genie_ota_ctx));
genie_ota_ctx.image_type = p_ota_req->image_type;
genie_ota_ctx.image_ver = p_ota_req->ver;
genie_ota_ctx.image_size = p_ota_req->fw_size;
genie_ota_ctx.image_crc16 = p_ota_req->crc16;
genie_ota_ctx.ota_flag = p_ota_req->ota_flag;
p_upd_resp->state = 1;
/*If support breakpoint continue,you should set rx_size*/
p_upd_resp->rx_size = 0;
}
p_upd_resp->total_frame = CONFIG_AIS_TOTAL_FRAME - 1;
if (encrypt > 0)
{
genie_crypto_encrypt(plaine_data, encrypt_data);
genie_ais_notify(msg_id, AIS_OTA_UPD_RESP, encrypt_data, GENIE_CRYPTO_UNIT_SIZE);
}
else
{
genie_ais_notify(msg_id, AIS_OTA_UPD_RESP, plaine_data, 6); //response use plain data
}
return true;
}
bool genie_ota_parse_pdu(ais_pdu_t *p_msg)
{
uint8_t *p_payload = p_msg->payload;
uint16_t payload_len = p_msg->header.payload_len;
if (p_msg->header.seq > p_msg->header.total_frame)
{
BT_ERR("invalid");
return false;
}
if (p_msg->header.seq != genie_ota_ctx.except_seq)
{
printf("except_seq:%d rx_seq:%d len:%d\r\n", genie_ota_ctx.except_seq, p_msg->header.seq, p_msg->header.payload_len);
if (genie_ota_ctx.err_count++ == 0)
{
/* send fail */
genie_ota_status_report();
/* refresh timer */
return true;
}
return false;
}
BT_DBG("b4:rx %d/%d", genie_ota_ctx.rx_size, genie_ota_ctx.image_size);
if (genie_ota_ctx.rx_size + p_msg->header.payload_len > genie_ota_ctx.image_size)
{
BT_ERR("out of size, rx %ld, recv %d", genie_ota_ctx.rx_size, p_msg->header.payload_len);
return false;
}
genie_ota_ctx.err_count = 0;
if (p_msg->header.seq == 0)
{
genie_ota_ctx.rx_len = 0;
memset(genie_ota_ctx.recv_buf, 0, sizeof(genie_ota_ctx.recv_buf));
}
if (payload_len)
{
//BT_DBG("save %d", payload_len);
genie_ota_ctx.flash_clean = 1;
memcpy(genie_ota_ctx.recv_buf + genie_ota_ctx.rx_len, p_payload, payload_len);
genie_ota_ctx.rx_len += payload_len;
}
genie_ota_ctx.last_seq = p_msg->header.seq;
genie_ota_ctx.total_frame = p_msg->header.total_frame;
genie_ota_ctx.rx_size += p_msg->header.payload_len;
BT_DBG("rx %d/%d", genie_ota_ctx.rx_size, genie_ota_ctx.image_size);
if (p_msg->header.seq == p_msg->header.total_frame)
{
ali_dfu_image_update(genie_ota_ctx.image_type,
genie_ota_ctx.rx_size - genie_ota_ctx.rx_len, genie_ota_ctx.rx_len,
(int *)genie_ota_ctx.recv_buf);
genie_ota_ctx.rx_len = 0;
genie_ota_ctx.except_seq = 0;
}
else
{
genie_ota_ctx.except_seq = p_msg->header.seq + 1;
}
if (genie_ota_ctx.rx_size == genie_ota_ctx.image_size || p_msg->header.seq == p_msg->header.total_frame)
{
genie_ota_status_report();
}
return true;
}
bool genie_ota_check_firmware(uint8_t msg_id, ais_ota_check_req_t *p_check_req)
{
uint16_t crc16 = 0;
uint8_t plaine_data[GENIE_CRYPTO_UNIT_SIZE];
uint8_t encrypt_data[GENIE_CRYPTO_UNIT_SIZE];
ais_ota_check_resp_t *p_check_resp = (ais_ota_check_resp_t *)plaine_data;
genie_ais_state_set(AIS_STATE_IDLE);
if (p_check_req->state == 1)
{
memset(plaine_data, 15, sizeof(plaine_data));
p_check_resp->state = dfu_check_checksum(genie_ota_ctx.image_type, &crc16);
BT_DBG("check %d %04x %04x", p_check_resp->state, genie_ota_ctx.image_crc16, crc16);
if (p_check_resp->state && crc16 != genie_ota_ctx.image_crc16)
{
p_check_resp->state = 0;
BT_ERR("crc error");
}
if (p_check_resp->state)
{
genie_ais_state_set(AIS_STATE_REBOOT);
_ais_set_ota_change();
BT_WARN("ota success, reboot in 3s!");
}
else
{
BT_ERR("ota failed");
}
genie_crypto_encrypt(plaine_data, encrypt_data);
genie_ais_notify(msg_id, AIS_OTA_CHECK_RESP, encrypt_data, GENIE_CRYPTO_UNIT_SIZE);
return true;
}
else
{
return false;
}
}
bool genie_ota_is_updating(void)
{
return (genie_ota_ctx.rx_size > 0) ? 1 : 0;
}
static int ota_report_version_result_cb(transport_result_e result_e)
{
if (result_e == SEND_RESULT_SUCCESS)
{
genie_storage_delete_userdata(GFI_OTA_INDICAT);
}
return 0;
}
int genie_ota_report_version(void)
{
uint8_t payload[8];
uint32_t version = genie_version_appver_get();
genie_transport_payload_param_t transport_payload_param;
payload[0] = ATTR_TYPE_REPORT_VERSION & 0xff;
payload[1] = (ATTR_TYPE_REPORT_VERSION >> 8) & 0xff;
memcpy(&payload[2], &version, 4);
payload[6] = VENDOR_MODEL_VERSION;
payload[7] = SDK_VERSION;
memset(&transport_payload_param, 0, sizeof(genie_transport_payload_param_t));
transport_payload_param.opid = VENDOR_OP_ATTR_INDICATE;
transport_payload_param.p_payload = payload;
transport_payload_param.payload_len = sizeof(payload);
transport_payload_param.retry_cnt = GENIE_TRANSPORT_DEFAULT_RETRY_COUNT;
transport_payload_param.result_cb = ota_report_version_result_cb;
return genie_transport_send_payload(&transport_payload_param);
}
int genie_ota_init(void)
{
genie_ais_init();
genie_ota_report_version();
return 0;
}
int genie_ota_pre_init(void)
{
#ifdef CONFIG_GENIE_OTA_PINGPONG
ota_check_image_id();
#endif
genie_ais_pre_init();
memset(&genie_ota_ctx, 0, sizeof(genie_ota_ctx_t));
erase_dfu_flash();
return 0;
}
| YifuLiu/AliOS-Things | components/genie_service/core/src/genie_ota.c | C | apache-2.0 | 10,539 |
/*
* Copyright (C) 2018-2020 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include <string.h>
#include <genie_provision.h>
#include "genie_service.h"
#ifdef GENIE_ULTRA_PROV
#include <errno.h>
#include <tinycrypt/sha256.h>
#include <tinycrypt/constants.h>
#include <net/buf.h>
#include "crypto.h"
#include "adv.h"
#define BUF_TIMEOUT K_MSEC(400)
#define BT_MESH_ADV(buf) (*(struct bt_mesh_adv **)net_buf_user_data(buf))
static uint8_t p_prov_data_key[32];
static uint8_t p_ultra_prov_devkey[32];
static uint8_t p_confirm[16];
#endif
#define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_MESH_DEBUG_PROV)
#include "common/log.h"
static struct k_timer pbadv_timeout_timer;
static struct k_timer prov_timeout_timer;
static genie_provision_state_e provision_state = GENIE_PROVISION_UNPROV;
static uint8_t genie_uuid[GENIE_PROVISON_UUID_LEN];
static void genie_provision_set_silent_flag(void)
{
genie_uuid[13] |= UNPROV_ADV_FEATURE1_SILENT_ADV;
}
void genie_provision_clear_silent_flag(void)
{
genie_uuid[13] &= UNPROV_ADV_FEATURE1_SILENT_UNMASK;
}
int genie_provision_set_state(genie_provision_state_e state)
{
provision_state = state;
return 0;
}
genie_provision_state_e genie_provision_get_state(void)
{
return provision_state;
}
uint8_t *genie_provision_get_uuid(void)
{
int i = 0;
genie_triple_t *p_genie_triple = NULL;
p_genie_triple = genie_triple_get();
// all fields in uuid should be in little-endian
// CID: Taobao
genie_uuid[0] = CONFIG_MESH_VENDOR_COMPANY_ID & 0xFF;
genie_uuid[1] = (CONFIG_MESH_VENDOR_COMPANY_ID >> 8) & 0xFF;
// PID
// Bit0~Bit3: 0001 (broadcast version)
// Bit4:1 (one secret pre device)
// Bit5: 1 (OTA support)
// Bit6~Bit7: 01 (00:4.0 01:4.2 10:5.0 11:>5.0)
genie_uuid[2] = 0x71;
// Product ID
for (i = 0; i < 4; i++)
{
genie_uuid[3 + i] = (p_genie_triple->pid >> (i << 3)) & 0xFF;
}
// mac addr (device name)
for (i = 0; i < GENIE_TRIPLE_MAC_SIZE; i++)
{
genie_uuid[7 + i] = p_genie_triple->mac[GENIE_TRIPLE_MAC_SIZE - 1 - i];
}
genie_uuid[13] = UNPROV_ADV_FEATURE1_UUID_VERSION;
#if defined(BOARD_TG7100B)
genie_uuid[14] = UNPROV_ADV_FEATURE2_GENIE_MESH_STACK_V1;
#elif defined(BOARD_PHY6220_EVB) || defined(BOARD_TG7120B_EVB)
genie_uuid[14] = UNPROV_ADV_FEATURE2_GENIE_MESH_STACK_V2;
#elif defined(BOARD_TG7121B_EVB)
genie_uuid[14] = UNPROV_ADV_FEATURE2_GENIE_MESH_STACK_V3;
#endif
#ifdef GENIE_ULTRA_PROV
genie_uuid[14] |= UNPROV_ADV_FEATURE2_ULTRA_PROV_FLAG;
genie_uuid[14] |= UNPROV_ADV_FEATURE2_AUTH_FLAG;
#else
#ifndef GENIE_OLD_AUTH
genie_uuid[14] |= UNPROV_ADV_FEATURE2_AUTH_FLAG;
#endif
#endif
BT_INFO("uuid: %s", bt_hex(genie_uuid, GENIE_PROVISON_UUID_LEN));
return genie_uuid;
}
int genie_provision_get_saved_data(genie_provision_t *p_genie_provision)
{
genie_storage_status_e ret = GENIE_STORAGE_SUCCESS;
if (p_genie_provision == NULL)
{
return -1;
}
memset(p_genie_provision, 0, sizeof(genie_provision_t));
ret = genie_storage_read_addr(&p_genie_provision->addr);
if (ret != GENIE_STORAGE_SUCCESS)
{
return ret;
}
ret = genie_storage_read_seq(&p_genie_provision->seq);
if (ret != GENIE_STORAGE_SUCCESS)
{
return ret;
}
ret = genie_storage_read_devkey(p_genie_provision->devkey);
if (ret != GENIE_STORAGE_SUCCESS)
{
return ret;
}
ret = genie_storage_read_netkey(&p_genie_provision->netkey);
if (ret != GENIE_STORAGE_SUCCESS)
{
return ret;
}
ret = genie_storage_read_appkey(&p_genie_provision->appkey);
if (ret != GENIE_STORAGE_SUCCESS)
{
return ret;
}
return 0;
}
#ifdef GENIE_ULTRA_PROV
void ultra_prov_get_auth(const uint8_t random_hex[16], const uint8_t key[16], uint8_t cfm[16])
{
bt_mesh_prov_conf(key, random_hex, genie_crypto_get_auth(random_hex), cfm);
BT_DBG("cfm: %s", bt_hex(cfm, 16));
}
static int _ultra_prov_send(uint8_t type, uint8_t *p_msg, uint8_t len)
{
struct net_buf *buf;
buf = bt_mesh_adv_create(0, 0, BUF_TIMEOUT);
if (!buf)
{
BT_ERR("Out of provisioning buffers");
return -ENOBUFS;
}
BT_MESH_ADV(buf)->tiny_adv = 1;
net_buf_add_be16(buf, CONFIG_MESH_VENDOR_COMPANY_ID);
//VID
net_buf_add_u8(buf, 0x0d);
net_buf_add_u8(buf, type);
net_buf_add_mem(buf, p_msg, len);
BT_DBG("send %s", bt_hex(buf->data, buf->len));
bt_mesh_adv_send(buf, NULL, NULL);
net_buf_unref(buf);
return 0;
}
static void genie_provision_ultra_prov_recv_random(uint8_t *buf)
{
uint8_t tmp[48];
uint8_t random_a[17];
uint8_t random_b[17];
uint8_t cfm_key[32];
int ret;
struct tc_sha256_state_struct sha256_ctx;
genie_triple_t *p_genie_triple = genie_triple_get();
if (buf[0] != p_genie_triple->mac[4] || buf[1] != p_genie_triple->mac[5])
{
return;
}
buf += 2;
genie_event(GENIE_EVT_SDK_MESH_PROV_START, NULL);
memset(p_prov_data_key, 0, sizeof(p_prov_data_key));
memset(p_ultra_prov_devkey, 0, sizeof(p_ultra_prov_devkey));
memset(p_confirm, 0, sizeof(p_confirm));
hextostring(buf, (char *)random_a, 8);
random_a[16] = 0;
hextostring(buf + 8, (char *)random_b, 8);
random_b[16] = 0;
sprintf((char *)tmp, "%s%sConfirmationKey", random_a, random_b);
BT_DBG("string %s\n", tmp);
/* calculate the sha256 of random and
* fetch the top 16 bytes as confirmationKey
*/
ret = tc_sha256_init(&sha256_ctx);
if (ret != TC_CRYPTO_SUCCESS)
{
BT_ERR("sha256 init fail\n");
}
ret = tc_sha256_update(&sha256_ctx, tmp, 47);
if (ret != TC_CRYPTO_SUCCESS)
{
BT_ERR("sha256 udpate fail\n");
}
ret = tc_sha256_final(cfm_key, &sha256_ctx);
if (ret != TC_CRYPTO_SUCCESS)
{
BT_ERR("sha256 final fail\n");
}
else
{
BT_DBG("cfmKey: %s", bt_hex(cfm_key, 16));
}
//calc cloud cfm
memcpy(tmp, buf + 8, 8);
memcpy(tmp + 8, buf, 8);
ultra_prov_get_auth(tmp, cfm_key, p_confirm);
hextostring(p_confirm, (char *)tmp, 16);
sprintf((char *)tmp + 32, "SessionKey");
BT_DBG("tmp %s\n", tmp);
ret = tc_sha256_init(&sha256_ctx);
if (ret != TC_CRYPTO_SUCCESS)
{
BT_ERR("sha256 init fail\n");
}
ret = tc_sha256_update(&sha256_ctx, tmp, 42);
if (ret != TC_CRYPTO_SUCCESS)
{
BT_ERR("sha256 udpate fail\n");
}
ret = tc_sha256_final(p_prov_data_key, &sha256_ctx);
if (ret != TC_CRYPTO_SUCCESS)
{
BT_ERR("sha256 final fail\n");
}
else
{
BT_DBG("provKkey: %s", bt_hex(p_prov_data_key, 22));
}
//calc dev key
sprintf((char *)tmp + 32, "DeviceKey");
BT_DBG("tmp %s\n", tmp);
ret = tc_sha256_init(&sha256_ctx);
if (ret != TC_CRYPTO_SUCCESS)
{
BT_ERR("sha256 init fail\n");
}
ret = tc_sha256_update(&sha256_ctx, tmp, 41);
if (ret != TC_CRYPTO_SUCCESS)
{
BT_ERR("sha256 udpate fail\n");
}
ret = tc_sha256_final(p_ultra_prov_devkey, &sha256_ctx);
if (ret != TC_CRYPTO_SUCCESS)
{
BT_ERR("sha256 final fail\n");
}
else
{
BT_INFO("dk %s", bt_hex(p_ultra_prov_devkey, 16));
}
memcpy(tmp, buf, 16);
ultra_prov_get_auth(tmp, cfm_key, p_confirm);
tmp[0] = p_genie_triple->mac[4];
tmp[1] = p_genie_triple->mac[5];
memcpy(tmp + 2, p_confirm, 16);
_ultra_prov_send(GENIE_PROV_STATUS_SEND_CONFIRM_DATA, tmp, 18);
}
static void genie_provision_ultra_prov_recv_data(uint8_t *buf)
{
uint8_t i = 0;
uint16_t net_idx;
uint8_t flags;
uint32_t iv_index;
uint16_t addr;
genie_triple_t *p_genie_triple = genie_triple_get();
if (genie_provision_get_state() != GENIE_PROVISION_START)
{
BT_WARN("I not in provisioning");
return;
}
while (i < 22)
{
buf[i] ^= p_prov_data_key[i];
i++;
}
BT_DBG("%s", bt_hex(buf, 22));
if (buf[0] != p_genie_triple->mac[4] || buf[1] != p_genie_triple->mac[5])
{
return;
}
buf += 2;
flags = buf[0];
net_idx = 0;
iv_index = buf[17];
addr = sys_get_be16(&buf[18]);
BT_DBG("net_idx %u iv_index 0x%08x, addr 0x%04x",
net_idx, iv_index, addr);
genie_event(GENIE_EVT_SDK_MESH_PROV_DATA, &addr);
BT_INFO("nk %s", bt_hex(buf + 1, 16));
bt_mesh_provision(buf + 1, net_idx, flags, iv_index, addr, p_ultra_prov_devkey);
_ultra_prov_send(GENIE_PROV_STATUS_SEND_COMPLETED, p_genie_triple->mac, 6);
}
int genie_provision_ultra_prov_handle(uint8_t frame_type, void *frame_buf)
{
uint16_t company = 0;
uint8_t fixed_byte = 0;
uint8_t prov_cmd = 0;
struct net_buf_simple *buf = NULL;
buf = (struct net_buf_simple *)frame_buf;
if (frame_type != GENIE_PROV_ADV_TYPE || buf == NULL)
{
return -1;
}
company = net_buf_simple_pull_be16(buf);
if (company == CONFIG_MESH_VENDOR_COMPANY_ID)
{
fixed_byte = net_buf_simple_pull_u8(buf);
if (fixed_byte == GENIE_PROV_FIXED_BYTE)
{
prov_cmd = net_buf_simple_pull_u8(buf);
switch (prov_cmd)
{
case GENIE_PROV_STATUS_RECV_RANDOM:
genie_provision_ultra_prov_recv_random(buf->data);
break;
case GENIE_PROV_STATUS_RECV_PROV_DATA:
genie_provision_ultra_prov_recv_data(buf->data);
break;
default:
break;
}
}
}
return 0;
}
#endif
static void _genie_pbadv_timer_cb(void *p_timer, void *args)
{
genie_event(GENIE_EVT_SDK_MESH_PBADV_TIMEOUT, NULL);
}
void genie_provision_pbadv_timer_start(uint32_t prov_timeout)
{
static uint8_t inited = 0;
if (!inited)
{
k_timer_init(&pbadv_timeout_timer, _genie_pbadv_timer_cb, NULL);
inited = 1;
}
k_timer_start(&pbadv_timeout_timer, prov_timeout);
}
void genie_provision_pbadv_timer_stop(void)
{
k_timer_stop(&pbadv_timeout_timer);
}
void genie_provision_start_slient_pbadv(void)
{
genie_provision_set_silent_flag();
//bt_mesh_prov_disable(BT_MESH_PROV_GATT | BT_MESH_PROV_ADV);
extern void genie_set_silent_unprov_beacon_interval(bool is_silent);
genie_set_silent_unprov_beacon_interval(true);
bt_mesh_prov_enable(BT_MESH_PROV_ADV);
}
static void _genie_prov_timer_cb(void *p_timer, void *args)
{
genie_event(GENIE_EVT_SDK_MESH_PROV_TIMEOUT, NULL);
}
void genie_provision_prov_timer_start(void)
{
static uint8_t inited = 0;
if (!inited)
{
k_timer_init(&prov_timeout_timer, _genie_prov_timer_cb, NULL);
inited = 1;
}
k_timer_start(&prov_timeout_timer, MESH_PROVISIONING_TIMEOUT);
}
void genie_provision_prov_timer_stop(void)
{
k_timer_stop(&prov_timeout_timer);
}
| YifuLiu/AliOS-Things | components/genie_service/core/src/genie_provision.c | C | apache-2.0 | 10,953 |
/*
* Copyright (C) 2018-2020 Alibaba Group Holding Limited
*/
#define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_MESH_DEBUG_MODEL)
//#include <port/mesh_hal_ble.h>
#include "common/log.h"
#include "mesh/access.h"
#include "mesh/main.h"
#include "prov.h"
#include "genie_service.h"
static struct k_timer repeat_reset_timer;
static struct k_timer delay_reset_timer;
//1:need reset 0:no reset
static uint8_t hw_reset_flag = 0;
uint8_t genie_reset_get_hw_reset_flag(void)
{
return hw_reset_flag;
}
static genie_storage_status_e _genie_reset_write_count(uint8_t count)
{
uint8_t data = count;
return genie_storage_write_userdata(GFI_MESH_RESET_CNT, &data, 1);
}
static void repeat_reset_timer_cb(void *p_timer, void *args)
{
uint8_t number = 0;
_genie_reset_write_count(number);
}
void genie_reset_by_repeat_init(void)
{
uint8_t count = 0;
genie_storage_status_e flash_err = GENIE_STORAGE_SUCCESS;
flash_err = genie_storage_read_userdata(GFI_MESH_RESET_CNT, &count, 1);
if (flash_err != GENIE_STORAGE_SUCCESS)
{
count = 0;
}
/* update number and check if exceeded */
if (count > GENIE_RESET_BY_REPEAT_COUNTER)
{
count = 0;
}
if (count < GENIE_RESET_BY_REPEAT_COUNTER)
{
count++;
_genie_reset_write_count(count);
}
else
{
hw_reset_flag = 1;
}
k_timer_init(&repeat_reset_timer, repeat_reset_timer_cb, NULL);
k_timer_start(&repeat_reset_timer, GENIE_RESET_BY_REPEAT_TIMEOUT);
}
int genie_reset_provision(void)
{
bt_mesh_reset();
if (bt_prov_active())
{
extern void reset_link(void);
reset_link();
}
bt_mesh_adv_stop();
#ifndef CONFIG_BT_SETTINGS
return genie_storage_reset_system();
#else
return 0;
#endif
}
static void delay_reset_timer_cb(void *p_timer, void *args)
{
genie_provision_set_state(GENIE_PROVISION_UNPROV);
genie_reset_provision();
#ifdef CONFIG_GENIE_SW_RESET_PROV
bt_mesh_prov_enable(BT_MESH_PROV_GATT | BT_MESH_PROV_ADV);
genie_event(GENIE_EVT_SDK_MESH_PBADV_START, NULL);
return;
#else
aos_reboot();
#endif
}
genie_event_e genie_reset_do_sw_reset(void)
{
k_timer_start(&delay_reset_timer, GENIE_RESET_WAIT_TIMEOUT); //wait report reset event done
return GENIE_EVT_NONE;
}
static int reset_report_result_cb(transport_result_e result_e)
{
if (result_e == SEND_RESULT_SUCCESS)
{
hw_reset_flag = 0;
GENIE_LOG_INFO("report reset ok");
}
else
{
GENIE_LOG_INFO("report reset fail");
}
return 0;
}
static int genie_reset_report_device_reset(void)
{
uint8_t payload[3];
genie_transport_payload_param_t transport_payload_param;
payload[0] = ATTR_TYPE_DEVICE_EVENT & 0xFF;
payload[1] = (ATTR_TYPE_DEVICE_EVENT >> 8) & 0xFF;
payload[2] = EL_HW_RESET_T;
memset(&transport_payload_param, 0, sizeof(genie_transport_payload_param_t));
transport_payload_param.opid = VENDOR_OP_ATTR_INDICATE;
transport_payload_param.p_payload = payload;
transport_payload_param.payload_len = sizeof(payload);
transport_payload_param.retry_cnt = GENIE_TRANSPORT_DEFAULT_RETRY_COUNT;
transport_payload_param.result_cb = reset_report_result_cb;
return genie_transport_send_payload(&transport_payload_param);
}
genie_event_e genie_reset_do_hw_reset(bool is_only_report)
{ extern uint8_t is_proxy_connected();
if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY) && !is_proxy_connected()) {
extern int bt_mesh_proxy_gatt_disable();
bt_mesh_proxy_gatt_disable();
}
genie_reset_report_device_reset();
if (is_only_report)
{
return GENIE_EVT_NONE;
}
else
{
return GENIE_EVT_SW_RESET;
}
}
int genie_reset_init(void)
{
#ifdef CONFIG_GENIE_RESET_BY_REPEAT
genie_reset_by_repeat_init();
#endif
k_timer_init(&delay_reset_timer, delay_reset_timer_cb, NULL);
return 0;
}
| YifuLiu/AliOS-Things | components/genie_service/core/src/genie_reset.c | C | apache-2.0 | 3,933 |
/*
* Copyright (C) 2018-2020 Alibaba Group Holding Limited
*/
#include <stdlib.h>
//#include <aos/aos.h>
#include <aos/kv.h>
#include "aos/hal/flash.h"
#include <hal/hal.h>
#include "crc16.h"
#include "bt_crypto.h"
#include "genie_service.h"
#define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_MESH_DEBUG_FLASH)
#include "common/log.h"
static uint8_t g_enc_key[16] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
static genie_storage_status_e _genie_storage_encrypt(uint8_t *p_buff, uint16_t size)
{
uint8_t data_temp[16];
uint8_t enc_temp[16];
uint16_t i = 0;
while (i < (size >> 4))
{
memcpy(data_temp, p_buff + (i << 4), 16);
BT_DBG("data: %s", bt_hex(data_temp, 16));
bt_mesh_aes_encrypt(g_enc_key, data_temp, enc_temp);
memcpy(p_buff + (i << 4), enc_temp, 16);
i++;
}
return 0;
}
static genie_storage_status_e _genie_storage_decrypt(uint8_t *p_buff, uint16_t size)
{
uint8_t data_temp[16];
uint8_t dec_temp[16];
uint16_t i = 0;
while (i < (size >> 4))
{
memcpy(data_temp, p_buff + (i << 4), 16);
bt_mesh_aes_decrypt(g_enc_key, data_temp, dec_temp);
BT_DBG("dec: %s", bt_hex(dec_temp, 16));
memcpy(p_buff + (i << 4), dec_temp, 16);
i++;
}
return 0;
}
#ifdef PROJECT_SECRET_KEY
static void _ginie_flash_get_enc_key(uint8_t project_key[16])
{
BT_DBG("project key: %s", bt_hex(project_key, 16));
//TODO:need find suitable key
bt_mesh_aes_encrypt(project_key, project_key, g_enc_key);
BT_DBG("enc key: %s", bt_hex(g_enc_key, 16));
}
#endif
genie_storage_status_e genie_storage_init(void)
{
static uint8_t flash_already_inited = 0;
genie_storage_status_e ret = GENIE_STORAGE_SUCCESS;
if (flash_already_inited == 1)
{
return GENIE_STORAGE_SUCCESS;
}
flash_already_inited = 1;
#ifdef PROJECT_SECRET_KEY
char key_char[] = PROJECT_SECRET_KEY;
uint8_t prj_key[16];
memset(prj_key, 0, 16);
stringtohex(key_char, prj_key, 16);
_ginie_flash_get_enc_key(prj_key);
#endif
return ret;
}
static int genie_kv_read(int key_index, uint8_t *value, uint16_t value_size)
{
int read_len = 0;
char key[10] = {0};
read_len = value_size;
snprintf(key, sizeof(key), "%s_%d", "key", key_index);
return aos_kv_get(key, value, &read_len);
}
static genie_storage_status_e _genie_storage_read(uint16_t key_index, uint8_t *p_buff, uint16_t size)
{
int retval = 0;
retval = genie_kv_read(key_index, p_buff, size);
if (retval != 0)
{
//GENIE_LOG_ERR("func:%s index(%d) failed(%d)\n", __func__, key_index, retval);
return GENIE_STORAGE_READ_FAIL;
}
else
{
return GENIE_STORAGE_SUCCESS;
}
}
static int genie_kv_write(int key_index, uint8_t *value, uint16_t value_size)
{
char key[10] = {0};
snprintf(key, sizeof(key), "%s_%d", "key", key_index);
return aos_kv_set(key, value, (int)value_size, 0);
}
static genie_storage_status_e _genie_storage_write(uint16_t key_index, uint8_t *p_buff, uint16_t size)
{
int retval = 0;
if (p_buff == NULL || 0 == size)
{
GENIE_LOG_ERR("p_buff is null!!!");
return GENIE_STORAGE_DATA_INVALID;
}
retval = genie_kv_write(key_index, p_buff, size);
if (retval != 0)
{
//GENIE_LOG_ERR("func:%s index(%d) failed(%d)\n", __func__, key_index, retval);
return GENIE_STORAGE_WRITE_FAIL;
}
return GENIE_STORAGE_SUCCESS;
}
static uint16_t _genie_storage_get_reliable_size(uint16_t data_size)
{
if ((data_size & 0x0F) == 0)
{
return data_size;
}
else
{
return ((data_size >> 4) + 1) << 4;
}
}
genie_storage_status_e genie_storage_read_reliable(uint16_t index, uint8_t *p_data, uint16_t data_size)
{
genie_storage_status_e ret = GENIE_STORAGE_SUCCESS;
uint16_t buff_size = _genie_storage_get_reliable_size(data_size);
uint8_t *p_buff = NULL;
if (p_data == NULL)
{
GENIE_LOG_ERR("p_data is null!!!");
return GENIE_STORAGE_DATA_INVALID;
}
p_buff = hal_malloc(buff_size);
if (p_buff == NULL)
{
GENIE_LOG_ERR("p_buff is null!!!");
return GENIE_STORAGE_DATA_INVALID;
}
if (GFI_MESH_TRITUPLE == index)
{
if (0 != hal_flash_read_triples(p_buff, buff_size))
{
GENIE_LOG_ERR("read triples fail");
ret = GENIE_STORAGE_READ_FAIL;
}
}
else
{
ret = _genie_storage_read(index, p_buff, buff_size);
}
if (ret == 0)
{
_genie_storage_decrypt(p_buff, buff_size);
memcpy(p_data, p_buff, data_size);
}
hal_free(p_buff);
return ret;
}
genie_storage_status_e genie_storage_write_reliable(uint16_t index, uint8_t *p_data, uint16_t data_size)
{
uint8_t *p_buff = NULL;
genie_storage_status_e ret = GENIE_STORAGE_SUCCESS;
uint16_t buff_size = _genie_storage_get_reliable_size(data_size);
if (p_data == NULL)
{
GENIE_LOG_ERR("p_data is null!!!");
return GENIE_STORAGE_DATA_INVALID;
}
p_buff = hal_malloc(buff_size);
if (p_buff == NULL)
{
GENIE_LOG_ERR("p_buff is null!!!");
return GENIE_STORAGE_DATA_INVALID;
}
memset(p_buff, 0, buff_size);
memcpy(p_buff, p_data, data_size);
GENIE_LOG_DBG("data:%d buff:%d", data_size, buff_size);
_genie_storage_encrypt(p_buff, buff_size);
if (GFI_MESH_TRITUPLE == index)
{
if (0 != hal_flash_write_triples(p_buff, buff_size))
{
GENIE_LOG_ERR("write triples fail");
ret = GENIE_STORAGE_WRITE_FAIL;
}
}
else
{
ret = _genie_storage_write(index, p_buff, buff_size);
}
hal_free(p_buff);
return ret;
}
genie_storage_status_e genie_storage_delete_reliable(uint16_t index)
{
char key[10] = {0};
snprintf(key, sizeof(key), "%s_%d", "key", index);
return aos_kv_del(key);
}
genie_storage_status_e genie_storage_read_userdata(uint16_t index, uint8_t *p_buff, uint16_t size)
{
return _genie_storage_read(index, p_buff, size);
}
genie_storage_status_e genie_storage_write_userdata(uint16_t index, uint8_t *p_buff, uint16_t size)
{
return _genie_storage_write(index, p_buff, size);
}
genie_storage_status_e genie_storage_delete_userdata(uint16_t index)
{
char key[10] = {0};
snprintf(key, sizeof(key), "%s_%d", "key", index);
return aos_kv_del(key);
}
genie_storage_status_e genie_storage_write_seq(uint32_t *p_seq, bool force_write)
{
int ret = -1;
uint32_t seq_write = 0;
/*Don't save seq number too frequently for save energy*/
/*Save seq number 1\2\3 for provision*/
if ((force_write == false) && (*p_seq > 0x03) && (*p_seq % GENIE_SEQ_SAVE_INTERVAL) != 0)
{
//GENIE_LOG_INFO("no save seq(%d)", *p_seq);
return GENIE_STORAGE_SUCCESS;
}
seq_write = (*p_seq & 0x00FFFFFF) | (GENIE_SEQ_MAGIC_NUMBER << 24);
ret = aos_kv_set(GENIE_KV_SEQ_KEY, &seq_write, sizeof(uint32_t), 0);
if (ret != 0)
{
GENIE_LOG_ERR("func:%s (%d)failed\n", __func__, ret);
return GENIE_STORAGE_WRITE_FAIL;
}
else
{
return GENIE_STORAGE_SUCCESS;
}
}
genie_storage_status_e genie_storage_read_seq(uint32_t *p_seq)
{
int ret = -1;
uint32_t seq_read;
int seq_len = sizeof(uint32_t);
ret = aos_kv_get(GENIE_KV_SEQ_KEY, &seq_read, &seq_len);
if ((seq_read >> 24) != GENIE_SEQ_MAGIC_NUMBER)
{
return GENIE_STORAGE_DATA_INVALID;
}
*p_seq = seq_read & 0x00FFFFFF;
*p_seq += GENIE_SEQ_SAVE_INTERVAL;
genie_storage_write_seq(p_seq, true); //update seq in kv
return ret;
}
genie_storage_status_e genie_storage_delete_seq(void)
{
int ret = -1;
ret = aos_kv_del(GENIE_KV_SEQ_KEY);
if (ret != 0)
{
GENIE_LOG_ERR("func:%s (%d)failed\n", __func__, ret);
return GENIE_STORAGE_DELETE_FAIL;
}
else
{
return GENIE_STORAGE_SUCCESS;
}
}
genie_storage_status_e genie_storage_write_sub(uint16_t *p_sub)
{
uint16_t group_addr_crc = 0;
uint16_t crc_magic = 0xA5A6;
uint8_t data[CONFIG_BT_MESH_MODEL_GROUP_COUNT * 2 + 2] = {0};
memcpy(data, p_sub, CONFIG_BT_MESH_MODEL_GROUP_COUNT * 2);
group_addr_crc = util_crc16_compute(data, CONFIG_BT_MESH_MODEL_GROUP_COUNT * 2, &crc_magic);
memcpy(data + CONFIG_BT_MESH_MODEL_GROUP_COUNT * 2, (unsigned char *)&group_addr_crc, 2);
return hal_flash_write_group_addr(data, CONFIG_BT_MESH_MODEL_GROUP_COUNT * 2 + 2);
}
genie_storage_status_e genie_storage_read_sub(uint16_t *p_sub)
{
uint16_t group_addr_crc = 0;
uint16_t group_addr_read_crc = 0;
uint16_t crc_magic = 0xA5A6;
uint8_t *p_crc = NULL;
uint8_t data[CONFIG_BT_MESH_MODEL_GROUP_COUNT * 2 + 2] = {0};
if (0 != hal_flash_read_group_addr(data, CONFIG_BT_MESH_MODEL_GROUP_COUNT * 2 + 2))
{
GENIE_LOG_ERR("read group addr fail");
return GENIE_STORAGE_READ_FAIL;
}
group_addr_crc = util_crc16_compute(data, CONFIG_BT_MESH_MODEL_GROUP_COUNT * 2, &crc_magic);
p_crc = data + CONFIG_BT_MESH_MODEL_GROUP_COUNT * 2;
group_addr_read_crc = p_crc[0] | (p_crc[1] << 8);
if (group_addr_read_crc != group_addr_crc)
{
return GENIE_STORAGE_READ_FAIL;
}
memcpy(p_sub, data, CONFIG_BT_MESH_MODEL_GROUP_COUNT * 2);
return GENIE_STORAGE_SUCCESS;
}
genie_storage_status_e genie_storage_write_para(struct bt_mesh_net *mesh_data)
{
return genie_storage_write_reliable(GFI_MESH_PARA, (uint8_t *)mesh_data, sizeof(struct bt_mesh_net));
}
genie_storage_status_e genie_storage_read_para(struct bt_mesh_net *mesh_data)
{
return genie_storage_read_reliable(GFI_MESH_PARA, (uint8_t *)mesh_data, sizeof(struct bt_mesh_net));
}
genie_storage_status_e genie_storage_write_devkey(uint8_t *p_devkey)
{
return genie_storage_write_reliable(GFI_MESH_DEVKEY, p_devkey, 16);
}
genie_storage_status_e genie_storage_read_devkey(uint8_t *p_devkey)
{
return genie_storage_read_reliable(GFI_MESH_DEVKEY, p_devkey, 16);
}
genie_storage_status_e genie_storage_write_netkey(mesh_netkey_para_t *p_netkey)
{
return genie_storage_write_reliable(GFI_MESH_NETKEY, (uint8_t *)p_netkey, sizeof(mesh_netkey_para_t));
}
genie_storage_status_e genie_storage_read_netkey(mesh_netkey_para_t *p_netkey)
{
return genie_storage_read_reliable(GFI_MESH_NETKEY, (uint8_t *)p_netkey, sizeof(mesh_netkey_para_t));
}
genie_storage_status_e genie_storage_write_appkey(mesh_appkey_para_t *p_appkey)
{
return genie_storage_write_reliable(GFI_MESH_APPKEY, (uint8_t *)p_appkey, sizeof(mesh_appkey_para_t));
}
genie_storage_status_e genie_storage_read_appkey(mesh_appkey_para_t *p_appkey)
{
return genie_storage_read_reliable(GFI_MESH_APPKEY, (uint8_t *)p_appkey, sizeof(mesh_appkey_para_t));
}
genie_storage_status_e genie_storage_write_addr(uint16_t *p_addr)
{
BT_DBG("0x%04x", *p_addr);
return genie_storage_write_reliable(GFI_MESH_SADDR, (uint8_t *)p_addr, 2);
}
genie_storage_status_e genie_storage_read_addr(uint16_t *p_addr)
{
return genie_storage_read_reliable(GFI_MESH_SADDR, (uint8_t *)p_addr, 2);
}
genie_storage_status_e genie_storage_write_hb(mesh_hb_para_t *p_para)
{
return genie_storage_write_reliable(GFI_MESH_HB, (uint8_t *)p_para, sizeof(mesh_hb_para_t));
}
genie_storage_status_e genie_storage_read_hb(mesh_hb_para_t *p_para)
{
return genie_storage_read_reliable(GFI_MESH_HB, (uint8_t *)p_para, sizeof(mesh_hb_para_t));
}
#ifdef CONFIG_BT_MESH_CTRL_RELAY
genie_storage_status_e genie_storage_write_ctrl_relay(mesh_ctrl_relay_para_t *p_para)
{
return genie_storage_write_reliable(GFI_MESH_CTRL_RELAY, (uint8_t *)p_para, sizeof(mesh_ctrl_relay_para_t));
}
genie_storage_status_e genie_storage_read_ctrl_relay(mesh_ctrl_relay_para_t *p_para)
{
return genie_storage_read_reliable(GFI_MESH_CTRL_RELAY, (uint8_t *)p_para, sizeof(mesh_ctrl_relay_para_t));
}
#endif
genie_storage_status_e genie_storage_reset_system(void)
{
int ret = 0;
ret = aos_kv_reset();
if (ret != 0)
{
GENIE_LOG_ERR("func:%s (%d)failed", __func__, ret);
return GENIE_STORAGE_EARSE_FAIL;
}
return GENIE_STORAGE_SUCCESS;
}
| YifuLiu/AliOS-Things | components/genie_service/core/src/genie_storage.c | C | apache-2.0 | 12,320 |
/*
* Copyright (C) 2018-2020 Alibaba Group Holding Limited
*/
#include <stdint.h>
#include <api/mesh.h>
#include <misc/slist.h>
#include "genie_service.h"
#ifdef GENIE_TIME_UPDATE_WHEN_BOOTUP
#include "mesh.h"
#endif
static inline uint8_t is_leap_year(uint16_t year);
static genie_time_data_t genie_time_data;
static genie_time_timer_t genie_time_timer;
static utc_time_t local_time = {0};
#define GENIE_TIME_LOCK k_sem_take(&genie_time_timer.lock, -1)
#define GENIE_TIME_UNLOCK k_sem_give(&genie_time_timer.lock)
utc_time_t genie_time_local_time_get()
{
return local_time;
}
uint32_t genie_time_local_unixtime_get()
{
return genie_time_timer.unix_time;
}
static int genie_time_time_sync_get(uint16_t *period_time, uint8_t *retry_delay, uint8_t *retry_times)
{
*period_time = genie_time_data.timing_sync_config.period_time;
*retry_delay = genie_time_data.timing_sync_config.retry_delay;
*retry_times = genie_time_data.timing_sync_config.retry_times;
return 0;
}
static int genie_time_save()
{
#ifdef GT_STORE
int ret;
ret = genie_storage_write_userdata(GFI_MESH_VND_TIMER, &genie_time_data, sizeof(genie_time_data));
if (ret)
{
GENIE_LOG_DBG("vendor timers save fail %d\n", ret);
}
return ret;
#else
return -1;
#endif
}
static inline uint32_t UTC2unix(utc_time_t *utc_time)
{
uint32_t days;
uint16_t g_noleap_daysbeforemonth[13] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
days = (utc_time->year - 1970) * 365;
days += (utc_time->year - 1969) >> 2;
days += g_noleap_daysbeforemonth[utc_time->month];
if (utc_time->month >= 2 && is_leap_year(utc_time->year))
{
days++;
}
days += utc_time->day - 1;
return ((days * 24 + utc_time->hour) * 60 + utc_time->minutes) * 60 + utc_time->seconds;
}
static inline uint8_t next_weekday_diff_get(uint8_t weekday_now, uint8_t schedule)
{
uint16_t schedule_tmp = 0;
if (weekday_now == 0)
{
weekday_now = 7;
}
schedule_tmp = ((schedule | ((uint16_t)schedule << 7)) >> (weekday_now - 1)) & 0x7f;
uint8_t day_diff = 0;
while (day_diff < 7)
{
if ((schedule_tmp >> day_diff) & 0x0001)
{
break;
}
day_diff++;
}
return day_diff;
}
static genie_time_t *genie_time_find(uint8_t index)
{
if (index >= GENIE_TIME_MAX)
{
return NULL;
}
GENIE_TIME_LOCK;
genie_time_t *tmp, *node;
sys_slist_t *list;
list = &genie_time_timer.timer_list_active;
SYS_SLIST_FOR_EACH_CONTAINER_SAFE(list, node, tmp, next)
{
if (node->index == index)
{
GENIE_TIME_UNLOCK;
return node;
}
}
GENIE_TIME_UNLOCK;
return NULL;
}
static genie_time_t *genie_time_new()
{
genie_time_t *free_timer;
GENIE_TIME_LOCK;
free_timer = (genie_time_t *)sys_slist_get(&genie_time_timer.timer_list_idle);
GENIE_TIME_UNLOCK;
GENIE_LOG_DBG("timer new %p\n", free_timer);
return free_timer;
}
static int genie_time_periodic_start(uint8_t index, uint32_t periodic_time, uint8_t schedule, vendor_attr_data_t *attr_data)
{
genie_time_t *vendor_timer;
GENIE_LOG_DBG("periodic timer start index %d periodic_time %d schedule %d on_off %d\n",
index, periodic_time, schedule, attr_data->para);
if (!genie_time_timer.init)
{
return -GT_E_INIT;
}
if (!genie_time_timer.update)
{
return -GT_E_LOCALTIME_NOTSET;
}
if (index >= GENIE_TIME_MAX)
{
//return -GT_E_INDEX;
}
if (schedule == 0)
{
return -GT_E_PARAM;
}
vendor_timer = genie_time_find(index);
if (vendor_timer == NULL)
{
vendor_timer = genie_time_new();
if (vendor_timer == NULL)
{
return -GT_E_NORESOURCE;
}
}
else
{
GENIE_TIME_LOCK;
sys_slist_find_and_remove(&genie_time_timer.timer_list_active, &vendor_timer->next);
GENIE_TIME_UNLOCK;
}
vendor_timer->index = index;
vendor_timer->periodic = 1;
vendor_timer->periodic_time = periodic_time;
vendor_timer->schedule = schedule;
vendor_timer->state = TIMER_ON;
vendor_timer->attr_data.para = attr_data->para;
vendor_timer->attr_data.type = attr_data->type;
utc_time_t utc = local_time;
utc.hour = 0;
utc.minutes = 0;
utc.seconds = 0;
utc.day = utc.day + next_weekday_diff_get(local_time.weekday, schedule);
vendor_timer->unixtime_match = UTC2unix(&utc) + periodic_time - genie_time_data.timezone * HOUR;
GENIE_LOG_DBG("periodic timer unixtime_match %d\n", vendor_timer->unixtime_match);
GENIE_TIME_LOCK;
sys_slist_append(&genie_time_timer.timer_list_active, &vendor_timer->next);
GENIE_TIME_UNLOCK;
genie_time_save();
return 0;
}
static int8_t genie_time_timezone_get()
{
return genie_time_data.timezone;
}
static int genie_time_operate_status(uint8_t tid, u16_t attr_type)
{
u16_t payload_len = 0;
uint8_t payload[10] = {0};
genie_transport_payload_param_t transport_payload_param;
switch (attr_type)
{
case UNIX_TIME_T:
{
uint32_t unix_time = genie_time_local_unixtime_get();
payload[payload_len++] = UNIX_TIME_T & 0xff;
payload[payload_len++] = (UNIX_TIME_T >> 8) & 0xff;
payload[payload_len++] = (uint8_t)(unix_time & 0xFF);
payload[payload_len++] = (uint8_t)((unix_time >> 8) & 0xFF);
payload[payload_len++] = (uint8_t)((unix_time >> 16) & 0xFF);
payload[payload_len++] = (uint8_t)((unix_time >> 24) & 0xFF);
}
break;
case TIMEZONE_SETTING_T:
{
int8_t timezone = genie_time_timezone_get();
payload[payload_len++] = TIMEZONE_SETTING_T & 0xff;
payload[payload_len++] = (TIMEZONE_SETTING_T >> 8) & 0xff;
payload[payload_len++] = timezone;
}
break;
case TIMING_SYNC_T:
{
u16_t period_time = 0;
u8_t retry_delay = 0;
u8_t retry_times = 0;
genie_time_time_sync_get(&period_time, &retry_delay, &retry_times);
payload[payload_len++] = TIMING_SYNC_T & 0xff;
payload[payload_len++] = (TIMING_SYNC_T >> 8) & 0xff;
payload[payload_len++] = period_time & 0xff;
payload[payload_len++] = (period_time >> 8) & 0xff;
payload[payload_len++] = retry_delay;
payload[payload_len++] = retry_times;
}
break;
default:
return -1;
}
memset(&transport_payload_param, 0, sizeof(genie_transport_payload_param_t));
transport_payload_param.opid = VENDOR_OP_ATTR_STATUS;
transport_payload_param.p_payload = payload;
transport_payload_param.payload_len = payload_len;
transport_payload_param.retry_cnt = 1;
return genie_transport_send_payload(&transport_payload_param);
}
static int _genie_time_errcode_status(u16_t attr_type, u8_t err_code, u8_t index, uint8_t tid)
{
uint8_t payload[6] = {0};
genie_transport_payload_param_t transport_payload_param;
payload[0] = ERROR_CODE_T & 0xff;
payload[1] = (ERROR_CODE_T >> 8) & 0xff;
payload[2] = attr_type & 0xff;
payload[3] = (attr_type >> 8) & 0xff;
payload[4] = err_code;
payload[5] = index;
memset(&transport_payload_param, 0, sizeof(genie_transport_payload_param_t));
transport_payload_param.opid = VENDOR_OP_ATTR_STATUS;
transport_payload_param.p_payload = payload;
transport_payload_param.payload_len = sizeof(payload);
transport_payload_param.retry_cnt = 1;
return genie_transport_send_payload(&transport_payload_param);
}
static int genie_time_start(uint8_t index, uint32_t unix_time, vendor_attr_data_t *attr_data)
{
genie_time_t *vendor_timer;
if (!attr_data)
{
return -GT_E_PARAM;
}
GENIE_LOG_DBG("timer start index %d unix_time %d on_off %d\n",
index, unix_time, attr_data->type);
if (!genie_time_timer.init)
{
return -GT_E_INIT;
}
if (!genie_time_timer.update)
{
return -GT_E_LOCALTIME_NOTSET;
}
if (index >= GENIE_TIME_MAX)
{
//return -GT_E_INDEX;
}
if (unix_time <= genie_time_timer.unix_time)
{
return -GT_E_PARAM;
}
vendor_timer = genie_time_find(index);
if (vendor_timer == NULL)
{
vendor_timer = genie_time_new();
if (vendor_timer == NULL)
{
return -GT_E_NORESOURCE;
}
}
else
{
GENIE_TIME_LOCK;
sys_slist_find_and_remove(&genie_time_timer.timer_list_active, &vendor_timer->next);
GENIE_TIME_UNLOCK;
}
vendor_timer->index = index;
vendor_timer->unixtime_match = unix_time; // + genie_time_timer.timezone * HOUR;
vendor_timer->state = TIMER_ON;
vendor_timer->attr_data.type = attr_data->type;
vendor_timer->attr_data.para = attr_data->para;
GENIE_TIME_LOCK;
sys_slist_append(&genie_time_timer.timer_list_active, &vendor_timer->next);
GENIE_TIME_UNLOCK;
genie_time_save();
return 0;
}
int genie_time_timing_settting_event(u8_t op, u8_t *msg, u16_t msg_length, uint8_t tid)
{
struct
{
uint32_t unix_time;
uint8_t index;
vendor_attr_data_t attr_data;
} timing_setting_attr;
u8_t *pmsg = msg;
u16_t attr_type = *pmsg++;
uint16_t msg_len = msg_length;
genie_transport_payload_param_t transport_payload_param;
attr_type += (*pmsg++ << 8);
msg_len -= 2;
if (attr_type != TIMING_SETTING_T)
{
return -1;
}
if (op != VENDOR_OP_ATTR_SET_ACK && op != VENDOR_OP_ATTR_GET_STATUS)
{
return -1;
}
if (op == VENDOR_OP_ATTR_SET_ACK)
{
while (msg_len > 0)
{
if (msg_len < sizeof(timing_setting_attr))
{
break;
}
timing_setting_attr.index = *pmsg++;
uint32_t unixtime_tmp = (pmsg[0]) | (pmsg[1] << 8) | (pmsg[2] << 16) | (pmsg[3] << 24);
pmsg += 4;
timing_setting_attr.unix_time = unixtime_tmp / 60 * 60;
if (unixtime_tmp % 60 != 1)
{
//return _genie_time_errcode_status(TIMING_SETTING_T, ERR_CODE_NOTSUP_ATTR_OP,
// timing_setting_attr.index, tid);
}
timing_setting_attr.attr_data.type = (pmsg[0]) | (pmsg[1] << 8);
pmsg += 2;
if (timing_setting_attr.attr_data.type != ATTR_TYPE_GENERIC_ONOFF)
{
return _genie_time_errcode_status(TIMING_SETTING_T, ERR_CODE_NOTSUP_ATTR_OP,
timing_setting_attr.index, tid);
}
timing_setting_attr.attr_data.para = *pmsg++;
if (timing_setting_attr.attr_data.para > 1)
{
return _genie_time_errcode_status(TIMING_SETTING_T, ERR_CODE_NOTSUP_ATTR_PARAM,
timing_setting_attr.index, tid);
}
int ret = genie_time_start(timing_setting_attr.index,
timing_setting_attr.unix_time,
&timing_setting_attr.attr_data);
if (ret)
{
uint8_t errcode;
if (ret == -GT_E_INIT || ret == GT_E_LOCALTIME_NOTSET)
{
errcode = ERR_CODE_UNIXTIME;
}
else if (ret == -GT_E_INDEX)
{
errcode = ERR_CODE_TIMER_INDEX;
}
else if (ret == -GT_E_NORESOURCE)
{
errcode = ERR_CODE_TIMER_FULL;
}
else if (ret == -GT_E_PARAM)
{
errcode = ERR_CODE_TIMER_SETTING;
}
else
{
errcode = ERR_CODE_UNIXTIME;
}
return _genie_time_errcode_status(TIMING_SETTING_T, errcode,
timing_setting_attr.index, tid);
}
msg_len -= sizeof(timing_setting_attr);
}
}
memset(&transport_payload_param, 0, sizeof(genie_transport_payload_param_t));
transport_payload_param.opid = VENDOR_OP_ATTR_STATUS;
transport_payload_param.p_payload = msg;
transport_payload_param.payload_len = msg_length;
transport_payload_param.retry_cnt = 1;
return genie_transport_send_payload(&transport_payload_param);
}
int genie_time_priordic_timing_settting_event(u8_t op, u8_t *msg, u16_t msg_length, uint8_t tid)
{
struct
{
uint8_t index;
uint16_t prioridc_time;
uint8_t schedule;
vendor_attr_data_t attr_data;
} priordic_timing_attr;
u8_t *pmsg = msg;
u16_t attr_type = *pmsg++;
uint16_t msg_len = msg_length;
genie_transport_payload_param_t transport_payload_param;
attr_type += (*pmsg++ << 8);
msg_len -= 2;
if (attr_type != TIMING_PERIODIC_SETTING_T)
{
return -1;
}
if (op != VENDOR_OP_ATTR_SET_ACK && op != VENDOR_OP_ATTR_GET_STATUS)
{
return -1;
}
if (op == VENDOR_OP_ATTR_SET_ACK)
{
while (msg_len > 0)
{
if (msg_len < 7)
{ // sizeof(priordic_timing_attr) by bytes
break;
}
priordic_timing_attr.index = *pmsg++;
uint32_t priordic_tmp = (pmsg[0]) | (pmsg[1] << 8);
pmsg += 2;
priordic_timing_attr.prioridc_time = priordic_tmp & 0x0FFF;
if (((priordic_tmp >> 12) & 0x0F) != 1)
{
//return _genie_time_errcode_status(TIMING_PERIODIC_SETTING_T, ERR_CODE_NOTSUP_ATTR_OP,
// priordic_timing_attr.index, tid);
}
priordic_timing_attr.schedule = *pmsg++;
if (priordic_timing_attr.schedule > 0x7F)
{
return _genie_time_errcode_status(TIMING_PERIODIC_SETTING_T, ERR_CODE_TIMER_PRIORDIC_PARAM,
priordic_timing_attr.index, tid);
}
priordic_timing_attr.attr_data.type = (pmsg[0]) | (pmsg[1] << 8);
pmsg += 2;
if (priordic_timing_attr.attr_data.type != ATTR_TYPE_GENERIC_ONOFF)
{
return _genie_time_errcode_status(TIMING_PERIODIC_SETTING_T, ERR_CODE_NOTSUP_ATTR_OP,
priordic_timing_attr.index, tid);
}
priordic_timing_attr.attr_data.para = *pmsg++;
if (priordic_timing_attr.attr_data.para > 1)
{
return _genie_time_errcode_status(TIMING_PERIODIC_SETTING_T, ERR_CODE_NOTSUP_ATTR_PARAM,
priordic_timing_attr.index, tid);
}
int ret = genie_time_periodic_start(priordic_timing_attr.index,
priordic_timing_attr.prioridc_time * 60,
priordic_timing_attr.schedule,
&priordic_timing_attr.attr_data);
if (ret)
{
uint8_t errcode;
if (ret == -GT_E_INIT || ret == GT_E_LOCALTIME_NOTSET)
{
errcode = ERR_CODE_UNIXTIME;
}
else if (ret == -GT_E_INDEX)
{
errcode = ERR_CODE_TIMER_INDEX;
}
else if (ret == -GT_E_NORESOURCE)
{
errcode = ERR_CODE_TIMER_FULL;
}
else if (ret == -GT_E_PARAM)
{
errcode = ERR_CODE_TIMER_SETTING;
}
else
{
errcode = ERR_CODE_TIMER_PRIORDIC_PARAM;
}
return _genie_time_errcode_status(TIMING_PERIODIC_SETTING_T, errcode,
priordic_timing_attr.index, tid);
}
msg_len -= 7; // sizeof(priordic_timing_attr) by bytes
}
}
memset(&transport_payload_param, 0, sizeof(genie_transport_payload_param_t));
transport_payload_param.opid = VENDOR_OP_ATTR_STATUS;
transport_payload_param.p_payload = msg;
transport_payload_param.payload_len = msg_length;
transport_payload_param.retry_cnt = 1;
return genie_transport_send_payload(&transport_payload_param);
}
static int genie_time_stop(int8_t index)
{
if (!genie_time_timer.init)
{
return -GT_E_INIT;
}
if (!genie_time_timer.update)
{
return -GT_E_LOCALTIME_NOTSET;
}
if (index >= GENIE_TIME_MAX)
{
return -GT_E_INDEX;
}
genie_time_t *vendor_timer = genie_time_find(index);
if (vendor_timer == NULL)
{
return -GT_E_INDEX;
}
else
{
GENIE_TIME_LOCK;
GENIE_LOG_DBG("timer stop %d\n", index);
vendor_timer->index = 0xFF;
vendor_timer->state = TIMER_INVAILD;
vendor_timer->unixtime_match = 0;
sys_slist_find_and_remove(&genie_time_timer.timer_list_active, &vendor_timer->next);
sys_slist_append(&genie_time_timer.timer_list_idle, &vendor_timer->next);
GENIE_TIME_UNLOCK;
}
return 0;
}
static int genie_time_remove(int8_t index)
{
int i;
int ret = 0;
GENIE_LOG_DBG("timer remove %d\n", index);
/* remove alll timers */
if (index == 0xFF)
{
for (i = 0; i < GENIE_TIME_MAX; i++)
{
genie_time_stop(i);
}
}
else
{
ret = genie_time_stop(index);
}
genie_time_save();
return ret;
}
int genie_time_timing_remove_event(u8_t op, u8_t *msg, u16_t msg_length, uint8_t tid)
{
u8_t *pmsg = msg;
u16_t attr_type = *pmsg++;
uint16_t msg_len = msg_length;
genie_transport_payload_param_t transport_payload_param;
attr_type += (*pmsg++ << 8);
msg_len -= 2;
if (attr_type != TIMING_DELETE_T)
{
return -1;
}
if (op != VENDOR_OP_ATTR_SET_ACK)
{
return -1;
}
if (op == VENDOR_OP_ATTR_SET_ACK)
{
while (msg_len > 0)
{
uint8_t index = *pmsg++;
msg_len--;
int ret = genie_time_remove(index);
if (ret)
{
//return _genie_time_errcode_status(TIMING_DELETE_T, ERR_CODE_TIMER_INDEX, index, tid);
}
}
}
memset(&transport_payload_param, 0, sizeof(genie_transport_payload_param_t));
transport_payload_param.opid = VENDOR_OP_ATTR_STATUS;
transport_payload_param.p_payload = msg;
transport_payload_param.payload_len = msg_length;
transport_payload_param.retry_cnt = 1;
return genie_transport_send_payload(&transport_payload_param);
}
static void _genie_time_timeout_indicate(u8_t index)
{
uint8_t payload[4] = {0};
genie_transport_payload_param_t transport_payload_param;
payload[0] = TIMING_TIMEOUT_T & 0xff;
payload[1] = (TIMING_TIMEOUT_T >> 8) & 0xff;
payload[2] = EL_TIMING_TIMEOUT_T;
payload[3] = index;
memset(&transport_payload_param, 0, sizeof(genie_transport_payload_param_t));
transport_payload_param.opid = VENDOR_OP_ATTR_INDICATE;
transport_payload_param.p_payload = payload;
transport_payload_param.payload_len = sizeof(payload);
transport_payload_param.retry_cnt = VENDOR_MODEL_MSG_MAX_RETRY_TIMES;
genie_transport_send_payload(&transport_payload_param);
}
static inline utc_time_t unix2UTC(uint32_t unix_time)
{
utc_time_t utc;
uint16_t g_noleap_daysbeforemonth[13] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
uint32_t epoch;
uint32_t jdn;
int year;
int month;
int day;
int hour;
int minutes;
int sec;
int weekday;
epoch = unix_time;
jdn = epoch / DAY;
epoch -= DAY * jdn;
weekday = (jdn + 4) % 7; // 1970/1/1 is thursday
hour = epoch / HOUR;
epoch -= HOUR * hour;
minutes = epoch / MINU;
epoch -= MINU * minutes;
sec = epoch;
year = jdn / (4 * 365 + 1); /* Number of 4-years periods since the epoch */
jdn -= year * (4 * 365 + 1); /* Remaining days */
year <<= 2; /* Years since the epoch */
/* Then we will brute force the next 0-3 years */
bool leapyear;
int tmp;
for (;;)
{
/* Is this year a leap year (we'll need this later too) */
leapyear = is_leap_year(year + 1970);
/* Get the number of days in the year */
tmp = (leapyear ? 366 : 365);
/* Do we have that many days? */
if (jdn >= tmp)
{
/* Yes.. bump up the year */
year++;
jdn -= tmp;
}
else
{
/* Nope... then go handle months */
break;
}
}
/* At this point, value has the year and days has number days into this year */
year += 1970;
/* Handle the month (zero based) */
int min = 0;
int max = 11;
int value = 0;
do
{
/* Get the midpoint */
value = (min + max) >> 1;
/* Get the number of days that occurred before the beginning of the month
* following the midpoint.
*/
tmp = g_noleap_daysbeforemonth[value + 1];
if (value + 1 >= 2 && leapyear)
{
tmp++;
}
/* Does the number of days before this month that equal or exceed the
* number of days we have remaining?
*/
if (tmp > jdn)
{
/* Yes.. then the month we want is somewhere from 'min' and to the
* midpoint, 'value'. Could it be the midpoint?
*/
tmp = g_noleap_daysbeforemonth[value];
if (value >= 2 && leapyear)
{
tmp++;
}
if (tmp > jdn)
{
/* No... The one we want is somewhere between min and value-1 */
max = value - 1;
}
else
{
/* Yes.. 'value' contains the month that we want */
break;
}
}
else
{
/* No... The one we want is somwhere between value+1 and max */
min = value + 1;
}
/* If we break out of the loop because min == max, then we want value
* to be equal to min == max.
*/
value = min;
} while (min < max);
/* The selected month number is in value. Subtract the number of days in the
* selected month
*/
tmp = g_noleap_daysbeforemonth[value];
if (value >= 2 && leapyear)
{
tmp++;
}
jdn -= tmp;
/* At this point, value has the month into this year (zero based) and days has
* number of days into this month (zero based)
*/
month = value; // zero based
day = jdn + 1; // one based
utc.year = year;
utc.month = month;
utc.day = day;
utc.weekday = weekday;
utc.hour = hour;
utc.minutes = minutes;
utc.seconds = sec;
return utc;
}
static inline uint8_t is_leap_year(uint16_t year)
{
if (((year % 4) == 0) && ((year % 100) != 0))
{
return 1;
}
else if ((year % 400) == 0)
{
return 1;
}
else
{
return 0;
}
}
static inline void month_update()
{
local_time.month++;
if (local_time.month >= 12)
{
local_time.month = 0;
local_time.year++;
}
}
static inline void days_update()
{
uint8_t month_days_list[12] = {
31,
28,
31,
30,
31,
30,
31,
31,
30,
31,
30,
31,
};
local_time.day++;
if (is_leap_year(local_time.year))
{
month_days_list[1] = 29;
}
uint8_t month_day = month_days_list[local_time.month];
if (local_time.day > month_day)
{
local_time.day = 0;
month_update();
}
local_time.weekday = (local_time.weekday + 1) % 7;
}
static inline void hours_update()
{
local_time.hour++;
if (local_time.hour == 24)
{
local_time.hour = 0;
days_update();
}
}
static inline void minutes_update()
{
local_time.minutes++;
if (local_time.minutes == 60)
{
local_time.minutes = 0;
hours_update();
}
}
static inline void seconds_update()
{
local_time.seconds++;
if (local_time.seconds == 60)
{
local_time.seconds = 0;
minutes_update();
}
}
static inline uint8_t is_weekday_match(uint8_t weekday_now, uint8_t schedule)
{
uint8_t weekday_mask = weekday_now ? (uint8_t)(1 << (weekday_now - 1)) : (uint8_t)(1 << 6);
return (weekday_mask == (schedule & weekday_mask));
}
static inline uint8_t next_weekday(uint8_t weekday_now)
{
return (weekday_now + 1) % 7;
}
static int genie_time_erase()
{
#ifdef GT_STORE
int ret;
ret = genie_storage_delete_userdata();
if (ret)
{
GENIE_LOG_DBG("vendor timers flash erase fail %d\n", ret);
}
return ret;
#else
return 0;
#endif
}
static int genie_time_restore()
{
#ifdef GT_STORE
int ret;
uint16_t len = sizeof(genie_time_data);
memset(&genie_time_data, 0, sizeof(genie_time_data));
ret = genie_storage_read_userdata(GFI_MESH_VND_TIMER, &genie_time_data, &len);
if (ret)
{
GENIE_LOG_DBG("vendor timers restore fail %d\n", ret);
return ret;
}
if (genie_time_data.magic != 0xABCD || genie_time_data.timezone < -12 || genie_time_data.timezone > 12)
{
GENIE_LOG_DBG("vendor timers restore missmatch\n");
return -1;
}
int i = 0;
for (i = 0; i < GENIE_TIME_MAX; i++)
{
if (genie_time_data.timer_data[i].state != TIMER_INVAILD)
{
sys_slist_append(&genie_time_timer.timer_list_active, &genie_time_data.timer_data[i].next);
}
else
{
sys_slist_append(&genie_time_timer.timer_list_idle, &genie_time_data.timer_data[i].next);
}
GENIE_LOG_DBG("restore vendor timer index %d state %d periodic %d periodic_time %d schedule %d unixtime_match %d\n",
genie_time_data.timer_data[i].index, genie_time_data.timer_data[i].state,
genie_time_data.timer_data[i].periodic, genie_time_data.timer_data[i].periodic_time,
genie_time_data.timer_data[i].schedule, genie_time_data.timer_data[i].unixtime_match);
}
return 0;
#else
return -1;
#endif
}
static uint8_t is_genie_time_timeout(genie_time_t *vendor_timer)
{
if (vendor_timer->state == TIMER_INVAILD)
{
return 0;
}
if (vendor_timer->periodic)
{
if (is_weekday_match(local_time.weekday, vendor_timer->schedule) && vendor_timer->unixtime_match < genie_time_timer.unix_time)
{
vendor_timer->unixtime_match += (1 + next_weekday_diff_get(next_weekday(local_time.weekday), vendor_timer->schedule)) * DAY;
}
}
return vendor_timer->unixtime_match == genie_time_timer.unix_time;
}
static void genie_time_do_work(struct k_work *work)
{
genie_time_t *tmp = NULL, *node = NULL;
SYS_SLIST_FOR_EACH_CONTAINER_SAFE(&genie_time_timer.timer_list_active, node, tmp, next)
{
if (is_genie_time_timeout(node))
{
if (genie_time_timer.genie_time_event_cb)
{
genie_time_timer.genie_time_event_cb(GT_TIMEOUT, node->index, &node->attr_data);
}
GENIE_TIME_LOCK;
if (!node->periodic)
{
node->unixtime_match = 0xffffffff;
node->state = TIMER_INVAILD;
sys_slist_find_and_remove(&genie_time_timer.timer_list_active, &node->next);
sys_slist_append(&genie_time_timer.timer_list_idle, &node->next);
}
else
{
node->unixtime_match += 24 * HOUR;
}
GENIE_TIME_UNLOCK;
genie_time_save();
}
}
if (genie_time_timer.unix_time_sync_match && genie_time_timer.unix_time_sync_match <= genie_time_timer.unix_time)
{
if (genie_time_timer.genie_time_event_cb)
{
int ret = genie_time_timer.genie_time_event_cb(GT_TIMING_SYNC, 0, NULL);
if (ret)
{
if (genie_time_timer.unix_time_sync_retry_times > 0)
{
genie_time_timer.unix_time_sync_match += genie_time_data.timing_sync_config.retry_delay * MINU;
genie_time_timer.unix_time_sync_retry_times--;
return;
}
}
}
genie_time_timer.unix_time_sync_retry_times = genie_time_data.timing_sync_config.retry_times;
genie_time_timer.unix_time_sync_match = genie_time_timer.unix_time + genie_time_data.timing_sync_config.period_time * MINU;
}
}
static void timer_update(void *args)
{
if (!genie_time_timer.update)
{
return;
}
genie_time_timer.unix_time += 1;
seconds_update();
k_work_submit(&genie_time_timer.work);
if (genie_time_timer.unix_time % 60 == 0)
{
GENIE_LOG_DBG("timer_update %d\n", genie_time_timer.unix_time);
}
}
int genie_time_utc_start(uint8_t index, utc_time_t utc_time, vendor_attr_data_t *attr_data)
{
GENIE_LOG_DBG("utc timer start index %d on_off %d %4d/%2d/%2d %2d:%2d:%d weekday %2d %04d\n",
index, attr_data->para,
utc_time.year, utc_time.month + 1, utc_time.day,
utc_time.hour, utc_time.minutes, utc_time.seconds,
utc_time.weekday, genie_time_data.timezone);
return genie_time_start(index, UTC2unix(&utc_time), attr_data);
}
void genie_time_local_time_show()
{
GENIE_LOG_DBG("%4d/%2d/%2d %2d:%2d:%d weekday %2d %04d\n",
local_time.year, local_time.month + 1, local_time.day,
local_time.hour, local_time.minutes, local_time.seconds,
local_time.weekday, genie_time_data.timezone);
}
static int genie_time_timezone_update(int8_t timezone)
{
GENIE_LOG_DBG("timezone update %d\n", timezone);
if (timezone < -12 || timezone > 12)
{
return -GT_E_PARAM;
}
if (!genie_time_timer.init)
{
return -GT_E_INIT;
}
genie_time_data.timezone = timezone;
return 0;
}
static int genie_time_time_sync_set(uint16_t period_time, uint8_t retry_delay, uint8_t retry_times)
{
GENIE_LOG_DBG("timing sync set period_time %d retry_delay %d retry_times %d\n",
period_time, retry_delay, retry_times);
if (!period_time || !retry_delay || !retry_times)
{
return -GT_E_PARAM;
}
genie_time_data.timing_sync_config.period_time = period_time;
genie_time_data.timing_sync_config.retry_delay = retry_delay;
genie_time_data.timing_sync_config.retry_times = retry_times;
genie_time_timer.unix_time_sync_match = genie_time_timer.unix_time + genie_time_data.timing_sync_config.period_time * MINU;
genie_time_timer.unix_time_sync_retry_times = retry_times;
return 0;
}
static int genie_time_local_time_update(uint32_t unix_time)
{
if (!genie_time_timer.init)
{
return -GT_E_INIT;
}
genie_time_timer.update = 1;
genie_time_timer.unix_time = unix_time;
local_time = unix2UTC(unix_time + genie_time_data.timezone * HOUR);
GENIE_LOG_DBG("unix_time %d\n", unix_time);
GENIE_LOG_DBG("localtime update %4d/%2d/%2d %2d:%2d:%d weekday %2d\n",
local_time.year, local_time.month + 1, local_time.day,
local_time.hour, local_time.minutes, local_time.seconds,
local_time.weekday);
GENIE_LOG_DBG("unix_time revert %d\n", UTC2unix(&local_time));
genie_time_time_sync_set(DEF_SYNC_PERIOD, DEF_SYNC_DELAY, DEF_SYNC_DELAY_RETRY);
return 0;
}
#ifdef GENIE_TIME_UPDATE_WHEN_BOOTUP
static int genie_time_update(void)
{
if (bt_mesh_is_provisioned())
{
genie_time_timer.genie_time_event_cb(GT_TIMING_SYNC, 0, NULL);
return 0;
}
return -1;
}
#endif
static void genie_time_request_utc_time()
{
uint8_t payload[2] = {0};
genie_transport_payload_param_t transport_payload_param;
payload[0] = UNIX_TIME_T & 0xff;
payload[1] = (UNIX_TIME_T >> 8) & 0xff;
memset(&transport_payload_param, 0, sizeof(genie_transport_payload_param_t));
transport_payload_param.opid = VENDOR_OP_ATTR_INDICATE_TG;
transport_payload_param.p_payload = payload;
transport_payload_param.payload_len = sizeof(payload);
transport_payload_param.retry_cnt = 1;
genie_transport_send_payload(&transport_payload_param);
}
int genie_time_handle_model_mesg(genie_transport_model_param_t *p_msg)
{
u16_t attr_type = 0;
uint8_t *p_data = NULL;
uint16_t remain_len;
uint8_t is_time_mesg = 1;
if (!p_msg || !p_msg->data || p_msg->len == 0)
{
return -1;
}
p_data = p_msg->data;
remain_len = p_msg->len;
switch (p_msg->opid)
{
case VENDOR_OP_ATTR_GET_STATUS:
{
attr_type = *p_data++;
attr_type += (*p_data++ << 8);
remain_len -= 2;
if (attr_type == UNIX_TIME_T ||
attr_type == TIMEZONE_SETTING_T ||
attr_type == TIMING_SYNC_T)
{
genie_time_operate_status(p_msg->tid, attr_type);
}
else if (attr_type == TIMING_SETTING_T)
{
genie_time_timing_settting_event(VENDOR_OP_ATTR_GET_STATUS, p_msg->data, p_msg->len, p_msg->tid);
}
else if (attr_type == TIMING_PERIODIC_SETTING_T)
{
genie_time_priordic_timing_settting_event(VENDOR_OP_ATTR_GET_STATUS, p_msg->data, p_msg->len, p_msg->tid);
}
else
{
is_time_mesg = 0;
}
}
break;
case VENDOR_OP_ATTR_SET_ACK:
{
attr_type = *p_data++;
attr_type += (*p_data++ << 8);
remain_len -= 2;
if (attr_type == UNIX_TIME_T)
{
if (remain_len < 4) {
return -1;
}
uint32_t unix_time = (p_data[0]) | (p_data[1] << 8) | (p_data[2] << 16) | (p_data[3] << 24);
p_data += 4;
remain_len -= 4;
genie_time_local_time_update(unix_time);
genie_time_operate_status(p_msg->tid, attr_type);
}
else if (attr_type == TIMEZONE_SETTING_T)
{
if (remain_len < 1) {
return -1;
}
int8_t timezone = *p_data++;
remain_len -= 1;
genie_time_timezone_update(timezone);
genie_time_operate_status(p_msg->tid, attr_type);
}
else if (attr_type == TIMING_SYNC_T)
{
if (remain_len < 4) {
return -1;
}
u16_t period_time = (p_data[0]) | (p_data[1] << 8);
p_data += 2;
u8_t retry_delay = *p_data++;
u8_t retry_times = *p_data++;
remain_len -= 4;
genie_time_time_sync_set(period_time, retry_delay, retry_times);
genie_time_operate_status(p_msg->tid, attr_type);
}
else if (attr_type == TIMING_SETTING_T)
{
genie_time_timing_settting_event(VENDOR_OP_ATTR_SET_ACK, p_msg->data, p_msg->len, p_msg->tid);
}
else if (attr_type == TIMING_PERIODIC_SETTING_T)
{
genie_time_priordic_timing_settting_event(VENDOR_OP_ATTR_SET_ACK, p_msg->data, p_msg->len, p_msg->tid);
}
else if (attr_type == TIMING_DELETE_T)
{
genie_time_timing_remove_event(VENDOR_OP_ATTR_SET_ACK, p_msg->data, p_msg->len, p_msg->tid);
}
else
{
is_time_mesg = 0;
}
}
break;
case VENDOR_OP_ATTR_CONFIME_TG:
{
attr_type = *p_data++;
attr_type += (*p_data++ << 8);
remain_len -= 2;
if (attr_type == UNIX_TIME_T)
{
if (remain_len < 4) {
return -1;
}
uint32_t unix_time = (p_data[0]) | (p_data[1] << 8) | (p_data[2] << 16) | (p_data[3] << 24);
genie_time_local_time_update(unix_time);
}
else
{
is_time_mesg = 0;
}
}
break;
default:
{
is_time_mesg = 0;
}
break;
}
return is_time_mesg;
}
static int genie_time_event_callback(uint8_t event, uint8_t index, vendor_attr_data_t *data)
{
if (event == GT_TIMEOUT)
{
genie_time_local_time_show();
printf("timer index %d timeout\n", index);
genie_event(GENIE_EVT_TIMEOUT, data);
_genie_time_timeout_indicate(index);
}
else if (event == GT_TIMING_SYNC)
{
genie_time_request_utc_time();
}
return 0;
}
int genie_time_init(void)
{
int i;
if (genie_time_timer.init)
{
return 0;
}
memset(&genie_time_timer, 0, sizeof(genie_time_timer));
memset(&local_time, 0, sizeof(local_time));
genie_time_timer.genie_time_event_cb = genie_time_event_callback;
sys_slist_init(&genie_time_timer.timer_list_active);
sys_slist_init(&genie_time_timer.timer_list_idle);
k_sem_init(&genie_time_timer.lock, 1, 1);
k_work_init(&genie_time_timer.work, genie_time_do_work);
genie_time_timer.timer.port = GENIE_TIME_HW_TEIMER_ID;
genie_time_timer.timer.config.period = GENIE_TIME_HW_TEIMER_PERIOD;
genie_time_timer.timer.config.reload_mode = TIMER_RELOAD_AUTO;
genie_time_timer.timer.config.cb = timer_update;
genie_time_timer.timer.config.arg = NULL;
hal_timer_init(&genie_time_timer.timer);
hal_timer_start(&genie_time_timer.timer);
genie_time_timer.init = 1;
if (genie_time_restore())
{
memset(&genie_time_data, 0, sizeof(genie_time_data));
genie_time_data.timezone = 8;
genie_time_data.magic = 0xABCD;
for (i = 0; i < GENIE_TIME_MAX; i++)
{
genie_time_data.timer_data[i].unixtime_match = 0xffffffff;
genie_time_data.timer_data[i].index = 0xFF;
genie_time_data.timer_data[i].state = TIMER_INVAILD;
sys_slist_append(&genie_time_timer.timer_list_idle, &genie_time_data.timer_data[i].next);
}
}
#ifdef GENIE_TIME_UPDATE_WHEN_BOOTUP
genie_time_update(); //update UTC time from cloud
#endif
//GENIE_LOG_INFO("genie time init");
return 0;
}
int genie_time_finalize(void)
{
int ret;
int i = 0;
if (!genie_time_timer.init)
{
return -1;
}
for (i = 0; i < GENIE_TIME_MAX; i++)
{
genie_time_stop(i);
}
hal_timer_stop(&genie_time_timer.timer);
/*
ret = hal_timer_finalize(&genie_time_timer.timer);
if (ret)
{
printf("timer finalize faild\r\n");
return ret;
}*/
k_sem_delete(&genie_time_timer.lock);
(void)memset(&genie_time_timer, 0, offsetof(genie_time_timer_t, work));
memset(&local_time, 0, sizeof(local_time));
ret = genie_time_erase();
if (ret)
{
printf("timer erase faild\r\n");
}
return ret;
}
| YifuLiu/AliOS-Things | components/genie_service/core/src/genie_time.c | C | apache-2.0 | 39,564 |
/*
* Copyright (C) 2018-2020 Alibaba Group Holding Limited
*/
#include <aos/kernel.h>
#define BT_DBG_ENABLED IS_ENABLED(CONFIG_DEBUG_GENIE_TRANSPORT)
#include "common/log.h"
#include "mesh.h"
#include "mesh/access.h"
#include "net.h"
#include "access.h"
#ifdef CONFIG_SCAN_DURATION_AFTER_GENIE_MODEL_SEND
#include "adv.h"
#endif
#include "genie_service.h"
static uint16_t last_src_addr = BT_MESH_ADDR_TMALL_GENIE;
static genie_transport_tid_queue_t tid_queue[RECV_MSG_TID_QUEUE_SIZE];
#ifdef CONFIG_SCAN_DURATION_AFTER_GENIE_MODEL_SEND
static struct k_timer scan_off_timer;
#endif
/**
* send_list was used to save the unconfirmed vendor messages
* retransmit_timer was used to control when the vendor messages saved in send_list will be resent
* */
static sys_dlist_t send_list;
static struct k_timer retransmit_timer;
static aos_mutex_t transport_mutex;
/** @def genie_transport_msg_node_generate
*
* @brief duplicate genie_transport_model_param_t and save to genie_transport_node_t
*
* @param pointer to the vendor model message to be duplicated
*
* @return pointer to genie_transport_node_t for success, NULL for failure
*/
static genie_transport_node_t *genie_transport_msg_node_generate(genie_transport_model_param_t *p_model_msg)
{
genie_transport_node_t *p_node = NULL;
if (p_model_msg->retry > VENDOR_MODEL_MSG_MAX_RETRY_TIMES)
{
p_model_msg->retry = VENDOR_MODEL_MSG_MAX_RETRY_TIMES;
}
p_node = hal_malloc(sizeof(genie_transport_node_t) + p_model_msg->len);
if (!p_node)
{
BT_ERR("malloc for genie_transport_node_t failed");
return NULL;
}
memcpy(&p_node->msg, p_model_msg, sizeof(genie_transport_model_param_t));
BT_DBG("p_node->msg:%p, data:%p, %p", &p_node->msg, &p_node->msg.data, &p_node->msg.data + 1);
p_node->msg.data = (uint8_t *)(&p_node->msg.data + 1);
memcpy(p_node->msg.data, p_model_msg->data, p_model_msg->len);
BT_DBG("p_model_msg->data:%p, %s", p_model_msg->data, bt_hex(p_model_msg->data, p_model_msg->len));
BT_DBG("p_node->msg.data:%p, %s", p_node->msg.data, bt_hex(p_node->msg.data, p_node->msg.len));
p_node->timeout = k_uptime_get() + p_model_msg->retry_period;
p_node->left_retry = p_model_msg->retry;
return p_node;
}
static genie_transport_model_param_t *genie_transport_find_by_tid(uint8_t tid)
{
sys_dnode_t *p_node = NULL;
genie_transport_model_param_t *p_msg = NULL;
genie_transport_node_t *p_msg_node = NULL;
SYS_DLIST_FOR_EACH_NODE(&send_list, p_node)
{
p_msg_node = CONTAINER_OF(p_node, genie_transport_node_t, node);
if (p_msg_node == NULL)
{
continue;
}
p_msg = &p_msg_node->msg;
if (p_msg->tid == tid)
{
return p_msg;
}
}
return NULL;
}
#ifdef CONFIG_SCAN_DURATION_AFTER_GENIE_MODEL_SEND
static void scan_off_timer_cb(void *p_timer, void *args)
{
bt_mesh_scan_disable();
}
static void send_start_cb(u16_t duration, int err, void *cb_data)
{
bt_mesh_scan_disable();
}
static void send_end_cb(int err, void *cb_data)
{
bt_mesh_scan_enable();
k_timer_start(&scan_off_timer, CONFIG_SCAN_DURATION_AFTER_GENIE_MODEL_SEND);
}
#endif
/** @def genie_transport_model_send
*
* @brief send the vendor model message
*
* @param pointer to the message to be sent
*
* @return 0 for success; negative for failure
*/
static int16_t genie_transport_model_send(genie_transport_model_param_t *p_model_msg)
{
int16_t err = -1;
struct bt_mesh_model_pub *p_pub = &genie_model_pub;
struct net_buf_simple *p_msg = p_pub->msg;
struct bt_mesh_model *p_model = bt_mesh_model_find_vnd(p_model_msg->p_elem, CONFIG_MESH_VENDOR_COMPANY_ID, CONFIG_MESH_VENDOR_MODEL_SRV);
struct bt_mesh_msg_ctx ctx;
if (!p_model)
{
BT_ERR("cannot find vendor model server %p\n", p_model_msg->p_elem);
return err;
}
BT_DBG("p_model:%p, cid:0x%x, id:0x%x, retry:%d", p_model, p_model->vnd.company, p_model->vnd.id, p_model_msg->retry);
BT_DBG("tid:%02x opcode:%02x", p_model_msg->tid, p_model_msg->opid);
BT_DBG("p_model_msg->data:%p, %d, %s", p_model_msg, p_model_msg->len, bt_hex(p_model_msg->data, p_model_msg->len));
//prepare buffer
bt_mesh_model_msg_init(p_msg, BT_MESH_MODEL_OP_3(p_model_msg->opid, CONFIG_MESH_VENDOR_COMPANY_ID));
net_buf_simple_add_u8(p_msg, p_model_msg->tid);
if (p_model_msg->len)
{
net_buf_simple_add_mem(p_msg, p_model_msg->data, p_model_msg->len);
}
ctx.app_idx = bt_mesh_model_get_appkey_id(p_model_msg->p_elem, p_model);
ctx.net_idx = bt_mesh_model_get_netkey_id(p_model_msg->p_elem);
ctx.addr = p_model_msg->dst_addr;
ctx.send_ttl = GENIE_TRANSPORT_DEFAULT_TTL;
ctx.send_rel = 0;
if (ctx.addr == BT_MESH_ADDR_UNASSIGNED)
{
ctx.addr = BT_MESH_ADDR_TMALL_GENIE;
}
#ifdef CONFIG_SCAN_DURATION_AFTER_GENIE_MODEL_SEND
static struct bt_mesh_send_cb model_send_cb = {
.start = send_start_cb,
.end = send_end_cb,
};
err = bt_mesh_model_send(p_model, &ctx, p_msg, &model_send_cb, NULL);
#else
err = bt_mesh_model_send(p_model, &ctx, p_msg, NULL, NULL);
#endif
if (err)
{
BT_ERR("genie transport send fail:%d\n", err);
}
else
{
BT_DBG("genie transport send success");
}
return err;
}
/** @def genie_transport_append_mesg
*
* @brief duplicate genie_transport_model_param_t and append it to vendor model message list to be monitored
*
* @param pointer to the vendor model message to be duplicated
*
* @return 0 for success; negative for failure
*/
static int16_t genie_transport_append_mesg(genie_transport_model_param_t *p_model_msg)
{
genie_transport_node_t *p_msg_node = NULL;
BT_DBG("append msg:%p, opid:%x, retry:%d, head:%p, node:%p", p_model_msg, p_model_msg->opid, p_model_msg->retry, &send_list, &p_msg_node->node);
if (sys_dlist_node_number(&send_list) >= CONFIG_VENDOR_SEND_MSG_MAX)
{
GENIE_LOG_WARN("send list full");
return -1;
}
aos_mutex_lock(&transport_mutex, AOS_WAIT_FOREVER);
p_msg_node = genie_transport_msg_node_generate(p_model_msg);
if (!p_msg_node)
{
return -1;
}
sys_dlist_append(&send_list, &p_msg_node->node);
aos_mutex_unlock(&transport_mutex);
//Check retry timer, if timer is not started yet, start it
if (!k_timer_is_started(&retransmit_timer))
{
k_timer_start(&retransmit_timer, p_model_msg->retry_period);
}
return 0;
}
E_MESH_ERROR_TYPE genie_transport_check_tid(u16_t src_addr, uint8_t tid, uint8_t elem_id)
{
static uint8_t cur_index = 0;
uint8_t i = cur_index;
uint8_t ri = 0;
uint32_t cur_time = k_uptime_get();
uint32_t end_time = 0;
if (src_addr >= TMALL_GENIE_UADDR_START && src_addr <= TMALL_GENIE_UADDR_END)
{
src_addr = TMALL_GENIE_UADDR_START;
}
while (i < cur_index + RECV_MSG_TID_QUEUE_SIZE)
{
ri = i % RECV_MSG_TID_QUEUE_SIZE;
if ((tid_queue[ri].tid == tid) && (tid_queue[ri].addr == src_addr) && (tid_queue[ri].elemid == elem_id))
{
end_time = tid_queue[ri].time + GENIE_TRANSPORT_DEDUPLICATE_DURATION;
if (cur_time < end_time)
{
break;
}
}
i++;
}
if (i < cur_index + RECV_MSG_TID_QUEUE_SIZE)
{
return MESH_TID_REPEAT;
}
else
{
tid_queue[cur_index].tid = tid;
tid_queue[cur_index].elemid = elem_id;
tid_queue[cur_index].addr = src_addr;
tid_queue[cur_index].time = cur_time;
cur_index++;
cur_index %= RECV_MSG_TID_QUEUE_SIZE;
return MESH_SUCCESS;
}
}
void genie_transport_src_addr_set(uint16_t src_addr)
{
last_src_addr = src_addr;
}
uint16_t genie_transport_src_addr_get()
{
return last_src_addr;
}
/** @def transport_msg_node_free
*
* @brief free the vendor model message node struct's memory
*
* @param pointer to the vendor model message node to be freed
*
* @return 0 for success; negative for failure
*/
static int16_t transport_msg_node_free(genie_transport_node_t *p_node)
{
hal_free(p_node);
return 0;
}
static int transport_remove_by_tid(uint8_t tid)
{
sys_dnode_t *p_node = NULL;
sys_dnode_t *p_node_safe = NULL;
if (sys_dlist_is_empty(&send_list))
{
return -1;
}
aos_mutex_lock(&transport_mutex, AOS_WAIT_FOREVER);
SYS_DLIST_FOR_EACH_NODE_SAFE(&send_list, p_node, p_node_safe)
{
genie_transport_model_param_t *p_msg = NULL;
genie_transport_node_t *p_msg_node = NULL;
p_msg_node = CONTAINER_OF(p_node, genie_transport_node_t, node);
p_msg = &p_msg_node->msg;
BT_DBG("msg %02x", p_msg->tid);
if (p_msg->tid == tid)
{
sys_dlist_remove(p_node);
transport_msg_node_free((genie_transport_node_t *)p_node);
return 0;
}
}
aos_mutex_unlock(&transport_mutex);
return -1;
}
static uint16_t transport_get_send_timeout(uint16_t payload_len)
{
return GENIE_TRANSPORT_EACH_PDU_TIMEOUT * genie_transport_get_seg_count(payload_len);
}
int genie_transport_send_model(genie_transport_model_param_t *p_model_msg)
{
int r = -1;
if (!p_model_msg || !p_model_msg->data || p_model_msg->len == 0 || !bt_mesh_is_provisioned())
{
BT_ERR("send param err");
return r;
}
BT_DBG("opcode:0x%x, tid:%d, len:%d", p_model_msg->opid, p_model_msg->tid, p_model_msg->len);
BT_DBG("payload:%s", p_model_msg->len ? bt_hex(p_model_msg->data, p_model_msg->len) : "empty");
switch (p_model_msg->opid)
{
case VENDOR_OP_ATTR_STATUS:
case VENDOR_OP_ATTR_INDICATE:
case VENDOR_OP_ATTR_INDICATE_TG:
case VENDOR_OP_ATTR_TRANS_MSG:
case VENDOR_OP_ATTR_TRANS_INDICATE:
{
if (p_model_msg->tid == 0)
{
p_model_msg->tid = genie_transport_gen_tid();
}
/**
* no need to duplicate the following messages
* 1. retry <= 0 - the message won't want to be resent
* 2. tid device tid is [0x80, 0xBF]
* 3. opcode is not VENDOR_OP_ATTR_INDICATE/VENDOR_OP_ATTR_INDICATE_TG/VENDOR_OP_ATTR_TRANS_INDICATE
* 4. already duplicated or CONFIME/CONFIME_TG
* */
if ((p_model_msg->tid >= GENIE_TRANSPORT_TID_MIN &&
p_model_msg->tid <= GENIE_TRANSPORT_TID_MAX))
{
if (genie_transport_find_by_tid(p_model_msg->tid) != NULL)
{
transport_remove_by_tid(p_model_msg->tid); //remove old
}
if ((p_model_msg->opid != VENDOR_OP_ATTR_STATUS) && (p_model_msg->opid != VENDOR_OP_ATTR_TRANS_MSG))
{
//append for retransmit
if (p_model_msg->retry_period > 0)
{
r = genie_transport_append_mesg(p_model_msg); //append new
}
}
GENIE_LOG_INFO("SendTID(%02X)\n", p_model_msg->tid);
r = genie_transport_model_send(p_model_msg); //Send at first time
}
else
{
BT_WARN("no send");
}
}
break;
default:
{
BT_WARN("unknown opid:0x%x", p_model_msg->opid);
}
break;
}
return r;
}
int genie_transport_send_payload(genie_transport_payload_param_t *payload_param)
{
genie_transport_model_param_t transport_model_param = {0};
if (payload_param == NULL || payload_param->p_payload == NULL)
{
GENIE_LOG_ERR("invalid param");
return -1;
}
memset(&transport_model_param, 0, sizeof(genie_transport_model_param_t));
transport_model_param.opid = payload_param->opid;
transport_model_param.tid = payload_param->tid;
transport_model_param.data = payload_param->p_payload;
transport_model_param.len = payload_param->payload_len;
transport_model_param.p_elem = genie_mesh_get_primary_element();
transport_model_param.retry_period = transport_get_send_timeout(payload_param->payload_len);
transport_model_param.retry = payload_param->retry_cnt;
transport_model_param.result_cb = payload_param->result_cb;
transport_model_param.dst_addr = payload_param->dst_addr;
return genie_transport_send_model(&transport_model_param);
}
/** @def genie_transport_gen_tid
*
* @brief generate tid used in vendor model message
*
* @param NULL
*
* @return tid with range of [0x80, 0xBF]
*/
uint8_t genie_transport_gen_tid(void)
{
static uint8_t tid = GENIE_TRANSPORT_TID_MAX;
if (tid == GENIE_TRANSPORT_TID_MAX) //When bootup use rand tid
{
bt_rand(&tid, 1);
tid &= 0x3F;
}
else
{
tid = (tid + 1) & 0x3F;
}
return (tid | 0x80);
}
uint8_t genie_transport_get_seg_count(uint16_t msg_len)
{
if (msg_len <= 11) //One byte is Lower PDU header
{
return 1;
}
msg_len -= 8; //SZMIC
return (msg_len % GENIE_TRANSPORT_EACH_PDU_SIZE) ? (msg_len / GENIE_TRANSPORT_EACH_PDU_SIZE + 2) : (msg_len / GENIE_TRANSPORT_EACH_PDU_SIZE + 1);
}
bool genie_transport_tx_in_progress(void)
{
if (!sys_dlist_is_empty(&send_list))
{
return true;
}
return false;
}
/** @def retransmit_timer_cb
*
* @brief timeout handler for the retransmit_timer
*
* @param p_timer - pointer to the timer; args - pointer to send_list
*
* @return N/A
*/
static void retransmit_timer_cb(void *p_timer, void *args)
{
sys_dlist_t *p_head = (sys_dlist_t *)args;
sys_dnode_t *p_node = NULL;
sys_dnode_t *p_node_safe = NULL;
uint32_t nearest = 0;
genie_transport_node_t *p_msg_node = NULL;
genie_transport_model_param_t *p_msg = NULL;
BT_DBG("retransmit_timer timeout, p_head:%p", p_head);
/**
* 1. go through p_head
* 2. resend the no responsed messages if timeout happens and refresh timeout value
* */
aos_mutex_lock(&transport_mutex, AOS_WAIT_FOREVER);
SYS_DLIST_FOR_EACH_NODE_SAFE(p_head, p_node, p_node_safe)
{
p_msg_node = CONTAINER_OF(p_node, genie_transport_node_t, node);
nearest = p_msg_node->msg.retry_period;
p_msg = &p_msg_node->msg;
BT_DBG("msg:%p, opid:%d, left:%d\n", p_msg, p_msg->opid, p_msg_node->left_retry);
if (p_msg_node->timeout <= k_uptime_get())
{
BT_DBG("timeout - msg:%p, opid:%x, left:%d\n", p_msg, p_msg->opid, p_msg_node->left_retry);
if (p_msg_node->left_retry-- == 0)
{
GENIE_LOG_INFO("TID(%02X) timeout\n", p_msg_node->msg.tid);
if (p_msg_node->msg.result_cb)
{
p_msg_node->msg.result_cb(SEND_RESULT_TIMEOUT);
}
sys_dlist_remove(p_node);
transport_msg_node_free((genie_transport_node_t *)p_node);
break;
}
GENIE_LOG_INFO("ReTID(%02X), LR(%d)\n", p_msg->tid, p_msg_node->left_retry);
genie_transport_model_send(p_msg);
p_msg_node->timeout = k_uptime_get() + p_msg_node->msg.retry_period;
}
else
{
if (nearest > p_msg_node->timeout)
{
nearest = p_msg_node->timeout;
}
}
}
aos_mutex_unlock(&transport_mutex);
/* start new timer */
if (!sys_dlist_is_empty(p_head))
{
k_timer_start(&retransmit_timer, nearest);
BT_DBG("restart retry timer, timeout:%d\n", nearest);
}
else
{
k_timer_stop(&retransmit_timer);
BT_DBG("list empty, stop timer\n");
}
return;
}
/** @def genie_transport_ack
*
* @brief check received vendor message's tid
*
* @param pointer to send_list, tid of the received vendor model message
*
* @return 0 for success; negative for failure
*/
int genie_transport_ack(uint8_t tid)
{
sys_dnode_t *p_node = NULL;
sys_dnode_t *p_node_safe = NULL;
if (sys_dlist_is_empty(&send_list))
{
return 0;
}
/**
* go through message list and dequeue the vendor model's message and free it if received message
* s tid equals this message's tid
* */
BT_DBG("recv %02x\n", tid);
aos_mutex_lock(&transport_mutex, AOS_WAIT_FOREVER);
SYS_DLIST_FOR_EACH_NODE_SAFE(&send_list, p_node, p_node_safe)
{
genie_transport_model_param_t *p_msg = NULL;
genie_transport_node_t *p_msg_node = NULL;
p_msg_node = CONTAINER_OF(p_node, genie_transport_node_t, node);
p_msg = &p_msg_node->msg;
BT_DBG("msg %02x\n", p_msg->tid);
if (p_msg->tid == tid)
{
BT_DBG("dequeue msg:%p, opid:%x, retry:%d\n", p_msg, p_msg->opid, p_msg->retry);
if (p_msg->result_cb)
{
p_msg->result_cb(SEND_RESULT_SUCCESS);
}
sys_dlist_remove(p_node);
transport_msg_node_free((genie_transport_node_t *)p_node);
break;
}
}
aos_mutex_unlock(&transport_mutex);
return 0;
}
void genie_transport_init(void)
{
sys_dlist_init(&send_list);
k_timer_init(&retransmit_timer, retransmit_timer_cb, &send_list);
aos_mutex_new(&transport_mutex);
#ifdef CONFIG_SCAN_DURATION_AFTER_GENIE_MODEL_SEND
k_timer_init(&scan_off_timer, scan_off_timer_cb, NULL);
#endif
}
| YifuLiu/AliOS-Things | components/genie_service/core/src/genie_transport.c | C | apache-2.0 | 17,393 |
/*
* Copyright (C) 2018-2020 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
//#include <aos/aos.h>
#include <misc/printk.h>
#include <misc/byteorder.h>
#include <tinycrypt/sha256.h>
#include <tinycrypt/constants.h>
//#include <port/mesh_hal_sec.h>
#define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_MESH_DEBUG_MODEL)
#include "common/log.h"
#include "crc16.h"
#include "genie_service.h"
static genie_triple_t genie_triple;
genie_storage_status_e genie_triple_write(uint32_t *p_pid, uint8_t *p_mac, uint8_t *p_key)
{
#if 0
uint16_t triple_crc = 0;
uint16_t triple_crc_magic = GENIE_TRIPLE_CRC_MAGIC;
uint8_t data[GENIE_SIZE_TRI_TRUPLE];
memcpy(data, p_pid, GENIE_TRIPLE_PID_SIZE);
memcpy(data + GENIE_TRIPLE_PID_SIZE, p_key, GENIE_TRIPLE_KEY_SIZE);
memcpy(data + GENIE_TRIPLE_PID_SIZE + GENIE_TRIPLE_KEY_SIZE, p_mac, GENIE_TRIPLE_MAC_SIZE);
triple_crc = util_crc16_compute(data, GENIE_SIZE_TRI_TRUPLE - GENIE_TRIPLE_CRC_LEN, &triple_crc_magic);
memcpy(data + GENIE_TRIPLE_PID_SIZE + GENIE_TRIPLE_KEY_SIZE + GENIE_TRIPLE_MAC_SIZE, (unsigned char *)&triple_crc, GENIE_TRIPLE_CRC_LEN);
return genie_storage_write_reliable(GFI_MESH_TRITUPLE, data, GENIE_SIZE_TRI_TRUPLE);
#else
int32_t ret;
//uint32_t pid;
//uint8_t mac[GENIE_TRIPLE_MAC_SIZE];
//uint8_t device_secret[GENIE_TRIPLE_KEY_SIZE];
if ( p_pid == NULL || p_mac == NULL || p_key == NULL) {
GENIE_LOG_ERR("[%s]: input para error!\r\n", __func__);
return -1;
}
ret = aos_kv_set("pid", p_pid, GENIE_TRIPLE_PID_SIZE, 1);
if ( ret ){
GENIE_LOG_ERR("[%s]: set 'product_key' fail! ret = %d\r\n", __func__, ret);
return ret;
}
#if 0
printk("step 2, mac before save in kv : ");
for (int i = 0; i < 6; i++)
{
printk("%02x", p_mac[i]);
}
printk("\n");
#endif
ret = aos_kv_set("pro_mac", p_mac, GENIE_TRIPLE_MAC_SIZE + 1, 1);
if ( ret ) {
GENIE_LOG_ERR("[%s]: set 'device_name' fail! ret = %d\r\n", __func__, ret);
return ret;
}
ret = aos_kv_set("pro_secret", p_key, GENIE_TRIPLE_KEY_SIZE + 1, 1);
if ( ret ) {
GENIE_LOG_ERR("[%s]: set 'device_secret' fail! ret = %d\r\n", __func__, ret);
return ret;
}
return GENIE_STORAGE_SUCCESS;
#endif
}
genie_storage_status_e genie_triple_read(uint32_t *p_pid, uint8_t *p_mac, uint8_t *p_key)
{
#if 0
uint16_t triple_crc = 0;
uint16_t triple_read_crc = 0;
uint16_t triple_crc_magic = GENIE_TRIPLE_CRC_MAGIC;
unsigned char *p_data = NULL;
genie_storage_status_e ret;
uint8_t data[GENIE_SIZE_TRI_TRUPLE];
ret = genie_storage_read_reliable(GFI_MESH_TRITUPLE, data, GENIE_SIZE_TRI_TRUPLE);
if (GENIE_STORAGE_SUCCESS != ret)
{
GENIE_LOG_ERR("read triple fail:%d", ret);
return ret;
}
triple_crc = util_crc16_compute(data, GENIE_SIZE_TRI_TRUPLE - GENIE_TRIPLE_CRC_LEN, &triple_crc_magic);
p_data = data + GENIE_TRIPLE_PID_SIZE + GENIE_TRIPLE_KEY_SIZE + GENIE_TRIPLE_MAC_SIZE;
triple_read_crc = p_data[0] | (p_data[1] << 8);
if (triple_crc != triple_read_crc)
{
return GENIE_STORAGE_READ_FAIL;
}
memcpy(p_pid, data, GENIE_TRIPLE_PID_SIZE);
memcpy(p_key, data + GENIE_TRIPLE_PID_SIZE, GENIE_TRIPLE_KEY_SIZE);
memcpy(p_mac, data + GENIE_TRIPLE_PID_SIZE + GENIE_TRIPLE_KEY_SIZE, GENIE_TRIPLE_MAC_SIZE);
return GENIE_STORAGE_SUCCESS;
#else
int32_t ret;
uint32_t pid;
uint8_t mac[GENIE_TRIPLE_MAC_SIZE];
uint8_t device_secret[GENIE_TRIPLE_KEY_SIZE];
int pid_len = GENIE_TRIPLE_PID_SIZE;
int mac_len = GENIE_TRIPLE_MAC_SIZE + 1;
int secret_len = GENIE_TRIPLE_KEY_SIZE + 1;
ret = aos_kv_get("pid", &pid, &pid_len);
if (ret != 0) {
printf("pid in kv is valid \r\n");
}
ret = aos_kv_get("pro_mac", mac, &mac_len);
if ((ret != 0) || (mac_len != mac_len)) {
printf("mac in kv is valid ,ret = %d, mac_len = %d \r\n", ret, mac_len);
}
#if 0
printk("step 3, mac get from kv : ");
for (int i = 0; i < 6; i++)
{
printk("%02x", mac[i]);
}
printk("\n");
#endif
ret = aos_kv_get("pro_secret", device_secret, &secret_len);
if ((ret != 0) || (secret_len != secret_len)) {
printf("secret in kv is valid ,ret = %d, secret_len = %d\r\n", ret, secret_len);
}
memcpy(p_pid, &pid, GENIE_TRIPLE_PID_SIZE);
memcpy(p_key, device_secret, GENIE_TRIPLE_KEY_SIZE);
memcpy(p_mac, mac, GENIE_TRIPLE_MAC_SIZE);
#if 0
printk("step 4, in p_mac : ");
for (int i = 0; i < 6; i++)
{
printk("%02x", p_mac[i]);
}
printk("\n");
#endif
return GENIE_STORAGE_SUCCESS;
#endif
}
int8_t genie_triple_init(void)
{
genie_storage_status_e ret;
memset(&genie_triple, 0, sizeof(genie_triple_t));
ret = genie_triple_read(&genie_triple.pid, genie_triple.mac, genie_triple.key);
if (ret != GENIE_STORAGE_SUCCESS)
{
GENIE_LOG_ERR("No genie triples,please burn them");
return -1;
}
return 0;
}
genie_triple_t *genie_triple_get(void)
{
return &genie_triple;
}
uint8_t *genie_triple_get_mac(void)
{
return genie_triple.mac;
}
| YifuLiu/AliOS-Things | components/genie_service/core/src/genie_triple.c | C | apache-2.0 | 5,223 |
/*
* Copyright (C) 2018-2020 Alibaba Group Holding Limited
*/
#include <api/mesh.h>
#include <mesh/access.h>
#include "misc/dlist.h"
//nclude "access.h"
#include "genie_service.h"
#define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_MESH_DEBUG_VENDOR_MODEL)
#include "common/log.h"
/**
* vendor model publish context, alloc maximum message buffer size
* */
struct bt_mesh_model_pub genie_model_pub = {
//max = 8 seg package
.msg = NET_BUF_SIMPLE(GENIE_MODEL_MTU), // allocate maximum payload size
};
int genie_model_handle_mesg(genie_transport_model_param_t *p_msg)
{
uint8_t *p_data = NULL;
if (!p_msg)
{
BT_ERR("p_msg is null");
return -1;
}
if (p_msg->len < 2)
{
return genie_down_msg(GENIE_DOWN_MESG_VENDOR_TYPE, CONFIG_MESH_VENDOR_COMPANY_ID, p_msg);
}
if (!p_msg->data || p_msg->len == 0)
{
BT_ERR("invalid model mesg");
return -1;
}
p_data = p_msg->data;
BT_INFO("opcode:0x%x, tid:%d, len:%d", p_msg->opid, p_msg->tid, p_msg->len);
if (p_data && p_msg->len)
{
BT_INFO("payload: %s", bt_hex(p_data, p_msg->len));
}
#ifdef MESH_MODEL_VENDOR_TIMER
if (genie_time_handle_model_mesg(p_msg) != 0)
{
return 0; //This is genie time message
}
#endif
genie_down_msg(GENIE_DOWN_MESG_VENDOR_TYPE, CONFIG_MESH_VENDOR_COMPANY_ID, p_msg);
return 0;
}
/** @def genie_model_analyze
*
* @brief analyze the received message and notify genie SDK
*
* @param pointer to the received message (vendor model, context and the message buffer) and opid
*
* @return if success return 0; if fails return error no.
*/
static s16_t genie_model_analyze(struct bt_mesh_model *p_model,
struct bt_mesh_msg_ctx *p_ctx,
struct net_buf_simple *p_buf,
u8_t opid)
{
genie_transport_model_param_t msg;
sig_model_element_state_t *p_elem = NULL;
if (!p_model || !p_buf || !p_model->user_data)
return MESH_ANALYZE_ARGS_ERROR;
if (p_buf->len < 3)
{
BT_ERR("invalid buf len(%d)", p_buf->len);
return MESH_ANALYZE_SIZE_ERROR;
}
p_elem = p_model->user_data;
memset(&msg, 0, sizeof(genie_transport_model_param_t));
msg.opid = opid;
msg.tid = net_buf_simple_pull_u8(p_buf);
if (genie_transport_check_tid(p_ctx->addr, msg.tid, p_elem->element_id) != MESH_SUCCESS)
{
BT_ERR("MESH_TID_REPEAT src_addr(0x%04x) tid(0x%02x)", p_ctx->addr, msg.tid);
return MESH_TID_REPEAT;
}
genie_transport_src_addr_set(p_ctx->addr);
msg.len = p_buf->len;
BT_INFO("opcode:0x%x, tid:%d, len:%d", msg.opid, msg.tid, msg.len);
if (msg.len)
{
msg.data = (u8_t *)p_buf->data;
net_buf_simple_pull(p_buf, msg.len);
BT_DBG("payload:%s", bt_hex(msg.data, msg.len));
}
else
{
msg.data = NULL;
}
msg.p_model = p_model;
genie_event(GENIE_EVT_VENDOR_MODEL_MSG, (void *)&msg);
return 0;
}
/** @def genie_model_get
*
* @brief handle VENDOR_OP_ATTR_GET_STATUS message
*
* @param pointer to the received message (vendor model, context and the message buffer)
*
* @return N/A
*/
static void genie_model_get(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct net_buf_simple *buf)
{
genie_model_analyze(model, ctx, buf, VENDOR_OP_ATTR_GET_STATUS);
}
/** @def genie_model_set_ack
*
* @brief handle VENDOR_OP_ATTR_SET_ACK message
*
* @param pointer to the received message (vendor model, context and the message buffer)
*
* @return N/A
*/
static void genie_model_set_ack(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct net_buf_simple *buf)
{
genie_model_analyze(model, ctx, buf, VENDOR_OP_ATTR_SET_ACK);
}
/** @def genie_model_set_unack
*
* @brief handle VENDOR_OP_ATTR_SET_UNACK message
*
* @param pointer to the received message (vendor model, context and the message buffer)
*
* @return N/A
*/
static void genie_model_set_unack(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct net_buf_simple *buf)
{
genie_model_analyze(model, ctx, buf, VENDOR_OP_ATTR_SET_UNACK);
}
/** @def genie_model_confirm
*
* @brief handle VENDOR_OP_ATTR_CONFIME message
*
* @param pointer to the received message (vendor model, context and the message buffer)
*
* @return N/A
*/
static void genie_model_confirm(struct bt_mesh_model *p_model,
struct bt_mesh_msg_ctx *ctx,
struct net_buf_simple *buf)
{
u8_t tid = 0x0;
genie_transport_model_param_t msg;
if (!p_model || !p_model->user_data)
{
GENIE_LOG_ERR("param err");
return;
}
if (buf->len != 1)
{
BT_ERR("invalid buf len(%d)", buf->len);
return;
}
tid = net_buf_simple_pull_u8(buf);
genie_transport_ack(tid);
memset(&msg, 0, sizeof(genie_transport_model_param_t));
msg.opid = VENDOR_OP_ATTR_CONFIME;
msg.tid = tid;
msg.len = 0;
msg.data = NULL;
msg.p_model = p_model;
genie_event(GENIE_EVT_VENDOR_MODEL_MSG, (void *)&msg);
}
static void genie_model_get_indicate(struct bt_mesh_model *p_model,
struct bt_mesh_msg_ctx *ctx,
struct net_buf_simple *buf)
{
u8_t tid = 0x0;
genie_transport_model_param_t msg;
struct net_buf_simple *p_msg = NET_BUF_SIMPLE(3 + 1 + 4); //opcode + tid + TransMIC
if (!p_model || !p_model->user_data)
{
GENIE_LOG_ERR("param err");
return;
}
tid = net_buf_simple_pull_u8(buf);
genie_transport_ack(tid);
bt_mesh_model_msg_init(p_msg, BT_MESH_MODEL_OP_3(VENDOR_OP_ATTR_CONFIME, CONFIG_MESH_VENDOR_COMPANY_ID));
net_buf_simple_add_u8(p_msg, tid);
ctx->send_ttl = GENIE_TRANSPORT_DEFAULT_TTL;
if (bt_mesh_model_send(p_model, ctx, p_msg, NULL, NULL))
{
BT_ERR("send comfirm fail");
}
memset(&msg, 0, sizeof(genie_transport_model_param_t));
msg.opid = VENDOR_OP_ATTR_INDICATE;
msg.tid = tid;
msg.len = 0;
msg.data = NULL;
genie_transport_src_addr_set(ctx->addr);
msg.p_model = p_model;
genie_event(GENIE_EVT_VENDOR_MODEL_MSG, (void *)&msg);
}
/** @def genie_model_confirm_tg
*
* @brief handle VENDOR_OP_ATTR_CONFIME_TG message
*
* @param pointer to the received message (vendor model, context and the message buffer)
*
* @return N/A
*/
static void genie_model_confirm_tg(struct bt_mesh_model *p_model,
struct bt_mesh_msg_ctx *ctx,
struct net_buf_simple *buf)
{
u8_t tid = 0x0;
genie_transport_model_param_t msg;
if (!p_model || !p_model->user_data)
{
GENIE_LOG_ERR("param err");
return;
}
tid = net_buf_simple_pull_u8(buf);
genie_transport_ack(tid);
memset(&msg, 0, sizeof(genie_transport_model_param_t));
msg.opid = VENDOR_OP_ATTR_CONFIME_TG;
msg.tid = tid;
msg.len = buf->len;
if (msg.len)
{
msg.data = (u8_t *)buf->data;
net_buf_simple_pull(buf, msg.len);
BT_DBG("payload:%s", bt_hex(msg.data, msg.len));
}
else
{
msg.data = NULL;
}
msg.p_model = p_model;
genie_event(GENIE_EVT_VENDOR_MODEL_MSG, (void *)&msg);
}
/** @def genie_model_transparent
*
* @brief handle VENDOR_OP_ATTR_TRANS_MSG message
*
* @param pointer to the received message (vendor model, context and the message buffer)
*
* @return N/A
*/
static void genie_model_transparent(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct net_buf_simple *buf)
{
genie_model_analyze(model, ctx, buf, VENDOR_OP_ATTR_TRANS_MSG);
}
/** @def genie_model_transparent_ack
*
* @brief handle VENDOR_OP_ATTR_TRANS_ACK message
*
* @param pointer to the received message (vendor model, context and the message buffer)
*
* @return N/A
*/
static void genie_model_transparent_ack(struct bt_mesh_model *p_model,
struct bt_mesh_msg_ctx *ctx,
struct net_buf_simple *buf)
{
u8_t tid = 0x0;
genie_transport_model_param_t msg;
if (!p_model || !p_model->user_data)
{
GENIE_LOG_ERR("param err");
return;
}
if (buf->len != 1)
{
BT_ERR("invalid buf len(%d)", buf->len);
return;
}
tid = net_buf_simple_pull_u8(buf);
genie_transport_ack(tid);
memset(&msg, 0, sizeof(genie_transport_model_param_t));
msg.opid = VENDOR_OP_ATTR_TRANS_ACK;
msg.tid = tid;
msg.len = 0;
msg.data = NULL;
msg.p_model = p_model;
genie_event(GENIE_EVT_VENDOR_MODEL_MSG, (void *)&msg);
}
/** @def ggenie_model_alibaba_op
*
* @brief vendor model operations struct
*
*/
const struct bt_mesh_model_op genie_model_op[VENDOR_MODEL_OPC_NUM] = {
{BT_MESH_MODEL_OP_3(VENDOR_OP_ATTR_GET_STATUS, CONFIG_MESH_VENDOR_COMPANY_ID), 2, genie_model_get},
{BT_MESH_MODEL_OP_3(VENDOR_OP_ATTR_SET_ACK, CONFIG_MESH_VENDOR_COMPANY_ID), 2, genie_model_set_ack},
{BT_MESH_MODEL_OP_3(VENDOR_OP_ATTR_SET_UNACK, CONFIG_MESH_VENDOR_COMPANY_ID), 2, genie_model_set_unack},
{BT_MESH_MODEL_OP_3(VENDOR_OP_ATTR_INDICATE, CONFIG_MESH_VENDOR_COMPANY_ID), 1, genie_model_get_indicate},
{BT_MESH_MODEL_OP_3(VENDOR_OP_ATTR_CONFIME, CONFIG_MESH_VENDOR_COMPANY_ID), 1, genie_model_confirm},
{BT_MESH_MODEL_OP_3(VENDOR_OP_ATTR_CONFIME_TG, CONFIG_MESH_VENDOR_COMPANY_ID), 1, genie_model_confirm_tg},
{BT_MESH_MODEL_OP_3(VENDOR_OP_ATTR_TRANS_MSG, CONFIG_MESH_VENDOR_COMPANY_ID), 1, genie_model_transparent},
{BT_MESH_MODEL_OP_3(VENDOR_OP_ATTR_TRANS_ACK, CONFIG_MESH_VENDOR_COMPANY_ID), 1, genie_model_transparent_ack},
BT_MESH_MODEL_OP_END,
};
| YifuLiu/AliOS-Things | components/genie_service/core/src/genie_vendor_model.c | C | apache-2.0 | 10,107 |
/*
* Copyright (C) 2019-2020 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include "genie_service.h"
#ifndef GENIE_SDK_VERSION
#define GENIE_SDK_VERSION "1.3.2"
#endif
uint32_t genie_version_appver_get(void)
{
return PROJECT_SW_VERSION;
}
int genie_version_appver_string_get(char *version, int len)
{
return snprintf(version, len, "%d.%d.%d", (PROJECT_SW_VERSION >> 16 & 0xFF), (PROJECT_SW_VERSION >> 8 & 0xFF), PROJECT_SW_VERSION & 0xFF);
}
const char *genie_version_sysver_get(void)
{
return GENIE_SDK_VERSION;
}
| YifuLiu/AliOS-Things | components/genie_service/core/src/genie_version.c | C | apache-2.0 | 542 |
/*
* Copyright (C) 2018-2020 Alibaba Group Holding Limited
*/
//
#include <api/mesh.h>
#include "genie_service.h"
#define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_MESH_DEBUG_MODEL)
#include "common/log.h"
#ifdef CONFIG_MESH_MODEL_GEN_ONOFF_SRV
u16_t sig_model_generic_onoff_bind_ops(sig_model_element_state_t *p_elem)
{
#ifdef CONFIG_MESH_MODEL_LIGHTNESS_SRV
sig_model_lightness_update_by_onoff(p_elem);
#endif
#ifdef CONFIG_MESH_MODEL_CTL_SRV
sig_model_light_ctl_update_by_onoff(p_elem);
#endif
return 0;
}
#endif
#ifdef CONFIG_MESH_MODEL_LIGHTNESS_SRV
u16_t sig_model_generic_lightness_bind_ops(sig_model_element_state_t *p_elem, u8_t type)
{
#ifdef CONFIG_MESH_MODEL_GEN_ONOFF_SRV
sig_model_onoff_update_by_lightness(p_elem, type);
#endif
return 0;
}
#endif
#ifdef CONFIG_MESH_MODEL_CTL_SRV
u16_t sig_model_generic_color_temperature_bind_ops(sig_model_element_state_t *p_elem)
{
#ifdef CONFIG_MESH_MODEL_GEN_ONOFF_SRV
sig_model_onoff_update_by_color_temperature(p_elem);
#endif
return 0;
}
#endif
| YifuLiu/AliOS-Things | components/genie_service/core/src/sig_models/sig_model_bind_ops.c | C | apache-2.0 | 1,034 |
/*
* Copyright (C) 2019-2020 Alibaba Group Holding Limited
*/
#include "common/log.h"
#include "mesh.h"
#include <atomic.h>
#include "genie_service.h"
static ATOMIC_DEFINE(indicate_flags, SIG_MODEL_INDICATE_FLAGS);
static sig_model_event_e sig_model_event_handle_delay_start(sig_model_element_state_t *p_elem)
{
#ifdef CONFIG_MESH_MODEL_TRANS
sig_model_transition_timer_stop(p_elem);
#endif
k_timer_start(&p_elem->state.delay_timer, p_elem->state.delay * 5);
return SIG_MODEL_EVT_NONE;
}
static sig_model_event_e sig_model_event_handle_delay_end(sig_model_element_state_t *p_elem)
{
#ifdef CONFIG_MESH_MODEL_TRANS
bt_u32_t cur_time = k_uptime_get();
#endif
p_elem->state.delay = 0;
#ifdef CONFIG_MESH_MODEL_TRANS
if (p_elem->state.trans == 0 || cur_time >= p_elem->state.trans_end_time)
{
sig_model_transition_state_reset(p_elem);
return SIG_MODEL_EVT_ACTION_DONE;
}
else
{
return SIG_MODEL_EVT_TRANS_START;
}
#else
return SIG_MODEL_EVT_ACTION_DONE;
#endif
}
#ifdef CONFIG_MESH_MODEL_TRANS
static sig_model_event_e sig_model_event_handle_trans_start(sig_model_element_state_t *p_elem)
{
bt_u32_t cur_time = k_uptime_get();
sig_model_transition_timer_stop(p_elem);
//check time
if (cur_time >= p_elem->state.trans_end_time - SIG_MODEL_TRANSITION_INTERVAL)
{
return SIG_MODEL_EVT_TRANS_END;
}
else
{
//start cycle
k_timer_start(&p_elem->state.trans_timer, SIG_MODEL_TRANSITION_INTERVAL);
BT_DBG("start trans %p", &p_elem->state.trans_timer);
return SIG_MODEL_EVT_NONE;
}
}
static sig_model_event_e sig_model_event_handle_trans_cycle(sig_model_element_state_t *p_elem)
{
if (sig_model_transition_update(p_elem) == 0)
{
p_elem->state.trans = 0;
}
return SIG_MODEL_EVT_NONE;
}
static sig_model_event_e sig_model_event_handle_trans_end(sig_model_element_state_t *p_elem)
{
//clear paras
sig_model_transition_state_reset(p_elem);
//action done
return SIG_MODEL_EVT_ACTION_DONE;
}
#endif
static sig_model_event_e sig_model_event_handle_analyze_msg(sig_model_element_state_t *p_elem)
{
#ifdef CONFIG_MESH_MODEL_TRANS
if (p_elem->state.trans || p_elem->state.delay)
{
if (p_elem->state.delay)
{
return SIG_MODEL_EVT_DELAY_START;
}
else
{
return SIG_MODEL_EVT_TRANS_START;
}
}
#endif
return SIG_MODEL_EVT_ACTION_DONE;
}
static sig_model_event_e sig_model_handle_action_done(sig_model_element_state_t *p_elem)
{
#ifdef CONFIG_MESH_MODEL_GEN_ONOFF_SRV
BT_DBG("onoff cur(%d) tar(%d)", p_elem->state.onoff[TYPE_PRESENT], p_elem->state.onoff[TYPE_TARGET]);
if (p_elem->state.onoff[TYPE_PRESENT] != p_elem->state.onoff[TYPE_TARGET])
{
p_elem->state.onoff[TYPE_PRESENT] = p_elem->state.onoff[TYPE_TARGET];
atomic_set_bit(indicate_flags, SIG_MODEL_INDICATE_GEN_ONOFF);
}
#endif
#ifdef CONFIG_MESH_MODEL_LIGHTNESS_SRV
BT_DBG("lightness cur(%04x) tar(%04x)", p_elem->state.lightness[TYPE_PRESENT], p_elem->state.lightness[TYPE_TARGET]);
if (p_elem->state.lightness[TYPE_PRESENT] != p_elem->state.lightness[TYPE_TARGET])
{
p_elem->state.lightness[TYPE_PRESENT] = p_elem->state.lightness[TYPE_TARGET];
atomic_set_bit(indicate_flags, SIG_MODEL_INDICATE_GEN_LIGHTNESS);
}
#endif
#ifdef CONFIG_MESH_MODEL_CTL_SRV
BT_DBG("color_temperature cur(%04x) tar(%04x)", p_elem->state.color_temperature[TYPE_PRESENT], p_elem->state.color_temperature[TYPE_TARGET]);
if (p_elem->state.color_temperature[TYPE_PRESENT] != p_elem->state.color_temperature[TYPE_TARGET])
{
p_elem->state.color_temperature[TYPE_PRESENT] = p_elem->state.color_temperature[TYPE_TARGET];
atomic_set_bit(indicate_flags, SIG_MODEL_INDICATE_GEN_CTL);
}
#endif
#ifdef CONFIG_MESH_MODEL_SCENE_SRV
BT_DBG("scene cur(%04x) tar(%04x)", p_elem->state.scene[TYPE_PRESENT], p_elem->state.scene[TYPE_TARGET]);
if (p_elem->state.scene[TYPE_PRESENT] != p_elem->state.scene[TYPE_TARGET])
{
p_elem->state.scene[TYPE_PRESENT] = p_elem->state.scene[TYPE_TARGET];
atomic_set_bit(indicate_flags, SIG_MODEL_INDICATE_GEN_SCENE);
}
#endif
if (bt_mesh_is_provisioned())
{
return SIG_MODEL_EVT_INDICATE;
}
return SIG_MODEL_EVT_NONE;
}
static sig_model_event_e sig_model_handle_indicate(sig_model_element_state_t *p_elem)
{
uint8_t payload[SIG_MODEL_INDICATE_PAYLOAD_MAX_LEN];
uint8_t payload_len = 0;
genie_transport_model_param_t transport_model_param = {0};
if (p_elem == NULL)
{
return SIG_MODEL_EVT_NONE;
}
#ifdef CONFIG_MESH_MODEL_GEN_ONOFF_SRV
if (atomic_test_and_clear_bit(indicate_flags, SIG_MODEL_INDICATE_GEN_ONOFF))
{
payload[payload_len++] = ATTR_TYPE_GENERIC_ONOFF & 0xff;
payload[payload_len++] = (ATTR_TYPE_GENERIC_ONOFF >> 8) & 0xff;
payload[payload_len++] = p_elem->state.onoff[TYPE_PRESENT];
}
#endif
#ifdef CONFIG_MESH_MODEL_LIGHTNESS_SRV
if (atomic_test_and_clear_bit(indicate_flags, SIG_MODEL_INDICATE_GEN_LIGHTNESS))
{
payload[payload_len++] = ATTR_TYPE_LIGHTNESS & 0xff;
payload[payload_len++] = (ATTR_TYPE_LIGHTNESS >> 8) & 0xff;
payload[payload_len++] = p_elem->state.lightness[TYPE_PRESENT] & 0xff;
payload[payload_len++] = (p_elem->state.lightness[TYPE_PRESENT] >> 8) & 0xff;
}
#endif
#ifdef CONFIG_MESH_MODEL_CTL_SRV
if (atomic_test_and_clear_bit(indicate_flags, SIG_MODEL_INDICATE_GEN_CTL))
{
payload[payload_len++] = ATTR_TYPE_COLOR_TEMPERATURE & 0xff;
payload[payload_len++] = (ATTR_TYPE_COLOR_TEMPERATURE >> 8) & 0xff;
payload[payload_len++] = p_elem->state.color_temperature[TYPE_PRESENT] & 0xff;
payload[payload_len++] = (p_elem->state.color_temperature[TYPE_PRESENT] >> 8) & 0xff;
}
#endif
#ifdef CONFIG_MESH_MODEL_SCENE_SRV
if (atomic_test_and_clear_bit(indicate_flags, SIG_MODEL_INDICATE_GEN_SCENE))
{
payload[payload_len++] = ATTR_TYPE_SENCE & 0xff;
payload[payload_len++] = (ATTR_TYPE_SENCE >> 8) & 0xff;
payload[payload_len++] = p_elem->state.scene[TYPE_PRESENT] & 0xff;
payload[payload_len++] = (p_elem->state.scene[TYPE_PRESENT] >> 8) & 0xff;
}
#endif
if (payload_len > 0)
{
memset(&transport_model_param, 0, sizeof(genie_transport_model_param_t));
transport_model_param.opid = VENDOR_OP_ATTR_INDICATE;
transport_model_param.data = payload;
transport_model_param.len = MIN(SIG_MODEL_INDICATE_PAYLOAD_MAX_LEN, payload_len);
transport_model_param.p_elem = bt_mesh_elem_find_by_id(p_elem->element_id);
transport_model_param.retry_period = GENIE_TRANSPORT_EACH_PDU_TIMEOUT * genie_transport_get_seg_count(transport_model_param.len);
transport_model_param.retry = GENIE_TRANSPORT_DEFAULT_RETRY_COUNT;
genie_transport_send_model(&transport_model_param);
}
return SIG_MODEL_EVT_NONE;
}
void sig_model_event_set_indicate(int indicate)
{
atomic_set_bit(indicate_flags, indicate);
}
void sig_model_event(sig_model_event_e event, void *p_arg)
{
sig_model_event_e next_event = SIG_MODEL_EVT_NONE;
if (event != SIG_MODEL_EVT_NONE)
{
#ifdef CONFIG_MESH_MODEL_TRANS
if (event != SIG_MODEL_EVT_TRANS_CYCLE)
{
GENIE_LOG_INFO("SigE:%d\r\n", event);
}
#else
GENIE_LOG_INFO("SigE:%d\r\n", event);
#endif
}
switch (event)
{
case SIG_MODEL_EVT_INDICATE:
{
next_event = sig_model_handle_indicate((sig_model_element_state_t *)p_arg);
}
break;
case SIG_MODEL_EVT_ACTION_DONE:
{
next_event = sig_model_handle_action_done((sig_model_element_state_t *)p_arg);
}
break;
case SIG_MODEL_EVT_ANALYZE_MSG:
{
next_event = sig_model_event_handle_analyze_msg((sig_model_element_state_t *)p_arg);
}
break;
case SIG_MODEL_EVT_DELAY_START:
{
next_event = sig_model_event_handle_delay_start((sig_model_element_state_t *)p_arg);
}
break;
case SIG_MODEL_EVT_DELAY_END:
{
next_event = sig_model_event_handle_delay_end((sig_model_element_state_t *)p_arg);
}
break;
#ifdef CONFIG_MESH_MODEL_TRANS
case SIG_MODEL_EVT_TRANS_START:
{
next_event = sig_model_event_handle_trans_start((sig_model_element_state_t *)p_arg);
}
break;
case SIG_MODEL_EVT_TRANS_CYCLE:
{
next_event = sig_model_event_handle_trans_cycle((sig_model_element_state_t *)p_arg);
}
break;
case SIG_MODEL_EVT_TRANS_END:
{
next_event = sig_model_event_handle_trans_end((sig_model_element_state_t *)p_arg);
}
break;
#endif
case SIG_MODEL_EVT_GENERIC_MESG:
{
sig_model_msg *p_msg = (sig_model_msg *)p_arg;
genie_down_msg(GENIE_DOWN_MESG_SIG_TYPE, p_msg->opcode, p_arg);
}
break;
default:
break;
}
if (next_event != SIG_MODEL_EVT_NONE)
{
sig_model_event(next_event, p_arg);
}
if (event == SIG_MODEL_EVT_ACTION_DONE)
{
genie_event(GENIE_EVT_USER_ACTION_DONE, p_arg);
}
#ifdef CONFIG_MESH_MODEL_TRANS
if (event == SIG_MODEL_EVT_TRANS_CYCLE)
{
genie_event(GENIE_EVT_USER_TRANS_CYCLE, p_arg);
}
#endif
}
| YifuLiu/AliOS-Things | components/genie_service/core/src/sig_models/sig_model_event.c | C | apache-2.0 | 9,390 |
/*
* Copyright (C) 2018-2020 Alibaba Group Holding Limited
*/
#include <api/mesh.h>
#include <mesh.h>
#define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_MESH_DEBUG_MODEL)
#include "common/log.h"
#include "genie_service.h"
struct bt_mesh_model_pub g_ctl_srv_pub = {
};
#if CONFIG_MESH_MODEL_CTL_SRV //light ctl server
static void _ctl_prepare_buf(struct bt_mesh_model *p_model, struct net_buf_simple *p_msg, bool is_ack)
{
sig_model_state_t *p_state = &((sig_model_element_state_t *)p_model->user_data)->state;
u8_t remain_time_byte = 0;
BT_DBG("color_temperature cur(0x%04x) tar(0x%04x)", p_state->color_temperature[TYPE_PRESENT], p_state->color_temperature[TYPE_TARGET]);
#ifdef CONFIG_MESH_MODEL_TRANS
remain_time_byte = sig_model_transition_get_remain_time_byte(p_state, is_ack);
BT_DBG("remain(0x%02x)", remain_time_byte);
#endif
//prepear buff
bt_mesh_model_msg_init(p_msg, OP_GENERIC_LIGHT_CTL_STATUS);
if (is_ack && remain_time_byte == 0)
{
net_buf_simple_add_le16(p_msg, p_state->lightness[TYPE_TARGET]);
net_buf_simple_add_le16(p_msg, p_state->color_temperature[TYPE_TARGET]);
}
else
{
net_buf_simple_add_le16(p_msg, p_state->lightness[TYPE_PRESENT]);
net_buf_simple_add_le16(p_msg, p_state->color_temperature[TYPE_PRESENT]);
#ifdef CONFIG_MESH_MODEL_TRANS
if (remain_time_byte)
{
net_buf_simple_add_le16(p_msg, p_state->lightness[TYPE_TARGET]);
net_buf_simple_add_le16(p_msg, p_state->color_temperature[TYPE_TARGET]);
net_buf_simple_add_u8(p_msg, remain_time_byte);
}
#endif
}
}
static void _ctl_status(struct bt_mesh_model *p_model,
struct bt_mesh_msg_ctx *p_ctx, bool is_ack)
{
struct net_buf_simple *p_msg = NET_BUF_SIMPLE(2 + 9 + 4);
BT_DBG("addr(0x%04x)", bt_mesh_model_elem(p_model)->addr);
_ctl_prepare_buf(p_model, p_msg, is_ack);
p_ctx->send_ttl = GENIE_TRANSPORT_DEFAULT_TTL;
if (bt_mesh_model_send(p_model, p_ctx, p_msg, NULL, NULL))
{
BT_ERR("Unable to send ctl Status");
}
BT_DBG("Success!!!");
}
static u8_t _ctl_analyze(struct bt_mesh_model *p_model,
u16_t src_addr, struct net_buf_simple *p_buf)
{
u16_t lightness = 0;
u16_t color_temperature = 0;
u16_t uv = 0;
u8_t tid = 0;
#ifdef CONFIG_MESH_MODEL_TRANS
u8_t trans = 0;
u8_t delay = 0;
#endif
sig_model_element_state_t *p_elem = NULL;
if (!p_model || !p_buf)
return MESH_ANALYZE_ARGS_ERROR;
p_elem = p_model->user_data;
if (p_buf->len != 7 && p_buf->len != 9)
{
BT_ERR("MESH_ANALYZE_SIZE_ERROR p_buf->len(%d)", p_buf->len);
return MESH_ANALYZE_SIZE_ERROR;
}
//get message info
lightness = net_buf_simple_pull_le16(p_buf);
color_temperature = net_buf_simple_pull_le16(p_buf);
uv = net_buf_simple_pull_le16(p_buf);
tid = net_buf_simple_pull_u8(p_buf);
GENIE_LOG_INFO("uv:%d lightness:%d", uv, lightness);
(void)uv;
(void)lightness;
#ifdef CONFIG_MESH_MODEL_TRANS
if (p_buf->len)
{
trans = net_buf_simple_pull_u8(p_buf);
delay = net_buf_simple_pull_u8(p_buf);
}
else
{
trans = 0;
delay = 0;
}
if ((trans & 0x3F) == 0x3F)
{
BT_ERR("MESH_SET_TRANSTION_ERROR");
return MESH_SET_TRANSTION_ERROR;
}
#endif
//check color_temperature
if (color_temperature < COLOR_TEMPERATURE_MIN || color_temperature > COLOR_TEMPERATURE_MAX)
{
BT_ERR("MESH_ANALYZE_ARGS_ERROR color_temperature(0x%04x)", color_temperature);
return MESH_ANALYZE_ARGS_ERROR;
}
if (genie_transport_check_tid(src_addr, tid, p_elem->element_id) != MESH_SUCCESS)
{
BT_ERR("MESH_TID_REPEAT src_addr(0x%04x) tid(0x%02x)", src_addr, tid);
return MESH_TID_REPEAT;
}
p_elem->state.color_temperature[TYPE_TARGET] = color_temperature;
p_elem->powerup.last_color_temperature = p_elem->state.color_temperature[TYPE_TARGET];
BT_DBG("color_temperature cur(%04x) tar(%04x)", p_elem->state.color_temperature[TYPE_PRESENT], p_elem->state.color_temperature[TYPE_TARGET]);
#ifdef CONFIG_MESH_MODEL_TRANS
p_elem->state.trans = trans;
p_elem->state.delay = delay;
if (p_elem->state.trans)
{
p_elem->state.trans_start_time = k_uptime_get() + p_elem->state.delay * 5; // delay is in 5 millisecond steps
p_elem->state.trans_end_time = p_elem->state.trans_start_time + sig_model_transition_get_transition_time(p_elem->state.trans);
}
BT_DBG("trans(0x%02x) delay(0x%02x)", p_elem->state.trans, p_elem->state.delay);
#endif
//only check color_temperature when ali simaple model
if (p_elem->state.color_temperature[TYPE_PRESENT] != p_elem->state.color_temperature[TYPE_TARGET])
{
//only bind color_temperature when ali_simple_model is enable
sig_model_event_set_indicate(SIG_MODEL_INDICATE_GEN_CTL);
sig_model_generic_color_temperature_bind_ops(p_elem);
}
return MESH_SUCCESS;
}
static void _ctl_get(struct bt_mesh_model *p_model,
struct bt_mesh_msg_ctx *p_ctx,
struct net_buf_simple *p_buf)
{
BT_DBG("");
sig_model_msg msg;
sig_model_element_state_t *p_elem_state = NULL;
if (!p_model || !p_model->user_data)
{
GENIE_LOG_ERR("param err");
return;
}
memset(&msg, 0, sizeof(sig_model_msg));
msg.opcode = OP_GENERIC_LIGHT_CTL_GET;
if (p_buf != NULL)
{
msg.len = p_buf->len;
msg.data = (u8_t *)p_buf->data;
}
genie_transport_src_addr_set(p_ctx->addr);
p_elem_state = (sig_model_element_state_t *)p_model->user_data;
msg.element_id = p_elem_state->element_id;
sig_model_event(SIG_MODEL_EVT_GENERIC_MESG, (void *)&msg);
_ctl_status(p_model, p_ctx, 0);
}
static void _ctl_set(struct bt_mesh_model *p_model,
struct bt_mesh_msg_ctx *p_ctx,
struct net_buf_simple *p_buf)
{
E_MESH_ERROR_TYPE ret = 0;
sig_model_msg msg;
sig_model_element_state_t *p_elem_state = NULL;
if (!p_model || !p_model->user_data)
{
GENIE_LOG_ERR("param err");
return;
}
memset(&msg, 0, sizeof(sig_model_msg));
msg.opcode = OP_GENERIC_LIGHT_CTL_SET;
if (p_buf != NULL)
{
msg.len = p_buf->len;
msg.data = (u8_t *)p_buf->data;
}
genie_transport_src_addr_set(p_ctx->addr);
p_elem_state = (sig_model_element_state_t *)p_model->user_data;
msg.element_id = p_elem_state->element_id;
sig_model_event(SIG_MODEL_EVT_GENERIC_MESG, (void *)&msg);
ret = _ctl_analyze(p_model, p_ctx->addr, p_buf);
BT_DBG("ret %d", ret);
if (ret == MESH_SUCCESS || ret == MESH_TID_REPEAT)
{
_ctl_status(p_model, p_ctx, 1);
if (ret == MESH_SUCCESS)
{
sig_model_event(SIG_MODEL_EVT_ANALYZE_MSG, (sig_model_element_state_t *)p_model->user_data);
}
}
}
static void _ctl_set_unack(struct bt_mesh_model *p_model,
struct bt_mesh_msg_ctx *p_ctx,
struct net_buf_simple *p_buf)
{
BT_DBG("");
E_MESH_ERROR_TYPE ret = 0;
sig_model_msg msg;
sig_model_element_state_t *p_elem_state = NULL;
if (!p_model || !p_model->user_data)
{
GENIE_LOG_ERR("param err");
return;
}
memset(&msg, 0, sizeof(sig_model_msg));
msg.opcode = OP_GENERIC_LIGHT_CTL_SET_UNACK;
if (p_buf != NULL)
{
msg.len = p_buf->len;
msg.data = (u8_t *)p_buf->data;
}
genie_transport_src_addr_set(p_ctx->addr);
p_elem_state = (sig_model_element_state_t *)p_model->user_data;
msg.element_id = p_elem_state->element_id;
sig_model_event(SIG_MODEL_EVT_GENERIC_MESG, (void *)&msg);
ret = _ctl_analyze(p_model, p_ctx->addr, p_buf);
if (ret == MESH_SUCCESS)
{
sig_model_event(SIG_MODEL_EVT_ANALYZE_MSG, (sig_model_element_state_t *)p_model->user_data);
}
}
const struct bt_mesh_model_op g_ctl_srv_op[LIGHT_CTL_OPCODE_NUM] = {
{OP_GENERIC_LIGHT_CTL_GET, 0, _ctl_get},
{OP_GENERIC_LIGHT_CTL_SET, 7, _ctl_set},
{OP_GENERIC_LIGHT_CTL_SET_UNACK, 7, _ctl_set_unack},
BT_MESH_MODEL_OP_END,
};
#endif
void sig_model_light_ctl_update_by_onoff(sig_model_element_state_t *p_elem)
{
sig_model_state_t *p_state = &p_elem->state;
BT_DBG("onoff cur(%d) tar(%d)", p_state->onoff[TYPE_PRESENT], p_state->onoff[TYPE_TARGET]);
#ifdef CONFIG_MESH_MODEL_GEN_ONOFF_SRV
if (p_state->onoff[TYPE_PRESENT] == 0 && p_state->onoff[TYPE_TARGET] == 1)
{
//turn on, check temperature
BT_DBG("color_temperature cur(%d) tar(%d)", p_state->color_temperature[TYPE_PRESENT], p_state->color_temperature[TYPE_TARGET]);
if (p_state->color_temperature[TYPE_PRESENT] != p_state->color_temperature[TYPE_TARGET])
{
if (p_elem->powerup.last_color_temperature)
{
p_state->color_temperature[TYPE_TARGET] = p_elem->powerup.last_color_temperature;
}
else
{
p_state->color_temperature[TYPE_TARGET] = COLOR_TEMPERATURE_DEFAULT;
}
sig_model_event_set_indicate(SIG_MODEL_INDICATE_GEN_CTL);
}
}
#endif
BT_DBG("color_temperature cur(%04x) tar(%04x)", p_state->color_temperature[TYPE_PRESENT], p_state->color_temperature[TYPE_TARGET]);
}
| YifuLiu/AliOS-Things | components/genie_service/core/src/sig_models/sig_model_light_ctl_srv.c | C | apache-2.0 | 9,491 |
/*
* Copyright (C) 2018-2020 Alibaba Group Holding Limited
*/
#include <api/mesh.h>
#include "sig_models/sig_model.h"
#define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_MESH_DEBUG_MODEL)
#include "common/log.h"
#include "access.h"
struct bt_mesh_model_pub g_lightness_pub = {
.msg = NET_BUF_SIMPLE(2 + 5 + 4),
};
static void _lightness_prepare_buf(struct bt_mesh_model *p_model, struct net_buf_simple *p_msg, bool is_ack)
{
sig_model_state_t *p_state = &((sig_model_element_state_t *)p_model->user_data)->state;
u8_t remain_time_byte = 0;
BT_DBG("lightness cur(0x%04x) tar(0x%04x)", p_state->lightness[TYPE_PRESENT], p_state->lightness[TYPE_TARGET]);
#ifdef CONFIG_MESH_MODEL_TRANS
remain_time_byte = sig_model_transition_get_remain_time_byte(p_state, is_ack);
BT_DBG("remain(0x%02x)", remain_time_byte);
#endif
//prepear buff
bt_mesh_model_msg_init(p_msg, OP_GENERIC_LIGHTNESS_STATUS);
if (is_ack && remain_time_byte == 0)
{
net_buf_simple_add_le16(p_msg, p_state->lightness[TYPE_TARGET]);
}
else
{
net_buf_simple_add_le16(p_msg, p_state->lightness[TYPE_PRESENT]);
#ifdef CONFIG_MESH_MODEL_TRANS
if (remain_time_byte)
{
net_buf_simple_add_le16(p_msg, p_state->lightness[TYPE_TARGET]);
net_buf_simple_add_u8(p_msg, remain_time_byte);
}
#endif
}
}
static void _lightness_status(struct bt_mesh_model *p_model,
struct bt_mesh_msg_ctx *p_ctx, bool is_ack)
{
struct net_buf_simple *p_msg = NET_BUF_SIMPLE(2 + 5 + 4);
BT_DBG("addr(0x%04x)", bt_mesh_model_elem(p_model)->addr);
_lightness_prepare_buf(p_model, p_msg, is_ack);
p_ctx->send_ttl = GENIE_TRANSPORT_DEFAULT_TTL;
if (bt_mesh_model_send(p_model, p_ctx, p_msg, NULL, NULL))
{
BT_ERR("Unable to send lightness Status");
}
BT_DBG("Success!!!");
}
static E_MESH_ERROR_TYPE _lightness_analyze(struct bt_mesh_model *p_model,
u16_t src_addr, struct net_buf_simple *p_buf)
{
s16_t lightness = 0;
u8_t tid = 0;
#ifdef CONFIG_MESH_MODEL_TRANS
u8_t trans = 0;
u8_t delay = 0;
#endif
sig_model_element_state_t *p_elem = NULL;
if (!p_model || !p_buf)
return MESH_ANALYZE_ARGS_ERROR;
p_elem = p_model->user_data;
if (p_buf->len != 3 && p_buf->len != 5)
{
BT_ERR("MESH_ANALYZE_SIZE_ERROR buf->len(%d)", p_buf->len);
return MESH_ANALYZE_SIZE_ERROR;
}
lightness = (s16_t)net_buf_simple_pull_le16(p_buf);
tid = net_buf_simple_pull_u8(p_buf);
#ifdef CONFIG_MESH_MODEL_TRANS
if (p_buf->len)
{
trans = net_buf_simple_pull_u8(p_buf);
delay = net_buf_simple_pull_u8(p_buf);
}
else
{
trans = 0;
delay = 0;
}
if ((trans & 0x3F) == 0x3F)
{
BT_ERR("MESH_SET_TRANSTION_ERROR");
return MESH_SET_TRANSTION_ERROR;
}
#endif
if (genie_transport_check_tid(src_addr, tid, p_elem->element_id) != MESH_SUCCESS)
{
BT_ERR("MESH_TID_REPEAT src_addr(0x%04x) tid(0x%02x)", src_addr, tid);
return MESH_TID_REPEAT;
}
//light_set_target_with_ctl(lightness, p_elem->state.color_temperature[TYPE_TARGET]);
p_elem->state.lightness[TYPE_TARGET] = lightness;
if (p_elem->state.lightness[TYPE_TARGET])
{
p_elem->powerup.last_lightness = p_elem->state.lightness[TYPE_TARGET];
}
BT_DBG("lightness cur(%04x) tar(%04x)", p_elem->state.lightness[TYPE_PRESENT], p_elem->state.lightness[TYPE_TARGET]);
#ifdef CONFIG_MESH_MODEL_TRANS
p_elem->state.trans = trans;
p_elem->state.delay = delay;
if (p_elem->state.trans)
{
p_elem->state.trans_start_time = k_uptime_get() + p_elem->state.delay * 5; // delay is in 5 millisecond steps
p_elem->state.trans_end_time = p_elem->state.trans_start_time + sig_model_transition_get_transition_time(p_elem->state.trans);
}
BT_DBG("trans(0x%02x) delay(0x%02x)", p_elem->state.trans, p_elem->state.delay);
#endif
if (p_elem->state.lightness[TYPE_PRESENT] != p_elem->state.lightness[TYPE_TARGET])
{
sig_model_event_set_indicate(SIG_MODEL_INDICATE_GEN_LIGHTNESS);
sig_model_generic_lightness_bind_ops(p_elem, TYPE_TARGET);
}
return MESH_SUCCESS;
}
static void _lightness_get(struct bt_mesh_model *p_model,
struct bt_mesh_msg_ctx *p_ctx,
struct net_buf_simple *p_buf)
{
BT_DBG("");
sig_model_msg msg;
sig_model_element_state_t *p_elem_state = NULL;
if (!p_model || !p_model->user_data)
{
GENIE_LOG_ERR("param err");
return;
}
memset(&msg, 0, sizeof(sig_model_msg));
msg.opcode = OP_GENERIC_LIGHTNESS_GET;
if (p_buf != NULL)
{
msg.len = p_buf->len;
msg.data = (u8_t *)p_buf->data;
}
genie_transport_src_addr_set(p_ctx->addr);
p_elem_state = (sig_model_element_state_t *)p_model->user_data;
msg.element_id = p_elem_state->element_id;
sig_model_event(SIG_MODEL_EVT_GENERIC_MESG, (void *)&msg);
_lightness_status(p_model, p_ctx, 0);
}
static void _lightness_set(struct bt_mesh_model *p_model,
struct bt_mesh_msg_ctx *p_ctx,
struct net_buf_simple *p_buf)
{
E_MESH_ERROR_TYPE ret = 0;
sig_model_msg msg;
sig_model_element_state_t *p_elem_state = NULL;
if (!p_model || !p_model->user_data)
{
printf("param err");
return;
}
memset(&msg, 0, sizeof(sig_model_msg));
msg.opcode = OP_GENERIC_LIGHTNESS_SET;
if (p_buf != NULL)
{
msg.len = p_buf->len;
msg.data = (u8_t *)p_buf->data;
}
genie_transport_src_addr_set(p_ctx->addr);
p_elem_state = (sig_model_element_state_t *)p_model->user_data;
msg.element_id = p_elem_state->element_id;
sig_model_event(SIG_MODEL_EVT_GENERIC_MESG, (void *)&msg);
ret = _lightness_analyze(p_model, p_ctx->addr, p_buf);
BT_DBG("ret %d", ret);
if (ret == MESH_SUCCESS || ret == MESH_TID_REPEAT)
{
_lightness_status(p_model, p_ctx, 1);
if (ret == MESH_SUCCESS)
{
sig_model_event(SIG_MODEL_EVT_ANALYZE_MSG, (sig_model_element_state_t *)p_model->user_data);
}
}
}
static void _lightness_set_unack(struct bt_mesh_model *p_model,
struct bt_mesh_msg_ctx *p_ctx,
struct net_buf_simple *p_buf)
{
BT_DBG("");
sig_model_msg msg;
sig_model_element_state_t *p_elem_state = NULL;
if (!p_model || !p_model->user_data)
{
GENIE_LOG_ERR("param err");
return;
}
memset(&msg, 0, sizeof(sig_model_msg));
msg.opcode = OP_GENERIC_LIGHTNESS_SET_UNACK;
if (p_buf != NULL)
{
msg.len = p_buf->len;
msg.data = (u8_t *)p_buf->data;
}
genie_transport_src_addr_set(p_ctx->addr);
p_elem_state = (sig_model_element_state_t *)p_model->user_data;
msg.element_id = p_elem_state->element_id;
sig_model_event(SIG_MODEL_EVT_GENERIC_MESG, (void *)&msg);
E_MESH_ERROR_TYPE ret = _lightness_analyze(p_model, p_ctx->addr, p_buf);
if (ret == MESH_SUCCESS)
{
sig_model_event(SIG_MODEL_EVT_ANALYZE_MSG, (sig_model_element_state_t *)p_model->user_data);
}
}
const struct bt_mesh_model_op g_lightness_op[LIGHTNESS_OPC_NUM] = {
/* Light Lightness */
{OP_GENERIC_LIGHTNESS_GET, 0, _lightness_get},
{OP_GENERIC_LIGHTNESS_SET, 2, _lightness_set}, /* bind operation executed after action done in genie_mesh */
{OP_GENERIC_LIGHTNESS_SET_UNACK, 2, _lightness_set_unack},
BT_MESH_MODEL_OP_END,
};
void sig_model_lightness_update_by_onoff(sig_model_element_state_t *p_elem)
{
sig_model_state_t *p_state = &p_elem->state;
BT_DBG("onoff cur(%d) tar(%d)", p_state->onoff[TYPE_PRESENT], p_state->onoff[TYPE_TARGET]);
#ifdef CONFIG_MESH_MODEL_GEN_ONOFF_SRV
if (p_state->onoff[TYPE_PRESENT] == 0 && p_state->onoff[TYPE_TARGET] == 1)
{
//turn on, set default lightness
if (p_elem->powerup.last_lightness)
{
p_state->lightness[TYPE_TARGET] = p_elem->powerup.last_lightness;
}
else
{
p_state->lightness[TYPE_TARGET] = LIGHTNESS_DEFAULT;
}
}
else if (p_state->onoff[TYPE_PRESENT] == 1 && p_state->onoff[TYPE_TARGET] == 0)
{
//turn off, set zero
p_state->lightness[TYPE_TARGET] = 0;
}
#endif
BT_DBG("lightness cur(%04x) tar(%04x)", p_state->lightness[TYPE_PRESENT], p_state->lightness[TYPE_TARGET]);
}
| YifuLiu/AliOS-Things | components/genie_service/core/src/sig_models/sig_model_lightness_srv.c | C | apache-2.0 | 8,636 |
/*
* Copyright (C) 2018-2020 Alibaba Group Holding Limited
*/
#include <api/mesh.h>
#include "sig_models/sig_model.h"
#define BT_DBG_ENABLED 1 //IS_ENABLED(CONFIG_BT_MESH_DEBUG_MODEL)
#include "common/log.h"
struct bt_mesh_model_pub g_gen_onoff_pub = {
#ifndef CONFIG_BT_MESH_NOPUB
.msg = NET_BUF_SIMPLE(2 + 3 + 4),
#endif
};
static void _gen_onoff_prepear_buf(struct bt_mesh_model *p_model, struct net_buf_simple *p_msg, bool is_ack)
{
sig_model_state_t *p_state = &((sig_model_element_state_t *)p_model->user_data)->state;
u8_t remain_time_byte = 0;
BT_DBG("onoff cur(%d) tar(%d)", p_state->onoff[TYPE_PRESENT], p_state->onoff[TYPE_TARGET]);
#ifdef CONFIG_MESH_MODEL_TRANS
remain_time_byte = sig_model_transition_get_remain_time_byte(p_state, is_ack);
BT_DBG("remain(0x%02x)", remain_time_byte);
#endif
//prepear buff
bt_mesh_model_msg_init(p_msg, OP_GENERIC_ONOFF_STATUS);
if (is_ack && remain_time_byte == 0)
{
net_buf_simple_add_u8(p_msg, p_state->onoff[TYPE_TARGET]);
}
else
{
net_buf_simple_add_u8(p_msg, p_state->onoff[TYPE_PRESENT]);
#ifdef CONFIG_MESH_MODEL_TRANS
if (remain_time_byte)
{
net_buf_simple_add_u8(p_msg, p_state->onoff[TYPE_TARGET]);
net_buf_simple_add_u8(p_msg, remain_time_byte);
}
#endif
}
}
static void _gen_onoff_status(struct bt_mesh_model *p_model,
struct bt_mesh_msg_ctx *p_ctx, bool is_ack)
{
struct net_buf_simple *p_msg = NET_BUF_SIMPLE(2 + 3 + 4);
BT_DBG("addr(0x%04x)", bt_mesh_model_elem(p_model)->addr);
_gen_onoff_prepear_buf(p_model, p_msg, is_ack);
p_ctx->send_ttl = GENIE_TRANSPORT_DEFAULT_TTL;
if (bt_mesh_model_send(p_model, p_ctx, p_msg, NULL, NULL))
{
BT_ERR("Unable to send OnOff Status");
}
BT_DBG("Success!!!");
}
struct net_buf_simple *p_ack_buff;
static E_MESH_ERROR_TYPE _gen_onoff_analyze(struct bt_mesh_model *p_model,
u16_t src_addr, struct net_buf_simple *p_buf)
{
u8_t onoff = 0;
u8_t tid = 0;
#ifdef CONFIG_MESH_MODEL_TRANS
u8_t trans = 0;
u8_t delay = 0;
#endif
sig_model_element_state_t *p_elem = NULL;
if (!p_model || !p_buf)
{
return MESH_ANALYZE_ARGS_ERROR;
}
p_elem = p_model->user_data;
if (p_buf->len != 2 && p_buf->len != 4)
{
BT_ERR("MESH_ANALYZE_SIZE_ERROR buf->len(%d)", p_buf->len);
return MESH_ANALYZE_SIZE_ERROR;
}
//get message info
onoff = net_buf_simple_pull_u8(p_buf);
tid = net_buf_simple_pull_u8(p_buf);
#ifdef CONFIG_MESH_MODEL_TRANS
if (p_buf->len)
{
trans = net_buf_simple_pull_u8(p_buf);
delay = net_buf_simple_pull_u8(p_buf);
}
else
{
trans = 0;
delay = 0;
}
#endif
if (onoff >> 1)
{
BT_ERR("MESH_ANALYZE_ARGS_ERROR onoff(0x%02x)", onoff);
return MESH_ANALYZE_ARGS_ERROR;
}
#ifdef CONFIG_MESH_MODEL_TRANS
if ((trans & 0x3F) == 0x3F)
{
BT_ERR("MESH_SET_TRANSTION_ERROR");
return MESH_SET_TRANSTION_ERROR;
}
#endif
if (genie_transport_check_tid(src_addr, tid, p_elem->element_id) != MESH_SUCCESS)
{
BT_ERR("MESH_TID_REPEAT src_addr(0x%04x) tid(0x%02x)", src_addr, tid);
return MESH_TID_REPEAT;
}
genie_transport_src_addr_set(src_addr);
p_elem->state.onoff[TYPE_TARGET] = onoff;
BT_DBG("onoff cur(%d) tar(%d)", p_elem->state.onoff[TYPE_PRESENT], p_elem->state.onoff[TYPE_TARGET]);
#ifdef CONFIG_MESH_MODEL_TRANS
p_elem->state.trans = trans;
p_elem->state.delay = delay;
if (p_elem->state.trans)
{
p_elem->state.trans_start_time = k_uptime_get() + p_elem->state.delay * 5;
p_elem->state.trans_end_time = p_elem->state.trans_start_time + sig_model_transition_get_transition_time(p_elem->state.trans);
}
BT_DBG("trans(0x%02x) delay(0x%02x)", p_elem->state.trans, p_elem->state.delay);
#endif
if (p_elem->state.onoff[TYPE_PRESENT] != p_elem->state.onoff[TYPE_TARGET])
{
sig_model_event_set_indicate(SIG_MODEL_INDICATE_GEN_ONOFF);
sig_model_generic_onoff_bind_ops(p_elem);
}
return MESH_SUCCESS;
}
void gen_onoff_publication(struct bt_mesh_model *p_model)
{
}
static void _gen_onoff_get(struct bt_mesh_model *p_model,
struct bt_mesh_msg_ctx *p_ctx,
struct net_buf_simple *p_buf)
{
sig_model_msg msg;
sig_model_element_state_t *p_elem_state = NULL;
if (!p_model || !p_model->user_data)
{
GENIE_LOG_ERR("param err");
return;
}
memset(&msg, 0, sizeof(sig_model_msg));
msg.opcode = OP_GENERIC_ONOFF_GET;
if (p_buf != NULL)
{
msg.len = p_buf->len;
msg.data = (u8_t *)p_buf->data;
}
genie_transport_src_addr_set(p_ctx->addr);
p_elem_state = (sig_model_element_state_t *)p_model->user_data;
msg.element_id = p_elem_state->element_id;
sig_model_event(SIG_MODEL_EVT_GENERIC_MESG, (void *)&msg);
#ifndef CONFIG_GENIE_MESH_NO_AUTO_REPLY
_gen_onoff_status(p_model, p_ctx, 0);
#endif
}
static void _gen_onoff_set(struct bt_mesh_model *p_model,
struct bt_mesh_msg_ctx *p_ctx,
struct net_buf_simple *p_buf)
{
sig_model_msg msg;
sig_model_element_state_t *p_elem_state = NULL;
memset(&msg, 0, sizeof(sig_model_msg));
msg.opcode = OP_GENERIC_ONOFF_SET;
if (p_buf != NULL)
{
msg.len = p_buf->len;
msg.data = (u8_t *)p_buf->data;
}
E_MESH_ERROR_TYPE ret = _gen_onoff_analyze(p_model, p_ctx->addr, p_buf);
if (ret == MESH_SUCCESS)
{
p_elem_state = (sig_model_element_state_t *)p_model->user_data;
msg.element_id = p_elem_state->element_id;
sig_model_event(SIG_MODEL_EVT_GENERIC_MESG, (void *)&msg);
}
#ifndef CONFIG_GENIE_MESH_NO_AUTO_REPLY
if (ret == MESH_SUCCESS || ret == MESH_TID_REPEAT)
{
_gen_onoff_status(p_model, p_ctx, 1);
if (ret == MESH_SUCCESS)
{
sig_model_event(SIG_MODEL_EVT_ANALYZE_MSG, (sig_model_element_state_t *)p_model->user_data);
}
}
#endif
}
static void _gen_onoff_set_unack(struct bt_mesh_model *p_model,
struct bt_mesh_msg_ctx *p_ctx,
struct net_buf_simple *p_buf)
{
sig_model_msg msg;
sig_model_element_state_t *p_elem_state = NULL;
memset(&msg, 0, sizeof(sig_model_msg));
msg.opcode = OP_GENERIC_ONOFF_SET_UNACK;
if (p_buf != NULL)
{
msg.len = p_buf->len;
msg.data = (u8_t *)p_buf->data;
}
E_MESH_ERROR_TYPE ret = _gen_onoff_analyze(p_model, p_ctx->addr, p_buf);
if (ret == MESH_SUCCESS)
{
p_elem_state = (sig_model_element_state_t *)p_model->user_data;
msg.element_id = p_elem_state->element_id;
sig_model_event(SIG_MODEL_EVT_GENERIC_MESG, (void *)&msg);
#ifndef CONFIG_GENIE_MESH_NO_AUTO_REPLY
sig_model_event(SIG_MODEL_EVT_ANALYZE_MSG, (sig_model_element_state_t *)p_model->user_data);
#endif
}
}
const struct bt_mesh_model_op g_gen_onoff_op[] = {
{OP_GENERIC_ONOFF_GET, 0, _gen_onoff_get},
{OP_GENERIC_ONOFF_SET, 2, _gen_onoff_set},
{OP_GENERIC_ONOFF_SET_UNACK, 2, _gen_onoff_set_unack},
BT_MESH_MODEL_OP_END,
};
#ifdef CONFIG_MESH_MODEL_CTL_SRV
void sig_model_onoff_update_by_color_temperature(sig_model_element_state_t *p_elem)
{
sig_model_state_t *p_state = &p_elem->state;
if (p_state->onoff[TYPE_TARGET] == 0)
{
//turn on
p_state->onoff[TYPE_TARGET] = 1;
sig_model_generic_onoff_bind_ops(p_elem);
}
}
#endif
#ifdef CONFIG_MESH_MODEL_LIGHTNESS_SRV
void sig_model_onoff_update_by_lightness(sig_model_element_state_t *p_elem, E_VALUE_TYPE type)
{
sig_model_state_t *p_state = &p_elem->state;
if (type == TYPE_TARGET)
{
if (p_state->lightness[TYPE_PRESENT] == 0 && p_state->lightness[TYPE_TARGET] != 0)
{
//turn on
p_state->onoff[TYPE_TARGET] = 1;
}
else if (p_state->lightness[TYPE_PRESENT] != 0 && p_state->lightness[TYPE_TARGET] == 0)
{
//turn off
p_state->onoff[TYPE_TARGET] = 0;
}
}
else if (type == TYPE_PRESENT)
{
if (p_state->lightness[TYPE_PRESENT] == 0 && p_state->lightness[TYPE_TARGET] == 0)
{
//turn off
p_state->onoff[TYPE_PRESENT] = 0;
}
}
}
#endif
| YifuLiu/AliOS-Things | components/genie_service/core/src/sig_models/sig_model_onoff_srv.c | C | apache-2.0 | 8,566 |
/*
* Copyright (C) 2018-2020 Alibaba Group Holding Limited
*/
#define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_MESH_DEBUG_MODEL)
#include <api/mesh.h>
#include "sig_models/sig_model.h"
#include "access.h"
#include "common/log.h"
struct bt_mesh_model_pub g_scene_pub = {
.msg = NET_BUF_SIMPLE(2 + 5 + 4),
};
static void _scene_prepare_buf(struct bt_mesh_model *p_model, struct net_buf_simple *p_msg, bool is_ack)
{
sig_model_state_t *p_state = &((sig_model_element_state_t *)p_model->user_data)->state;
bt_mesh_model_msg_init(p_msg, OP_GENERIC_SCENE_STATUS);
net_buf_simple_add_le16(p_msg, p_state->scene[TYPE_PRESENT]);
}
static void _scene_status(struct bt_mesh_model *p_model,
struct bt_mesh_msg_ctx *p_ctx, bool is_ack)
{
struct net_buf_simple *p_msg = NET_BUF_SIMPLE(1 + 2 + 4);
BT_DBG("addr(0x%04x)", bt_mesh_model_elem(p_model)->addr);
_scene_prepare_buf(p_model, p_msg, is_ack);
p_ctx->send_ttl = GENIE_TRANSPORT_DEFAULT_TTL;
if (bt_mesh_model_send(p_model, p_ctx, p_msg, NULL, NULL))
{
BT_ERR("Unable to send scene Status");
}
BT_DBG("Success!!!");
}
int genie_model_scene_changed(u16_t last_scene, u16_t target_scene)
{
return 0;
}
static E_MESH_ERROR_TYPE _scene_analyze(struct bt_mesh_model *p_model,
u16_t src_addr, struct net_buf_simple *p_buf)
{
s16_t scene = 0;
u8_t tid = 0;
sig_model_element_state_t *p_elem = NULL;
if (!p_model || !p_buf)
return MESH_ANALYZE_ARGS_ERROR;
p_elem = p_model->user_data;
if (p_buf->len != 3 && p_buf->len != 5)
{
BT_ERR("MESH_ANALYZE_SIZE_ERROR buf->len(%d)", p_buf->len);
return MESH_ANALYZE_SIZE_ERROR;
}
scene = (s16_t)net_buf_simple_pull_le16(p_buf);
tid = net_buf_simple_pull_u8(p_buf);
if (genie_transport_check_tid(src_addr, tid, p_elem->element_id) != MESH_SUCCESS)
{
BT_ERR("MESH_TID_REPEAT src_addr(0x%04x) tid(0x%02x)", src_addr, tid);
return MESH_TID_REPEAT;
}
genie_transport_src_addr_set(src_addr);
if (p_elem->state.scene[TYPE_TARGET] != scene)
{
genie_model_scene_changed(p_elem->state.scene[TYPE_TARGET], scene);
p_elem->state.scene[TYPE_TARGET] = scene;
sig_model_event_set_indicate(SIG_MODEL_INDICATE_GEN_SCENE);
}
else
{
GENIE_LOG_WARN("Dup light sence");
}
GENIE_LOG_INFO("light sence(0x%02x)", p_elem->state.scene);
return MESH_SUCCESS;
}
static void _scene_get(struct bt_mesh_model *p_model,
struct bt_mesh_msg_ctx *p_ctx,
struct net_buf_simple *p_buf)
{
sig_model_msg msg;
sig_model_element_state_t *p_elem_state = NULL;
memset(&msg, 0, sizeof(sig_model_msg));
msg.opcode = OP_GENERIC_SCENE_GET;
if (p_buf != NULL)
{
msg.len = p_buf->len;
msg.data = (u8_t *)p_buf->data;
}
genie_transport_src_addr_set(p_ctx->addr);
p_elem_state = (sig_model_element_state_t *)p_model->user_data;
msg.element_id = p_elem_state->element_id;
sig_model_event(SIG_MODEL_EVT_GENERIC_MESG, (void *)&msg);
#ifndef CONFIG_GENIE_MESH_NO_AUTO_REPLY
_scene_status(p_model, p_ctx, 0);
#endif
}
static void _scene_set(struct bt_mesh_model *p_model,
struct bt_mesh_msg_ctx *p_ctx,
struct net_buf_simple *p_buf)
{
sig_model_msg msg;
sig_model_element_state_t *p_elem_state = NULL;
memset(&msg, 0, sizeof(sig_model_msg));
msg.opcode = OP_GENERIC_SCENE_SET;
if (p_buf != NULL)
{
msg.len = p_buf->len;
msg.data = (u8_t *)p_buf->data;
}
E_MESH_ERROR_TYPE ret = _scene_analyze(p_model, p_ctx->addr, p_buf);
BT_DBG("ret %d", ret);
if (ret == MESH_SUCCESS)
{
p_elem_state = (sig_model_element_state_t *)p_model->user_data;
msg.element_id = p_elem_state->element_id;
sig_model_event(SIG_MODEL_EVT_GENERIC_MESG, (void *)&msg);
}
#ifndef CONFIG_GENIE_MESH_NO_AUTO_REPLY
if (ret == MESH_SUCCESS || ret == MESH_TID_REPEAT)
{
_scene_status(p_model, p_ctx, 1);
if (ret == MESH_SUCCESS)
{
sig_model_event(SIG_MODEL_EVT_ANALYZE_MSG, (sig_model_element_state_t *)p_model->user_data);
}
}
#endif
}
static void _scene_set_unack(struct bt_mesh_model *p_model,
struct bt_mesh_msg_ctx *p_ctx,
struct net_buf_simple *p_buf)
{
sig_model_msg msg;
sig_model_element_state_t *p_elem_state = NULL;
memset(&msg, 0, sizeof(sig_model_msg));
msg.opcode = OP_GENERIC_SCENE_SET_UNACK;
if (p_buf != NULL)
{
msg.len = p_buf->len;
msg.data = (u8_t *)p_buf->data;
}
E_MESH_ERROR_TYPE ret = _scene_analyze(p_model, p_ctx->addr, p_buf);
if (ret == MESH_SUCCESS)
{
p_elem_state = (sig_model_element_state_t *)p_model->user_data;
msg.element_id = p_elem_state->element_id;
sig_model_event(SIG_MODEL_EVT_GENERIC_MESG, (void *)&msg);
#ifndef CONFIG_GENIE_MESH_NO_AUTO_REPLY
sig_model_event(SIG_MODEL_EVT_ANALYZE_MSG, (sig_model_element_state_t *)p_model->user_data);
#endif
}
}
const struct bt_mesh_model_op g_scene_op[GENIE_SCENE_OP_NUM] = {
{OP_GENERIC_SCENE_GET, 0, _scene_get},
{OP_GENERIC_SCENE_SET, 2, _scene_set},
{OP_GENERIC_SCENE_SET_UNACK, 2, _scene_set_unack},
BT_MESH_MODEL_OP_END,
};
| YifuLiu/AliOS-Things | components/genie_service/core/src/sig_models/sig_model_scene_srv.c | C | apache-2.0 | 5,475 |
/*
* Copyright (C) 2019-2020 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
//#include <aos/aos.h>
#include <aos/kernel.h>
#include <misc/printk.h>
#include <misc/byteorder.h>
//#include <hal/soc/gpio.h>
//#include <hal/soc/pwm.h>
#include <bluetooth/bluetooth.h>
//#include <soc.h>
#include <api/mesh.h>
#include "common/log.h"
#include "genie_service.h"
#ifdef CONFIG_MESH_MODEL_TRANS
void sig_model_transition_timer_stop(sig_model_element_state_t *p_elem)
{
k_timer_stop(&p_elem->state.delay_timer);
k_timer_stop(&p_elem->state.trans_timer);
}
void sig_model_transition_state_reset(sig_model_element_state_t *p_elem)
{
p_elem->state.trans = 0;
p_elem->state.trans_start_time = 0;
p_elem->state.trans_end_time = 0;
}
#define DELTA_ACTUAL_MIN 655
#define DELTA_TEMP_MIN 192
uint8_t sig_model_transition_update(sig_model_element_state_t *p_elem)
{
uint8_t cycle = 0;
uint16_t delta = 0;
bt_u32_t cur_time = k_uptime_get();
sig_model_state_t *p_state = &p_elem->state;
//stop cycle when timeout
if (cur_time <= p_state->trans_end_time - SIG_MODEL_TRANSITION_INTERVAL)
{
#if defined(CONFIG_MESH_MODEL_LIGHTNESS_SRV) || defined(CONFIG_MESH_MODEL_CTL_SRV)
uint16_t step = (p_state->trans_end_time - cur_time) / SIG_MODEL_TRANSITION_INTERVAL;
#endif
#ifdef CONFIG_MESH_MODEL_GEN_ONOFF_SRV
if (p_state->onoff[TYPE_PRESENT] != p_state->onoff[TYPE_TARGET])
{
p_state->onoff[TYPE_PRESENT] = p_state->onoff[TYPE_TARGET];
sig_model_event_set_indicate(SIG_MODEL_INDICATE_GEN_ONOFF);
}
#endif
#ifdef CONFIG_MESH_MODEL_LIGHTNESS_SRV
if (p_state->lightness[TYPE_PRESENT] != p_state->lightness[TYPE_TARGET])
{
if (p_state->lightness[TYPE_TARGET] > p_state->lightness[TYPE_PRESENT])
{
delta = (p_state->lightness[TYPE_TARGET] - p_state->lightness[TYPE_PRESENT]) / step;
delta = delta > DELTA_ACTUAL_MIN ? delta : DELTA_ACTUAL_MIN;
if (LIGHTNESS_MAX_VALUE - p_state->lightness[TYPE_PRESENT] < delta ||
p_state->lightness[TYPE_TARGET] - p_state->lightness[TYPE_PRESENT] < delta)
{
p_state->lightness[TYPE_PRESENT] = p_state->lightness[TYPE_TARGET];
sig_model_event_set_indicate(SIG_MODEL_INDICATE_GEN_LIGHTNESS);
}
else
{
p_state->lightness[TYPE_PRESENT] += delta;
if (p_state->lightness[TYPE_PRESENT] == p_state->lightness[TYPE_TARGET])
{
sig_model_event_set_indicate(SIG_MODEL_INDICATE_GEN_LIGHTNESS);
}
}
}
else
{
delta = (p_state->lightness[TYPE_PRESENT] - p_state->lightness[TYPE_TARGET]) / step;
delta = delta > DELTA_ACTUAL_MIN ? delta : DELTA_ACTUAL_MIN;
if (p_state->lightness[TYPE_PRESENT] < delta ||
p_state->lightness[TYPE_PRESENT] - delta < p_state->lightness[TYPE_TARGET])
{
p_state->lightness[TYPE_PRESENT] = p_state->lightness[TYPE_TARGET];
sig_model_event_set_indicate(SIG_MODEL_INDICATE_GEN_LIGHTNESS);
}
else
{
p_state->lightness[TYPE_PRESENT] -= delta;
if (p_state->lightness[TYPE_PRESENT] == p_state->lightness[TYPE_TARGET])
{
sig_model_event_set_indicate(SIG_MODEL_INDICATE_GEN_LIGHTNESS);
}
}
}
cycle = 1;
}
#endif
#ifdef CONFIG_MESH_MODEL_CTL_SRV
if (p_state->color_temperature[TYPE_PRESENT] != p_state->color_temperature[TYPE_TARGET])
{
if (p_state->color_temperature[TYPE_TARGET] > p_state->color_temperature[TYPE_PRESENT])
{
delta = (p_state->color_temperature[TYPE_TARGET] - p_state->color_temperature[TYPE_PRESENT]) / step;
delta = delta > DELTA_TEMP_MIN ? delta : DELTA_TEMP_MIN;
if (COLOR_TEMPERATURE_MAX - p_state->color_temperature[TYPE_PRESENT] < delta ||
p_state->color_temperature[TYPE_TARGET] - p_state->color_temperature[TYPE_PRESENT] < delta)
{
p_state->color_temperature[TYPE_PRESENT] = p_state->color_temperature[TYPE_TARGET];
sig_model_event_set_indicate(SIG_MODEL_INDICATE_GEN_CTL);
}
else
{
p_state->color_temperature[TYPE_PRESENT] += delta;
if (p_state->color_temperature[TYPE_PRESENT] == p_state->color_temperature[TYPE_TARGET])
{
sig_model_event_set_indicate(SIG_MODEL_INDICATE_GEN_CTL);
}
}
delta += p_state->color_temperature[TYPE_PRESENT];
p_state->color_temperature[TYPE_PRESENT] = delta > p_state->color_temperature[TYPE_TARGET] ? p_state->color_temperature[TYPE_TARGET] : delta;
}
else
{
delta = (p_state->color_temperature[TYPE_PRESENT] - p_state->color_temperature[TYPE_TARGET]) / step;
delta = delta > DELTA_TEMP_MIN ? delta : DELTA_TEMP_MIN;
if (p_state->color_temperature[TYPE_PRESENT] < delta + COLOR_TEMPERATURE_MIN ||
p_state->color_temperature[TYPE_PRESENT] - delta < p_state->color_temperature[TYPE_TARGET])
{
p_state->color_temperature[TYPE_PRESENT] = p_state->color_temperature[TYPE_TARGET];
sig_model_event_set_indicate(SIG_MODEL_INDICATE_GEN_CTL);
}
else
{
p_state->color_temperature[TYPE_PRESENT] -= delta;
if (p_state->color_temperature[TYPE_PRESENT] == p_state->color_temperature[TYPE_TARGET])
{
sig_model_event_set_indicate(SIG_MODEL_INDICATE_GEN_CTL);
}
}
}
cycle = 1;
}
#endif
}
#if 0
printf("next: %d->%d|%02x->%02x|%02x->%02x\n", p_state->onoff[TYPE_PRESENT], p_state->onoff[TYPE_TARGET],
p_state->lightness[TYPE_PRESENT], p_state->lightness[TYPE_TARGET], p_state->color_temperature[TYPE_PRESENT], p_state->color_temperature[TYPE_TARGET]);
#endif
#ifdef CONFIG_MESH_MODEL_GEN_ONOFF_SRV
if (p_state->onoff[TYPE_PRESENT] == p_state->onoff[TYPE_TARGET])
#endif
#ifdef CONFIG_MESH_MODEL_LIGHTNESS_SRV
if (p_state->lightness[TYPE_PRESENT] == p_state->lightness[TYPE_TARGET])
#endif
#ifdef CONFIG_MESH_MODEL_CTL_SRV
if (p_state->color_temperature[TYPE_PRESENT] == p_state->color_temperature[TYPE_TARGET])
#endif
cycle = 0;
//BT_DBG("cycle %d", cycle);
if (cycle == 0)
{
#ifdef CONFIG_MESH_MODEL_GEN_ONOFF_SRV
#ifdef CONFIG_MESH_MODEL_LIGHTNESS_SRV
if (p_state->lightness[TYPE_TARGET] == 0)
{
p_state->onoff[TYPE_TARGET] = 0;
}
#endif
if (p_state->onoff[TYPE_PRESENT] != p_state->onoff[TYPE_TARGET])
{
p_state->onoff[TYPE_PRESENT] = p_state->onoff[TYPE_TARGET];
sig_model_event_set_indicate(SIG_MODEL_INDICATE_GEN_ONOFF);
}
//BT_DBG("onoff %d->%d", p_state->onoff[TYPE_PRESENT], p_state->onoff[TYPE_TARGET]);
#endif
#ifdef CONFIG_MESH_MODEL_LIGHTNESS_SRV
if (p_state->lightness[TYPE_PRESENT] != p_state->lightness[TYPE_TARGET])
{
p_state->lightness[TYPE_PRESENT] = p_state->lightness[TYPE_TARGET];
sig_model_event_set_indicate(SIG_MODEL_INDICATE_GEN_LIGHTNESS);
}
//BT_DBG("lightness %02x->%02x", p_state->lightness[TYPE_PRESENT], p_state->lightness[TYPE_TARGET]);
#endif
#ifdef CONFIG_MESH_MODEL_CTL_SRV
if (p_state->color_temperature[TYPE_PRESENT] != p_state->color_temperature[TYPE_TARGET])
{
p_state->color_temperature[TYPE_PRESENT] = p_state->color_temperature[TYPE_TARGET];
sig_model_event_set_indicate(SIG_MODEL_INDICATE_GEN_CTL);
}
//BT_DBG("color_temperature %02x->%02x", p_state->color_temperature[TYPE_PRESENT], p_state->color_temperature[TYPE_TARGET]);
#endif
p_state->trans = 0;
}
return cycle;
}
#endif
#ifdef CONFIG_MESH_MODEL_TRANS
bt_u32_t TRANS_TIMES[] = {TRANSITION_TIME_UNIT_1, TRANSITION_TIME_UNIT_2, TRANSITION_TIME_UNIT_3, TRANSITION_TIME_UNIT_4};
static uint8_t _get_transition_byte(bt_u32_t time)
{
if (time > TRANS_TIMES[3] * TRANSITION_TIME_VALUE_MAX)
{
return 0;
}
else if (time > TRANS_TIMES[2] * TRANSITION_TIME_VALUE_MAX)
{
return (time / TRANS_TIMES[3]) | TRANSITION_TIME_UNIT_BIT(3);
}
else if (time > TRANS_TIMES[1] * TRANSITION_TIME_VALUE_MAX)
{
return (time / TRANS_TIMES[2]) | TRANSITION_TIME_UNIT_BIT(2);
}
else if (time > TRANS_TIMES[0] * TRANSITION_TIME_VALUE_MAX)
{
return (time / TRANS_TIMES[1]) | TRANSITION_TIME_UNIT_BIT(1);
}
else
{
return (time / TRANS_TIMES[0]);
}
}
//unit is 1ms
bt_u32_t sig_model_transition_get_transition_time(uint8_t byte)
{
if ((byte & TRANSITION_TIME_VALUE_MASK) == TRANSITION_TIME_VALUE_INVALID)
{
MODEL_E("%s ERROR, invalid 0x%02X!!!\n", __func__, byte);
return TRANSITION_TIME_VALUE_INVALID;
}
return (byte & TRANSITION_TIME_VALUE_MASK) * TRANS_TIMES[byte >> 6];
}
uint8_t sig_model_transition_get_remain_time_byte(sig_model_state_t *p_state, bool is_ack)
{
uint8_t remain_time_byte = p_state->trans;
int64_t cur_time = k_uptime_get();
int64_t passed_time = 0;
bt_u32_t trans_duration = 0;
if (!is_ack && p_state->trans_start_time < cur_time)
{
passed_time -= p_state->trans_start_time;
trans_duration = sig_model_transition_get_transition_time(p_state->trans);
if (trans_duration > passed_time)
{
remain_time_byte = _get_transition_byte(trans_duration - passed_time);
}
else
{
remain_time_byte = TRANSITION_TIME_VALUE_MIN;
}
}
return remain_time_byte;
}
#endif
| YifuLiu/AliOS-Things | components/genie_service/core/src/sig_models/sig_model_transition.c | C | apache-2.0 | 10,414 |
#include <stdio.h>
#include <string.h>
#include "aos/hal/flash.h"
#include "ali_dfu_port.h"
/* 需要定义SPIFLAHS Sector 大小 */
#ifndef SPIF_SECTOR_SIZE
#define SPIF_SECTOR_SIZE 0x1000
#endif
extern uint16_t util_crc16_ccitt(uint8_t const *p_data, uint32_t size, uint16_t const *p_crc);
extern void drv_reboot(void);
#define LOG printf
#define ADDR_GRAN_MASK (0xFFF)
#define ADDR_ALIGN_UP(a) (((a) + ADDR_GRAN_MASK) & ~ADDR_GRAN_MASK)
static unsigned short image_crc16 = 0;
/**
* @brief 镜像更新
*
* @param[in] signature 暂时不使用
* @param[in] offset 当前buf代表的内容,从镜像bin文件从offset位置开始,比如为100,表示当前buffer是bin文件的第100字节开始
* @param[in] length 本次buffer的长度
* @param[in] buf 本次写入的具体内容
*
* @return 0:success, otherwise is failed
*/
int ali_dfu_image_update(short signature, int offset, int length, int *buf)
{
int ret;
hal_logic_partition_t partition_info;
uint32_t wr_idx = offset;
uint8_t *wr_buf = (uint8_t *)buf;
if (offset == 0)
{
image_crc16 = util_crc16_ccitt(wr_buf, length, NULL);
}
else
{
image_crc16 = util_crc16_ccitt(wr_buf, length, &image_crc16);
}
///get OTA temporary partition information
hal_flash_info_get(HAL_PARTITION_OTA_TEMP, &partition_info);
if (partition_info.partition_length < (offset + length))
{
LOG("The write range is over OTA temporary!\r\n");
return -1;
}
/* For bootloader upgrade, we will reserve two sectors, then save the image */
wr_idx += (SPIF_SECTOR_SIZE << 1);
ret = hal_flash_write(HAL_PARTITION_OTA_TEMP, &wr_idx, (void *)wr_buf, length);
if (ret < 0)
{
LOG("write flash error!!\r\n");
return -1;
}
//LOG("write ok!\n");
return 0;
}
/**
* @brief 写入flash之前和之后checksum计算
*
* @param[in] image_id 暂时不使用
* @param[in] crc16_output 计算出来的crc返回给调用者
*
* @return 1:success 0:failed
*/
unsigned char dfu_check_checksum(short image_id, unsigned short *crc16_output)
{
*crc16_output = image_crc16;
return 1;
}
/**
* @brief 升级结束后重启
*
* @param[in] -
* @return -
* @说明: 比如在此函数里面call 切换镜像分区的业务逻辑
*/
void dfu_reboot()
{
drv_reboot();
}
#ifdef CONFIG_GENIE_OTA_PINGPONG
uint8_t genie_sal_ota_get_current_image_id(void)
{
return 0;
}
uint8_t genie_sal_ota_change_image_id(uint8_t target_id)
{
return 0;
}
#endif
int erase_dfu_flash(void)
{
int ret;
hal_logic_partition_t partition_info;
uint32_t offset = (SPIF_SECTOR_SIZE << 1);
uint32_t length = 0;
uint8_t cmp_buf[32] = {0xFF};
uint8_t wr_buf[32] = {0};
///get OTA temporary partition information
hal_flash_info_get(HAL_PARTITION_OTA_TEMP, &partition_info);
length = partition_info.partition_length - offset;
memset(cmp_buf, 0xFF, sizeof(cmp_buf));
ret = hal_flash_read(HAL_PARTITION_OTA_TEMP, &offset, (void *)wr_buf, sizeof(wr_buf));
if (ret < 0)
{
LOG("read flash error!!\r\n");
return -1;
}
if (memcmp(wr_buf, cmp_buf, sizeof(wr_buf)) == 0)
{
return 0;
}
LOG("OTA dirty\n");
offset = (SPIF_SECTOR_SIZE << 1);
/* For bootloader upgrade, we will reserve two sectors, then save the image */
ret = hal_flash_erase(HAL_PARTITION_OTA_TEMP, offset, length);
if (ret < 0)
{
LOG("Erase flash error!!\r\n");
return -1;
}
return 0;
}
uint32_t ali_dfu_get_ota_partition_max_size(void)
{
uint32_t reserve_size = (SPIF_SECTOR_SIZE << 1);
hal_logic_partition_t partition_info;
hal_flash_info_get(HAL_PARTITION_OTA_TEMP, &partition_info);
if (partition_info.partition_length > reserve_size)
{
return partition_info.partition_length - reserve_size;
}
return 0;
}
| YifuLiu/AliOS-Things | components/genie_service/genie_port/ali_dfu_port.c | C | apache-2.0 | 3,952 |
#ifndef _ALI_DFU_PORT_H
#define _ALI_DFU_PORT_H
#include <stdbool.h>
#define DFU_IMAGE_SIZE_MAX 240*1024
void dfu_reboot(void);
unsigned char dfu_check_checksum(short image_id, unsigned short *crc16_output);
int ali_dfu_image_update(short signature, int offset, int length, int *p_void);
/**
* @brief get the current runing partition.
* @return the current runing partition.
*/
uint8_t get_program_image(void);
/**
* @brief switch the running partition, without reboot.
* @param[in] the partition which switch to.
* @return the runing partition when next boot.
*/
uint8_t change_program_image(uint8_t dfu_image);
int erase_dfu_flash(void);
#endif
| YifuLiu/AliOS-Things | components/genie_service/genie_port/ali_dfu_port.h | C | apache-2.0 | 660 |
#ifndef _BT_MESH_CUSTOM_LOG_H_
#define _BT_MESH_CUSTOM_LOG_H_
#ifdef USE_BT_MESH_CUSTOM_LOG
#ifdef BT_DBG
#undef BT_DBG
#define BT_DBG(f, ...) printf(f "\n", ##__VA_ARGS__)
#endif
#ifdef BT_INFO
#undef BT_INFO
#define BT_INFO(f, ...) printf(f "\n", ##__VA_ARGS__)
#endif
#endif
#if defined(USE_BT_MESH_CUSTOM_LOG) || defined(USE_BT_MESH_CUSTOM_ERR_LOG)
#ifdef BT_WARN
#undef BT_WARN
#define BT_WARN(f, ...) printf("[%s]" f "\n", __func__, ##__VA_ARGS__)
#endif
#ifdef BT_ERR
#undef BT_ERR
#define BT_ERR(f, ...) printf("[%s]" f "\n", __func__, ##__VA_ARGS__)
#endif
#endif
#endif
| YifuLiu/AliOS-Things | components/genie_service/genie_port/bt_mesh_custom_log.h | C | apache-2.0 | 587 |
/*
* Copyright (C) 2019-2020 Alibaba Group Holding Limited
*/
#include <stdint.h>
#include <genie_event.h>
#include <genie_service.h>
#include "port/mesh_event_port.h"
void genie_mesh_model_event_cb(mesh_model_event_e event, void *p_arg)
{
genie_event_e genie_evt;
switch (event) {
case BT_MESH_MODEL_EVT_PROV_START:
{
genie_evt = GENIE_EVT_SDK_MESH_PROV_START;
}
break;
case BT_MESH_MODEL_EVT_PROV_DATA:
{
genie_evt = GENIE_EVT_SDK_MESH_PROV_DATA;
}
break;
case BT_MESH_MODEL_EVT_APPKEY_ADD:
{
genie_mesh_load_group_addr();
genie_mesh_setup();
genie_evt = GENIE_EVT_SDK_APPKEY_ADD;
}
break;
case BT_MESH_MODEL_EVT_APPKEY_UPDATE:
{
genie_evt = GENIE_EVT_SDK_APPKEY_UPDATE;
}
break;
case BT_MESH_MODEL_EVT_APPKEY_DEL:
{
genie_evt = GENIE_EVT_SDK_APPKEY_DEL;
}
break;
case BT_MESH_MODEL_EVT_NETKEY_ADD:
{
genie_evt = GENIE_EVT_SDK_NETKEY_ADD;
}
break;
case BT_MESH_MODEL_EVT_NETKEY_UPDATE:
{
genie_evt = GENIE_EVT_SDK_NETKEY_UPDATE;
}
break;
case BT_MESH_MODEL_EVT_NETKEY_DEL:
{
genie_evt = GENIE_EVT_SDK_NETKEY_DEL;
}
break;
case BT_MESH_MODEL_EVT_NODE_RESET_OP:
{
genie_evt = GENIE_EVT_SW_RESET;
}
break;
#if 0
case BT_MESH_MODEL_EVT_SEQ_UPDATE:
{
genie_evt = GENIE_EVT_SDK_SEQ_UPDATE;
}
break;
#endif
default:
return;
}
genie_event(genie_evt, p_arg);
return;
}
int genie_mesh_port_init(void)
{
bt_mesh_event_register(genie_mesh_model_event_cb);
return 0;
}
| YifuLiu/AliOS-Things | components/genie_service/genie_port/bt_mesh_event_port.c | C | apache-2.0 | 1,667 |
/* Bluetooth Mesh */
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef _BT_MESH_EVENT_PORT_H_
#define _BT_MESH_EVENT_PORT_H_
#include <api/mesh.h>
int genie_mesh_port_init(void);
void genie_mesh_link_open(bt_mesh_prov_bearer_t bearer);
void genie_mesh_link_close(bt_mesh_prov_bearer_t bearer);
#endif
| YifuLiu/AliOS-Things | components/genie_service/genie_port/bt_mesh_event_port.h | C | apache-2.0 | 352 |
#ifndef _GENIE_PORT_H_
#define _GENIE_PORT_H_
#define GENIE_DEBUG_COLOR
#ifdef GENIE_DEBUG_COLOR
#define F_BLACK "\033[0;30m"
#define F_RED "\033[0;31m"
#define F_GREEN "\033[0;32m"
#define F_YELLOW "\033[0;33m"
#define F_BLUE "\033[0;34m"
#define F_PURPLE "\033[0;35m"
#define F_DGREEN "\033[0;36m"
#define F_WHITE "\033[0;37m"
#define F_END "\033[0m"
#define BT_DBG_R(fmt, ...) \
if (BT_DBG_ENABLED) { \
LOGV("GENIE",F_RED "[%s]" fmt F_END, __func__, \
##__VA_ARGS__); \
}
#else
#define F_BLACK
#define F_RED
#define F_GREEN
#define F_YELLOW
#define F_BLUE
#define F_PURPLE
#define F_DGREEN
#define F_WHITE
#define F_END
#define BT_DBG_R(fmt, ...)
#endif
extern uint8_t g_mesh_log_mode;
#define printk(...) \
{ \
if(g_mesh_log_mode) { \
printf(__VA_ARGS__); \
}\
}
#define k_malloc malloc
#if defined(CONFIG_BT_DEBUG_LOG)
//#define BT_DBG(fmt, ...) SYS_LOG_DBG(fmt, ##__VA_ARGS__)
//#define BT_ERR(fmt, ...) SYS_LOG_ERR(fmt, ##__VA_ARGS__)
//#define BT_WARN(fmt, ...) SYS_LOG_WRN(fmt, ##__VA_ARGS__)
//#define BT_INFO(fmt, ...) SYS_LOG_INF(fmt, ##__VA_ARGS__)
#else
//#define BT_DBG(fmt, ...)
//#define BT_ERR BT_DBG
//#define BT_WARN BT_DBG
//#define BT_INFO BT_DBG
#endif
#ifdef GENIE_DEBUG_COLOR
//#define F_RED "\033[0;31m"
//#define F_GREEN "\033[0;32m"
//#define F_BLUE "\033[0;34m"
//#define F_END "\033[0m"
#define BT_INFO_R(fmt, ...) SYS_LOG_DBG(F_RED fmt F_END, ##__VA_ARGS__);
#define BT_INFO_G(fmt, ...) SYS_LOG_DBG(F_GREEN fmt F_END, ##__VA_ARGS__);
#define BT_INFO_B(fmt, ...) SYS_LOG_DBG(F_BLUE fmt F_END, ##__VA_ARGS__);
#else
#define F_RED
#define F_GREEN
#define F_BLUE
#define F_END
#define BT_INFO_R(fmt, ...)
#define BT_INFO_G(fmt, ...)
#define BT_INFO_B(fmt, ...)
#endif
int bt_mesh_aes_encrypt(const uint8_t key[16], const uint8_t plaintext[16],
uint8_t enc_data[16]);
int bt_mesh_aes_decrypt(const uint8_t key[16], const uint8_t enc_data[16],
uint8_t dec_data[16]);
int bt_mesh_adv_stop(void);
#define hal_malloc malloc
#define hal_free free
void genie_mesh_setup(void);
#endif
| YifuLiu/AliOS-Things | components/genie_service/genie_port/genie_port.h | C | apache-2.0 | 2,270 |
/*
* Copyright (C) 2018-2020 Alibaba Group Holding Limited
*/
#ifndef HAL_FLASH_H_
#define HAL_FLASH_H_
/**
* Write data to OTP area on a chip from data buffer in RAM
*
* @param[in] in_buf Point to the data buffer that stores the data read from flash
* @param[in] in_buf_len The length of the buffer
*
* @return 0 : On success, EIO : If an error occurred with any step
*/
int32_t hal_flash_write_triples(const void *in_buf, uint32_t in_buf_len);
/**
* Read data from OTP area on a chip to data buffer in RAM
*
* @param[in] out_buf Point to the data buffer that stores the data read from flash
* @param[in] out_buf_len The length of the buffer
*
* @return 0 : On success, EIO : If an error occurred with any step
*/
int32_t hal_flash_read_triples(void *out_buf, uint32_t out_buf_len);
/**
* Write data to OTP area on a chip from data buffer in RAM
*
* @param[in] in_buf Point to the data buffer that stores the data read from flash
* @param[in] in_buf_len The length of the buffer
*
* @return 0 : On success, EIO : If an error occurred with any step
*/
int32_t hal_flash_write_group_addr(const void *in_buf, uint32_t in_buf_len);
/**
* Read data from OTP area on a chip to data buffer in RAM
*
* @param[in] out_buf Point to the data buffer that stores the data read from flash
* @param[in] out_buf_len The length of the buffer
*
* @return 0 : On success, EIO : If an error occurred with any step
*/
int32_t hal_flash_read_group_addr(void *out_buf, uint32_t out_buf_len);
int32_t hal_flash_write_xtalcap_params(const void *in_buf, uint32_t in_buf_len);
int32_t hal_flash_read_xtalcap_params(void *out_buf, uint32_t out_buf_len);
int32_t hal_flash_read_mac_params(void *out_buf, uint32_t out_buf_len);
int32_t hal_flash_write_mac_params(const void *in_buf, uint32_t in_buf_len);
/**
* Write data to OTP area on a chip from data buffer in RAM
*
* @param[in] in_buf Point to the data buffer that stores the data read from flash
* @param[in] in_buf_len The length of the buffer
*
* @return 0 : On success, EIO : If an error occurred with any step
*/
int32_t hal_flash_write_sn_params(const void *in_buf, uint32_t in_buf_len);
/**
* Read data from OTP area on a chip to data buffer in RAM
*
* @param[in] out_buf Point to the data buffer that stores the data read from flash
* @param[in] out_buf_len The length of the buffer
*
* @return 0 : On success, EIO : If an error occurred with any step
*/
int32_t hal_flash_read_sn_params(void *out_buf, uint32_t out_buf_len);
#endif /* HAL_FLASH_H_ */
| YifuLiu/AliOS-Things | components/genie_service/genie_port/hal/flash.h | C | apache-2.0 | 2,604 |
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
//#include "soc.h"
#include "drv/spiflash.h"
//#include "dut/hal/common.h"
//#include "dut/hal/ble.h"
#include "aos/hal/flash.h"
#include "aos/kernel.h"
#include "common/log.h"
#define FLASH_ALIGN_MASK ~(sizeof(uint32_t) - 1)
#define FLASH_ALIGN sizeof(uint32_t)
//#define MAC_PARAMS_OFFSET (0)
//#define MAC_PARAMS_SIZE (0x10)
//#define RSV_PARAMS_OFFSET (MAC_PARAMS_OFFSET + MAC_PARAMS_SIZE)
//#define RSV_PARAMS_SIZE (0x10)
//#define FREQ_PARAMS_OFFSET (RSV_PARAMS_OFFSET + RSV_PARAMS_SIZE)
//#define FREQ_PARAMS_SIZE (0x8)
//#define TRIPLE_OFFSET (FREQ_PARAMS_OFFSET + FREQ_PARAMS_SIZE)
#define TRIPLE_OFFSET (0)
#define TRIPLE_SIZE (32)
#define GROUP_ADDR_OFFSET (TRIPLE_OFFSET + TRIPLE_SIZE)
#define GROUP_ADDR_SIZE (18) //CONFIG_BT_MESH_MODEL_GROUP_COUNT * 2 + 2
#define SN_PARAMS_OFFSET (GROUP_ADDR_OFFSET + GROUP_ADDR_SIZE)
#define SN_PARAMS_SIZE (32)
//#define OTP_TOTAL_DATA_SIZE (MAC_PARAMS_SIZE + RSV_PARAMS_SIZE + FREQ_PARAMS_SIZE + TRIPLE_SIZE + GROUP_ADDR_SIZE + SN_PARAMS_SIZE)
#define OTP_TOTAL_DATA_SIZE (TRIPLE_SIZE + GROUP_ADDR_SIZE + SN_PARAMS_SIZE)
int32_t hal_flash_read_otp(uint32_t off_set, void *out_buf, uint32_t out_buf_len)
{
//return dut_hal_factorydata_read(off_set, out_buf, out_buf_len);
}
int32_t hal_flash_write_otp(uint32_t off_set, const void *in_buf, uint32_t in_buf_len)
{
int32_t retval = 0;
if (off_set + in_buf_len > OTP_TOTAL_DATA_SIZE)
{
printf("param err\n");
return -1;
}
//retval = dut_hal_factorydata_store(off_set, (uint8_t *)in_buf, in_buf_len);
return retval;
}
int32_t hal_flash_read_xtalcap_params(void *out_buf, uint32_t out_buf_len)
{
uint32_t xtal_cap = 0;
int ret = -1;
if (out_buf_len != sizeof(uint32_t)) {
return -1;
}
//ret = dut_hal_xtalcap_get(&xtal_cap);
memcpy(out_buf, &xtal_cap, sizeof(uint32_t));
return ret;
}
int32_t hal_flash_write_xtalcap_params(const void *in_buf, uint32_t in_buf_len)
{
if (in_buf_len != sizeof(uint32_t)) {
return -1;
}
//return dut_hal_xtalcap_store(*((uint32_t *)in_buf));
}
int32_t hal_flash_read_sn_params(void *out_buf, uint32_t out_buf_len)
{
return hal_flash_read_otp(SN_PARAMS_OFFSET, out_buf, out_buf_len);
}
int32_t hal_flash_write_sn_params(const void *in_buf, uint32_t in_buf_len)
{
return hal_flash_write_otp(SN_PARAMS_OFFSET, in_buf, in_buf_len);
}
int32_t hal_flash_read_mac_params(void *out_buf, uint32_t out_buf_len)
{
if (!out_buf || out_buf_len < 6)
return -1;
//return dut_hal_mac_get((uint8_t *)out_buf);
}
int32_t hal_flash_write_mac_params(const void *in_buf, uint32_t in_buf_len)
{
if (!in_buf || in_buf_len != 6)
return -1;
//return dut_hal_mac_store((uint8_t *)in_buf);
}
int32_t hal_flash_read_triples(void *out_buf, uint32_t out_buf_len)
{
return hal_flash_read_otp(TRIPLE_OFFSET, out_buf, out_buf_len);
}
int32_t hal_flash_write_triples(const void *in_buf, uint32_t in_buf_len)
{
return hal_flash_write_otp(TRIPLE_OFFSET, in_buf, in_buf_len);
}
int32_t hal_flash_read_group_addr(void *out_buf, uint32_t out_buf_len)
{
return hal_flash_read_otp(GROUP_ADDR_OFFSET, out_buf, out_buf_len);
}
int32_t hal_flash_write_group_addr(const void *in_buf, uint32_t in_buf_len)
{
return hal_flash_write_otp(GROUP_ADDR_OFFSET, in_buf, in_buf_len);
}
int32_t hal_flash_add2offset(hal_partition_t *in_partition, uint32_t *off_set, uint32_t addr)
{ //partition_start_addr
hal_logic_partition_t partition_info;
int ret;
for (int i = 0; i < HAL_PARTITION_MAX; i++)
{
ret = hal_flash_info_get(i, &partition_info);
if (ret)
continue;
if ((addr >= partition_info.partition_start_addr) && (addr < (partition_info.partition_start_addr + partition_info.partition_length)))
{
*in_partition = i;
*off_set = addr - partition_info.partition_start_addr;
return 0;
}
}
*in_partition = -1;
*off_set = 0;
return -1;
}
void hal_flash_write_test()
{
int ret = 0;
uint32_t offset = 0;
uint8_t data[32] = {0};
uint8_t data_read[32] = {0};
int i = 0;
for (i = 0; i < sizeof(data); i++)
{
data[i] = i;
}
hal_flash_erase(HAL_PARTITION_PARAMETER_2, 0, 4096);
offset = 0;
//printf("write test 32 by 32 %d, offset %d size %d, data %p\n", HAL_PARTITION_PARAMETER_2, offset, 4096, data);
for (i = 0; i < 4096 / 32; i++)
{
ret = hal_flash_write(HAL_PARTITION_PARAMETER_2, &offset, (uint8_t *)(data), 32);
if (ret)
{
printf("write 1 fail %d\n", ret);
break;
}
}
offset = 0;
memset(data_read, 0, 32);
for (i = 0; i < 4096 / 32; i++)
{
memset(data_read, 0, 32);
ret = hal_flash_read(HAL_PARTITION_PARAMETER_2, &offset, (uint8_t *)(data_read), 32);
if (ret)
{
printf("read 1 fail %d\n", ret);
break;
}
if (memcmp(data, data_read, 32))
{
printf("write test fail, data missmatch\n");
break;
}
}
hal_flash_erase(HAL_PARTITION_PARAMETER_2, 0, 4096);
offset = 0;
//printf("write test 1 by 1 %d, offset %d size %d, data %p\n", HAL_PARTITION_PARAMETER_2, offset, 4096, data);
for (i = 0; i < 4096; i++)
{
ret = hal_flash_write(HAL_PARTITION_PARAMETER_2, &offset, (uint8_t *)(data + i % 32), 1);
if (ret)
{
printf("write 2 fail %d\n", ret);
break;
}
}
offset = 0;
memset(data_read, 0, 32);
for (i = 0; i < 4096; i++)
{
ret = hal_flash_read(HAL_PARTITION_PARAMETER_2, &offset, (uint8_t *)(data_read + i % 32), 1);
if (ret)
{
printf("read 2 fail %d\n", ret);
break;
}
if ((i + 1) % 32 == 0)
{
if (memcmp(data, data_read, 32))
{
printf("write 2 1 by 1 test fail, data missmatch\n");
break;
}
memset(data_read, 0, 32);
}
}
hal_flash_erase(HAL_PARTITION_PARAMETER_2, 0, 4096);
}
| YifuLiu/AliOS-Things | components/genie_service/genie_port/hal/genie_hal_flash.c | C | apache-2.0 | 6,333 |
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef HAL_HAL_H_
#define HAL_HAL_H_
#include <stdint.h>
#include <stddef.h>
#include <aos/hal/timer.h>
#include <aos/hal/gpio.h>
#include <hal/flash.h>
#include <genie_port.h>
#endif /* HAL_HAL_H */
| YifuLiu/AliOS-Things | components/genie_service/genie_port/hal/hal.h | C | apache-2.0 | 271 |
/*
* Copyright (C) 2018-2020 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
//#include <aos/aos.h>
#include <aos/kernel.h>
#include <misc/printk.h>
#include <hal/hal.h>
#include "genie_service.h"
static genie_service_ctx_t genie_service_ctx;
static int genie_service_check_ctx(genie_service_ctx_t *p_ctx)
{
if (!p_ctx || !p_ctx->event_cb || !p_ctx->p_mesh_elem || p_ctx->mesh_elem_counts < 1)
{
GENIE_LOG_ERR("ctx:%p %p %p %d", p_ctx, p_ctx->event_cb, p_ctx->p_mesh_elem, p_ctx->mesh_elem_counts);
return -1;
}
memset(&genie_service_ctx, 0, sizeof(genie_service_ctx_t));
memcpy(&genie_service_ctx, p_ctx, sizeof(genie_service_ctx_t));
return 0;
}
genie_service_ctx_t *genie_service_get_context(void)
{
return &genie_service_ctx;
}
int genie_service_init(genie_service_ctx_t *p_ctx)
{
int ret = 0;
GENIE_LOG_ERR("genie service init");
if (genie_service_check_ctx(p_ctx) < 0)
{
GENIE_LOG_ERR("genie service context error");
return GENIE_SERVICE_ERRCODE_USER_INPUT;
}
genie_storage_init();
genie_cli_init();
#if defined(CONIFG_GENIE_MESH_BINARY_CMD) || defined(CONFIG_GENIE_MESH_AT_CMD)
genie_sal_uart_init();
#endif
genie_reset_init();
genie_transport_init();
#ifdef CONFIG_GENIE_MESH_GLP
p_ctx->lpm_conf.sleep_ms = GENIE_GLP_SLEEP_TIME;
p_ctx->lpm_conf.wakeup_ms = GENIE_GLP_WAKEUP_TIME;
#endif
#ifdef CONFIG_PM_SLEEP
genie_lpm_init(&p_ctx->lpm_conf);
#endif
if (genie_triple_init() < 0)
{
#ifdef CONFIG_PM_SLEEP
genie_sal_sleep_disable();
#endif
return GENIE_SERVICE_ERRCODE_NO_TRIPLE;
}
ret = genie_mesh_init(genie_service_ctx.p_mesh_elem, genie_service_ctx.mesh_elem_counts);
if (ret != 0)
{
GENIE_LOG_ERR("genie service init fail(%d)", ret);
return GENIE_SERVICE_ERRCODE_MESH_INIT;
}
else
{
return GENIE_SERVICE_SUCCESS;
}
}
| YifuLiu/AliOS-Things | components/genie_service/genie_service.c | C | apache-2.0 | 1,985 |
/*
* Copyright (C) 2018-2020 Alibaba Group Holding Limited
*/
#ifndef _GENIE_SERVICE_H_
#define _GENIE_SERVICE_H_
#include "ulog/ulog.h"
//#include <aos/aos.h>
//#include <soc.h>
#include <hal/hal.h>
#include <aos/hal/gpio.h>
#include "core/inc/genie_event.h"
#include "core/inc/genie_cli.h"
#include "core/inc/genie_at.h"
#include "core/inc/genie_bin_cmds.h"
#include "core/inc/genie_storage.h"
#include "core/inc/genie_reset.h"
#include "core/inc/genie_triple.h"
#include "core/inc/genie_addr.h"
#include "core/inc/genie_version.h"
#ifdef CONFIG_GENIE_OTA
#include "sal/inc/genie_sal_ota.h"
#include "core/inc/genie_ais.h"
#include "core/inc/genie_ota.h" //Please keep genie_ais.h is upper of genie_ota.h because ota depend ais
#endif
#include "core/inc/genie_transport.h"
#include "core/inc/genie_vendor_model.h"
#include "core/inc/genie_provision.h"
#include "core/inc/genie_crypto.h"
#ifdef CONFIG_PM_SLEEP
#include "core/inc/genie_lpm.h"
#include "genie_sal_lpm.h"
#endif
#ifdef MESH_MODEL_VENDOR_TIMER
#include "core/inc/genie_time.h"
#endif
#include "sal/inc/genie_sal_ble.h"
#include "sal/inc/genie_sal_uart.h"
#include "core/inc/sig_models/sig_model.h"
#include "core/inc/genie_mesh.h"
#define GENIE_SERVICE_TAG "Genie_service"
#define GENIE_LOG_ERR(fmt, ...) LOGE(GENIE_SERVICE_TAG, fmt, ##__VA_ARGS__)
#define GENIE_LOG_WARN(fmt, ...) LOGW(GENIE_SERVICE_TAG, fmt, ##__VA_ARGS__)
#define GENIE_LOG_INFO(fmt, ...) LOGI(GENIE_SERVICE_TAG, fmt, ##__VA_ARGS__)
#define GENIE_LOG_DBG(fmt, ...) LOGD(GENIE_SERVICE_TAG, fmt, ##__VA_ARGS__)
#define GENIE_GLP_SLEEP_TIME (1100) //unit:ms
#define GENIE_GLP_WAKEUP_TIME (60) //unit:ms
#define GENIE_SERVICE_ERRCODE_USER_BASE (-0x100)
#define GENIE_SERVICE_ERRCODE_MESH_BASE (-0x200)
#define GENIE_SERVICE_ERRCODE_TRIPLE_BASE (-0x300)
typedef enum _genie_service_errcode_s
{
GENIE_SERVICE_SUCCESS = 0,
GENIE_SERVICE_ERRCODE_USER_INPUT = GENIE_SERVICE_ERRCODE_USER_BASE - 1,
GENIE_SERVICE_ERRCODE_MESH_INIT = GENIE_SERVICE_ERRCODE_MESH_BASE - 1,
GENIE_SERVICE_ERRCODE_NO_TRIPLE = GENIE_SERVICE_ERRCODE_MESH_BASE - 2,
GENIE_SERVICE_ERRCODE_TRIPLE_READ_FAIL = GENIE_SERVICE_ERRCODE_TRIPLE_BASE - 1,
GENIE_SERVICE_ERRCODE_TRIPLE_WRITE_FAIL = GENIE_SERVICE_ERRCODE_TRIPLE_BASE - 2,
} genie_service_errcode;
typedef void (*user_event_cb)(genie_event_e event, void *p_arg);
typedef struct _genie_service_ctx_s
{
struct bt_mesh_elem *p_mesh_elem;
unsigned char mesh_elem_counts;
user_event_cb event_cb;
uint32_t prov_timeout;
#ifdef CONFIG_PM_SLEEP
genie_lpm_conf_t lpm_conf;
#endif
} genie_service_ctx_t;
/**
* @brief The initialization api for genie sdk. The application always
* involks this api to initialize AIS/Mesh procedure for bussiness.
*/
int genie_service_init(genie_service_ctx_t *p_ctx);
genie_service_ctx_t *genie_service_get_context(void);
#endif
| YifuLiu/AliOS-Things | components/genie_service/genie_service.h | C | apache-2.0 | 2,881 |
#ifndef __GENIE_SAL_BLE_H__
#define __GENIE_SAL_BLE_H__
#define GENIE_HAL_BLE_SEND_MAX_DATA_LEN (92)
#define GENIE_HAL_BLE_SCAN_TIMEOUT (5000)
extern uint8_t g_mesh_log_mode;
typedef void (*genie_sal_ble_get_rssi_cb)(unsigned char mac[], int16_t rssi);
int genie_sal_ble_get_rssi(uint8_t mac[], genie_sal_ble_get_rssi_cb get_rssi_callback, uint32_t timeout);
int genie_sal_ble_send_msg(uint8_t element_id, uint8_t *p_data, uint8_t len);
int genie_sal_ble_set_factory_flag(void);
int genie_sal_ble_init(void);
#endif
| YifuLiu/AliOS-Things | components/genie_service/sal/inc/genie_sal_ble.h | C | apache-2.0 | 520 |
#ifndef __GENIE_SAL_LPM_H__
#define __GENIE_SAL_LPM_H__
#include <types.h>
typedef void (*genie_io_wakeup_cb)(void *arg);
enum io_pol
{
FALLING = 0,
RISING = 1,
ACT_LOW = 2,
ACT_HIGH = 3,
};
void genie_sal_sleep_enable();
void genie_sal_sleep_disable();
int genie_sal_sleep_enter_standby();
int genie_sal_sleep_wakup_io_set(uint8_t port, uint8_t pol);
bool genie_sal_sleep_wakeup_io_get_status(uint8_t port);
int genie_sal_io_wakeup_cb_register(genie_io_wakeup_cb cb);
int genie_sal_io_wakeup_cb_unregister();
#endif
| YifuLiu/AliOS-Things | components/genie_service/sal/inc/genie_sal_lpm.h | C | apache-2.0 | 537 |
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#ifndef __GENIE_SAL_OTA_H__
#define __GENIE_SAL_OTA_H__
#include <stdbool.h>
#ifndef CONFIG_AIS_TOTAL_FRAME
#define CONFIG_AIS_TOTAL_FRAME 16
#endif
/**
* @brief reboot the device.
*/
void hal_reboot(void);
/**
* @brief finish ota and reboot the device.
*/
void dfu_reboot(void);
/**
* @brief check the dfu image.
* @param[in] the image type.
* @param[out] the crc of image.
* @return the result of checksum.
*/
unsigned char dfu_check_checksum(short image_id, unsigned short *crc16_output);
/**
* @brief write dfu data.
* @param[in] the image type.
* @param[in] the offset of flash.
* @param[in] the length of data.
* @param[in] the writting data.
* @return the current runing partition.
*/
int ali_dfu_image_update(short signature, int offset, int length, int *p_void);
uint32_t ali_dfu_get_ota_partition_max_size(void);
#ifdef CONFIG_GENIE_OTA_PINGPONG
/**
* @brief get the current runing partition.
* @return the current runing partition.
*/
uint8_t genie_sal_ota_get_program_image(void);
/**
* @brief switch the running partition, without reboot.
* @param[in] the partition which switch to.
* @return the runing partition when next boot.
*/
uint8_t genie_sal_ota_change_image_id(uint8_t target_id);
#endif
int erase_dfu_flash(void);
/*This api mainly for light product,if light is on we shouldn't reboot by ota*/
bool genie_sal_ota_is_allow_reboot(void);
#endif
| YifuLiu/AliOS-Things | components/genie_service/sal/inc/genie_sal_ota.h | C | apache-2.0 | 1,466 |
#ifndef __GENIE_SAL_UART_H__
#define __GENIE_SAL_UART_H__
#include "ulog/ulog.h"
#ifndef GENIE_MESH_DEFAULT_LOG_LEVEL
#define GENIE_MESH_DEFAULT_LOG_LEVEL LOG_DEBUG
#endif
int genie_sal_uart_init(void);
int32_t genie_sal_uart_send_one_byte(uint8_t byte);
int32_t genie_sal_uart_send_str(const char *fmt, ...);
#endif
| YifuLiu/AliOS-Things | components/genie_service/sal/inc/genie_sal_uart.h | C | apache-2.0 | 320 |
#include <stdint.h>
#include <hal/hal.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/hci.h>
//#include <aos/aos.h>
#include <aos/kv.h>
#include "adv.h"
#include "common/log.h"
#include "genie_service.h"
#include "genie_sal_ble.h"
static aos_sem_t scan_sem;
static genie_sal_ble_get_rssi_cb get_rssi_cb = NULL;
static uint8_t test_dev_mac[6] = {0};
extern int hci_driver_init(void);
void mesh_scan_cb(const bt_addr_le_t *addr, int8_t rssi,
uint8_t adv_type, struct net_buf_simple *buf)
{
uint8_t mac_addr[6] = {0};
if (buf == NULL || addr == NULL)
{
return;
}
//printf("addr->a.val: %s, rssi: %d\n", bt_hex(addr->a.val, sizeof(addr->a.val)), rssi);
sys_memcpy_swap(mac_addr, addr->a.val, 6);
if (memcmp(test_dev_mac, mac_addr, sizeof(test_dev_mac)) == 0)
{
bt_mesh_scan_disable();
bt_mesh_scan_enable();
memset(test_dev_mac, 0, sizeof(test_dev_mac));
if (get_rssi_cb)
{
get_rssi_cb(mac_addr, rssi);
}
aos_sem_signal_all(&scan_sem);
}
}
static void scan_timeout(void)
{
printf("scan timeout\r\n");
bt_mesh_scan_disable();
bt_mesh_scan_enable();
memset(test_dev_mac, 0, sizeof(test_dev_mac));
if (get_rssi_cb)
{
get_rssi_cb(test_dev_mac, 0);
}
}
int genie_sal_ble_get_rssi(uint8_t mac[6], genie_sal_ble_get_rssi_cb get_rssi_callback, uint32_t timeout)
{
struct bt_le_scan_param scan_param = {
.type = BT_HCI_LE_SCAN_PASSIVE,
.filter_dup = BT_HCI_LE_SCAN_FILTER_DUP_DISABLE,
.interval = 0x10,
.window = 0x10};
if (get_rssi_callback == NULL)
{
return -1;
}
if (0 != aos_sem_new(&scan_sem, 0))
{
printf("new sem fail\r\n");
return -1;
}
memcpy(test_dev_mac, mac, sizeof(test_dev_mac));
printf("scan mac:%s\n", bt_hex(test_dev_mac, sizeof(test_dev_mac)));
get_rssi_cb = get_rssi_callback;
bt_mesh_scan_disable();
int ret = bt_le_scan_start(&scan_param, mesh_scan_cb);
if (ret)
{
printf("scan err:%d\n", ret);
memset(test_dev_mac, 0, sizeof(test_dev_mac));
if (get_rssi_cb)
{
get_rssi_cb(test_dev_mac, 0);
}
aos_sem_free(&scan_sem);
return -1;
}
if (-ETIMEDOUT == aos_sem_wait(&scan_sem, timeout))
{
scan_timeout();
}
aos_sem_free(&scan_sem);
return 0;
}
int genie_sal_ble_send_msg(uint8_t element_id, uint8_t *p_data, uint8_t len)
{
int ret = -1;
uint8_t i = 0;
uint8_t seg_count = 0;
struct bt_mesh_model *p_model = NULL;
struct net_buf_simple *msg = NULL;
struct bt_mesh_msg_ctx ctx;
struct bt_mesh_elem *p_element = NULL;
genie_transport_model_param_t request_msg;
if (len > GENIE_HAL_BLE_SEND_MAX_DATA_LEN)
{
return -1;
}
p_element = bt_mesh_elem_find_by_id(element_id);
if (p_element == NULL)
{
printf("not find element by id:%d\r\n", element_id);
return -1;
}
if ((len >= 4) && (p_data[0] == VENDOR_OP_ATTR_INDICATE || p_data[0] == VENDOR_OP_ATTR_INDICATE_TG))
{
seg_count = genie_transport_get_seg_count(len - 4 + 4);
memset(&request_msg, 0, sizeof(genie_transport_model_param_t));
request_msg.opid = p_data[0];
request_msg.tid = p_data[3];
request_msg.data = (u8_t *)(p_data + 4);
request_msg.len = len - 4;
request_msg.p_elem = p_element;
request_msg.retry_period = GENIE_TRANSPORT_EACH_PDU_TIMEOUT * seg_count;
request_msg.retry = VENDOR_MODEL_MSG_MAX_RETRY_TIMES;
ret = genie_transport_send_model(&request_msg);
if (ret != 0)
{
printf("vendor model msg send fail\n");
return -1;
}
return 0;
}
else
{
ctx.app_idx = 0;
ctx.net_idx = 0;
ctx.addr = genie_transport_src_addr_get();
ctx.send_ttl = GENIE_TRANSPORT_DEFAULT_TTL;
ctx.send_rel = 0;
msg = NET_BUF_SIMPLE(GENIE_HAL_BLE_SEND_MAX_DATA_LEN + 4);
if (msg == NULL)
{
printf("no mem\n");
return -1;
}
net_buf_simple_init(msg, 0);
while (i < len)
{
net_buf_simple_add_u8(msg, p_data[i]);
i++;
}
if ((p_data[0] & 0xC0) == 0xC0)
{
p_model = p_element->vnd_models;
}
else
{
p_model = p_element->models;
}
if (p_model == NULL)
{
printf("no model\n");
return -1;
}
if (bt_mesh_model_send(p_model, &ctx, msg, NULL, NULL))
{
printf("mesh send fail\n");
return -1;
}
return 0;
}
}
int genie_sal_ble_set_factory_flag(void)
{
int ret = -1;
uint16_t flag = 0xAA55;
ret = aos_kv_set("FTST", &flag, sizeof(uint16_t), 0);
if (ret != 0)
{
printf("write FTST flag error\n");
return ret;
}
return 0;
}
int genie_sal_ble_init(void)
{
return hci_driver_init();
}
| YifuLiu/AliOS-Things | components/genie_service/sal/src/genie_sal_ble.c | C | apache-2.0 | 5,134 |
#include <stdint.h>
#include <string.h>
#include <types.h>
#include <hal/hal.h>
#include <pm.h>
#include <genie_sal_lpm.h>
#if defined(BOARD_TG7100B) || defined(BOARD_PHY6220_EVB) || defined(BOARD_TG7120B_EVB)
#include "gpio.h"
#endif
extern void drv_pm_sleep_enable();
extern void drv_pm_sleep_disable();
extern int drv_pm_enter_standby();
void genie_sal_sleep_enable()
{
drv_pm_sleep_enable();
}
void genie_sal_sleep_disable()
{
drv_pm_sleep_disable();
}
int genie_sal_sleep_enter_standby()
{
return drv_pm_enter_standby();
}
int genie_sal_sleep_wakup_io_set(uint8_t port, uint8_t pol)
{
#if defined(BOARD_TG7100B) || defined(BOARD_PHY6220_EVB) || defined(BOARD_TG7120B_EVB)
uint8_t type = (pol >= 2) ? pol - 2 : pol;
phy_gpio_pull_set(port, !type);
phy_gpio_wakeup_set(port, type);
return 0;
#endif
return -1;
}
__attribute__((section(".__sram.code"))) bool genie_sal_sleep_wakeup_io_get_status(uint8_t port)
{
#if defined(BOARD_TG7100B) || defined(BOARD_PHY6220_EVB) || defined(BOARD_TG7120B_EVB)
return phy_gpio_read(port);
#endif
return 0;
}
int genie_sal_io_wakeup_cb_register(genie_io_wakeup_cb cb)
{
if (!cb)
{
return -1;
}
drv_pm_io_wakeup_handler_register(cb);
return 0;
}
int genie_sal_io_wakeup_cb_unregister()
{
drv_pm_io_wakeup_handler_unregister();
return 0;
}
| YifuLiu/AliOS-Things | components/genie_service/sal/src/genie_sal_lpm.c | C | apache-2.0 | 1,342 |
#include <stdint.h>
#include <string.h>
#include <stdio.h>
#include <hal/hal.h>
#include <k_api.h>
#include <aos/hal/uart.h>
#include <aos/kernel.h>
#define GENIE_MCU_UART_PORT (1)
#define GENIE_MCU_UART_BAUDRATE (9600)
#define FRAME_BUFFER_SIZE (256)
#define SEND_BUFFER_SIZE (64)
#define FRAME_TIEMOUT (50) //unit ms
static uart_dev_t mcu_uart, *p_mcu_uart = NULL;
static unsigned char frame_buff_index = 0;
static unsigned char frame_buff[FRAME_BUFFER_SIZE];
static aos_timer_t uart_frame_end_timer;
extern int genie_at_cmd_parser(char data[]);
extern int genie_bin_cmds_handle(uint8_t *p_data, uint8_t data_len);
static void uart_frame_end_timer_cb(void *arg1, void *arg2)
{
if (frame_buff_index > 0) //received some datas
{
#ifdef CONIFG_GENIE_MESH_BINARY_CMD
genie_bin_cmds_handle(frame_buff, frame_buff_index);
#endif
#ifdef CONFIG_GENIE_MESH_AT_CMD
genie_at_cmd_parser((char *)frame_buff);
#endif
frame_buff_index = 0; //reset this index
memset(frame_buff, 0, FRAME_BUFFER_SIZE);
}
}
int genie_sal_uart_init(void)
{
memset(frame_buff, 0, FRAME_BUFFER_SIZE);
mcu_uart.port = GENIE_MCU_UART_PORT;
mcu_uart.config.baud_rate = GENIE_MCU_UART_BAUDRATE;
mcu_uart.config.mode = MODE_TX_RX;
mcu_uart.config.flow_control = FLOW_CONTROL_DISABLED;
mcu_uart.config.stop_bits = STOP_BITS_1;
mcu_uart.config.parity = NO_PARITY;
mcu_uart.config.data_width = DATA_WIDTH_8BIT;
if (0 != hal_uart_init(&mcu_uart))
{
printf("uart(%d) init fail\r\n", GENIE_MCU_UART_PORT);
return -1;
}
else
{
p_mcu_uart = &mcu_uart;
}
return aos_timer_new(&uart_frame_end_timer, uart_frame_end_timer_cb, NULL, FRAME_TIEMOUT, 0);
}
int32_t genie_sal_uart_send_one_byte(uint8_t byte)
{
uint8_t send_data = 0;
if (p_mcu_uart == NULL)
{
printf("uart(%d) not init\r\n", GENIE_MCU_UART_PORT);
return -1;
}
send_data = byte;
return hal_uart_send(p_mcu_uart, &send_data, 1, 0);
}
int32_t genie_sal_uart_send_str(const char *fmt, ...)
{
int ret = 0;
va_list params;
int8_t send_buff[SEND_BUFFER_SIZE];
if (p_mcu_uart == NULL)
{
printf("uart(%d) not init\r\n", GENIE_MCU_UART_PORT);
return -1;
}
va_start(params, fmt);
memset(send_buff, 0, SEND_BUFFER_SIZE);
ret = vsnprintf((char *)send_buff, SEND_BUFFER_SIZE - 1, fmt, params);
va_end(params);
if (ret <= 0)
{
printf("uart(%d) send fail,no mem\r\n", GENIE_MCU_UART_PORT);
return -1;
}
if (0 != hal_uart_send(p_mcu_uart, (void *)send_buff, (uint32_t)strlen((const char *)send_buff), HAL_WAIT_FOREVER))
{
printf("uart(%d) send fail\r\n", GENIE_MCU_UART_PORT);
return -1;
}
return 0;
}
int genie_sal_uart_read(uint32_t timeout)
{
int8_t read_buff;
int32_t ret = 0;
uint32_t recv_size = 0;
if (p_mcu_uart == NULL)
{
printf("uart(%d) not init\r\n", GENIE_MCU_UART_PORT);
return -1;
}
ret = hal_uart_recv_II(p_mcu_uart, &read_buff, 1, &recv_size, timeout);
if ((ret == 0) && (recv_size == 1))
{
if (frame_buff_index > FRAME_BUFFER_SIZE)
{
frame_buff_index = 0;
}
frame_buff[frame_buff_index++] = read_buff;
aos_timer_stop(&uart_frame_end_timer);
aos_timer_start(&uart_frame_end_timer);
}
return 0;
}
| YifuLiu/AliOS-Things | components/genie_service/sal/src/genie_sal_uart.c | C | apache-2.0 | 3,536 |
NAME := crc
$(NAME)_MBINS_TYPE := kernel
$(NAME)_SOURCES := crc16.c \
crc32.c
GLOBAL_INCLUDES += include
| YifuLiu/AliOS-Things | components/genie_service/utility/crc/crc.mk | Makefile | apache-2.0 | 137 |