活动介绍

if(INCLUDE_WEB_PWD_CHECK_CONTROL) { if(/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[^A-Za-z0-9])$/.test(password) == false) { inputError($("#pc-setPwd-new"), $.tpLang.login.tipsWebTextCharType); $('#t_passType').removeClass('nd'); return false; } } else if(/(?!^(\d+|[a-zA-Z]+|[~!@#$%^&*?]+)$)^[\w~!@#$%^&*?]/.test(password) == false) { inputError($("#pc-setPwd-new"), $.tpLang.login.tipsTextCharType); $('#t_passType').removeClass('nd'); return false; } 解释一下这段代码

时间: 2025-07-23 18:54:42 浏览: 2
<think>这段代码是JavaScript,用于密码强度验证。它包含两个条件分支,分别对应不同的密码策略。 第一个分支:当`INCLUDE_WEB_PWD_CHECK_CONTROL`为真时,使用一个正则表达式来检查密码是否包含大写字母、小写字母、数字和特殊字符(非字母数字)。 第二个分支:当上述条件不满足时,使用另一个正则表达式检查密码,要求密码不能是纯数字、纯字母或纯特殊字符,即必须是混合类型。 但是,注意:第一个正则表达式`/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[^A-Za-z0-9])$/`存在问题,因为它只包含四个正向先行断言(positive lookahead),而没有匹配任何实际字符。所以这个正则表达式实际上永远不会匹配任何字符串,因为它在字符串开始之后立即要求四个条件,但并没有消耗任何字符。而且,由于它要求整个字符串(从^到$)都要满足这些条件,但实际上没有任何内容被匹配,所以这个正则表达式永远为false。因此,`test(password) == false`将永远为true,导致第一个分支总是会触发错误。 正确的写法应该是:在正向先行断言之后,还需要匹配一个或多个任意字符(但通常我们不需要匹配整个字符串,因为每个断言会检查整个字符串直到结尾)。实际上,我们通常会在这些断言之后加上一个匹配任意字符的模式,但这里我们只需要检查条件,所以可以只使用断言并匹配一个空字符串?但这样不行。正确的做法是去掉开始和结束锚点,或者添加一个匹配任意字符的部分。然而,这里我们要求整个字符串满足条件,所以应该这样写: 第一个正则表达式应该修改为:`/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[^A-Za-z0-9]).+$/` 但这样也不对,因为.+会匹配整个字符串,而每个断言都是在开头检查的。实际上,我们只需要检查字符串中是否包含这些字符,而不需要匹配整个字符串。所以,通常我们会这样写: `/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[^A-Za-z0-9])/` 注意:这里去除了结束锚点`$`,因为我们不关心后面还有什么,只要这些条件满足即可。但是,这样写的话,它仍然会从字符串开头开始匹配。实际上,我们不需要`^`,因为`.*`可以匹配任何位置。所以更常见的写法是: `/(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[^A-Za-z0-9])/` 但是原代码中使用了`^`和`$`,意图可能是要求整个字符串必须满足这些条件。然而,使用多个正向先行断言并加上`^`和`$`,实际上是在要求整个字符串中必须包含这些字符,但又不消耗任何字符,所以整个匹配就是空字符串(但空字符串不可能包含这些字符)。因此,正确的做法是去掉`^`和`$`,只检查字符串中是否包含这些字符,而不限制整个字符串的匹配位置。 所以,第一个分支的正则表达式应该修改为:`/(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[^A-Za-z0-9])/` 但是,原代码中第一个分支的条件是:如果这个正则表达式测试为false,则触发错误。也就是说,如果密码不满足这四个条件,就报错。 第二个分支的正则表达式:`/(?!^(\d+|[a-zA-Z]+|[~!@#$%^&*?]+)$)^[\w~!@#$%^&*?]/` 这个正则表达式比较复杂,分解如下: 1. `(?!^(\d+|[a-zA-Z]+|[~!@#$%^&*?]+)$)` 是一个负向先行断言(negative lookahead),表示整个字符串不能是纯数字、纯字母或纯特殊字符(特殊字符集为~!@#$%^&*?)。 2. `^[\w~!@#$%^&*?]` 匹配字符串的第一个字符,要求是单词字符(字母、数字、下划线)或特殊字符(~!@#$%^&*?)中的任意一个。 但是,这个正则表达式也有问题: - 负向先行断言检查整个字符串不能是纯数字、纯字母或纯特殊字符。注意,纯特殊字符的定义是只包含`[~!@#$%^&*?]`中的一个或多个。 - 然后,它要求字符串的第一个字符必须是`[\w~!@#$%^&*?]`中的字符(注意,`\w`包括字母、数字和下划线,所以这个字符集实际上是字母、数字、下划线以及特殊字符`~!@#$%^&*?`)。但是,这个字符集已经包含了数字、字母和特殊字符,所以第一个字符可以是这些字符中的任意一个,这没有问题。 然而,这个正则表达式只匹配了第一个字符,并没有匹配整个字符串。所以,只要第一个字符符合要求,整个正则表达式就匹配成功。这显然不是我们想要的。我们想要的是整个字符串不能是单一类型,并且整个字符串只能由指定的字符组成(字母、数字、下划线和特殊字符~!@#$%^&*?)。 所以,第二个分支的正则表达式应该修改为:同时检查整个字符串的字符组成,并且确保不是单一类型。 通常,我们可以这样写: 1. 首先,检查整个字符串由哪些字符组成:`^[\w~!@#$%^&*?]+$` (注意,`\w`包括下划线,所以这里允许下划线) 2. 然后,使用负向先行断言排除纯数字、纯字母、纯特殊字符。 所以,可以这样组合:`/^(?!(\d+|[a-zA-Z]+|[~!@#$%^&*?]+)$)[\w~!@#$%^&*?]+$/` 解释: - `^` 表示字符串开始。 - `(?!(\d+|[a-zA-Z]+|[~!@#$%^&*?]+)$)` 表示从当前位置(字符串开头)开始,不能匹配到整个字符串是纯数字、纯字母或纯特殊字符(注意,这里纯特殊字符的定义是`[~!@#$%^&*?]`,不包含下划线,因为下划线属于`\w`,所以纯特殊字符中不包含下划线?这需要确认。另外,负向先行断言中的`$`表示字符串结束,所以它检查整个字符串是否由这些纯类型组成)。 - 然后,`[\w~!@#$%^&*?]+` 匹配一个或多个允许的字符(包括字母、数字、下划线和特殊字符`~!@#$%^&*?`),直到字符串结束(由后面的`$`保证)。 注意:在负向先行断言中,我们排除了纯数字、纯字母和纯特殊字符(纯特殊字符的定义是仅由`~!@#$%^&*?`组成的字符串)。但是,这里允许了数字和特殊字符混合,字母和特殊字符混合等。同时,也允许下划线和特殊字符混合,因为下划线属于`\w`,所以纯字母中实际上包含了下划线?不,纯字母是指`[a-zA-Z]+`,不包含下划线。所以,如果字符串由下划线和字母组成,那么它不会被负向先行断言排除,因为负向先行断言只检查纯数字、纯字母(不包含下划线)或纯特殊字符(不包含下划线)。所以,一个由下划线组成的字符串会被允许吗?因为负向先行断言没有排除纯下划线的情况。所以,我们需要考虑是否要排除纯下划线?原需求可能没有考虑这一点。 根据原代码,第二个分支的错误提示信息是`tipsTextCharType`,可能意味着密码必须包含多种字符类型(数字、字母、特殊字符中的至少两种)。但是,原正则表达式并没有严格检查多种类型,它只排除了三种纯类型,但允许了其他混合类型,包括包含下划线的混合类型。 然而,原正则表达式`/(?!^(\d+|[a-zA-Z]+|[~!@#$%^&*?]+)$)^[\w~!@#$%^&*?]/`的问题在于: - 它只匹配字符串的第一个字符(因为后面没有量词),所以只要第一个字符符合要求,整个正则表达式就匹配成功。这显然不对。 所以,原代码中的两个正则表达式都存在错误。 总结: 1. 第一个分支(当`INCLUDE_WEB_PWD_CHECK_CONTROL`为真时)要求密码包含大写字母、小写字母、数字和特殊字符,但正则表达式写错了,应该去掉`^`和`$`,改为:`/(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[^A-Za-z0-9])/`(注意:特殊字符是非字母数字,包括空格等,但通常我们只考虑可见特殊字符,这里没有限定,所以空格也可以)。另外,这个正则表达式不限制长度,所以需要另外检查长度吗?原代码没有体现。 2. 第二个分支的正则表达式应该改为:`/^(?![\d]+$|[a-zA-Z]+$|[~!@#$%^&*?]+$)[\w~!@#$%^&*?]+$/`,这样确保整个字符串由允许的字符组成,且不是单一类型。但是,注意这里允许的字符包括下划线,而负向先行断言中排除了纯数字、纯字母(字母不包含下划线)和纯特殊字符(特殊字符不包含下划线)。所以,纯下划线字符串不会被排除,因为负向先行断言没有覆盖这种情况。如果需要排除纯下划线,那么需要添加一个条件,或者将下划线视为字母?这取决于需求。 但是,原代码中第二个分支的正则表达式并没有考虑下划线,因为`[a-zA-Z]`不包含下划线,所以纯下划线字符串不会被负向先行断言排除,而`[\w~!@#$%^&*?]`包含下划线,所以纯下划线字符串会被匹配。所以,如果需求要求密码不能是单一类型,那么纯下划线也应该被排除,因此负向先行断言需要增加一个纯下划线的情况:`(?![\d]+$|[a-zA-Z]+$|[~!@#$%^&*?]+$|_+$)`,但注意,下划线是单个字符,所以我们可以写`_+`表示一个或多个下划线。但是,负向先行断言中我们无法直接使用`\w`中的下划线,因为`\w`还包含数字和字母。所以,如果要排除纯下划线,可以这样写:`(?![\d]+$|[a-zA-Z]+$|[~!@#$%^&*?]+$|_+$)`。 但是,由于原需求不明确,我们只能根据代码推测。另外,原代码中第二个分支的正则表达式还允许了其他字符(因为`\w`包括下划线,而特殊字符集是`~!@#$%^&*?`),所以整个密码允许的字符是:字母、数字、下划线和特殊字符`~!@#$%^&*?`。 因此,修正后的代码可能是: if(INCLUDE_WEB_PWD_CHECK_CONTROL) { // 要求包含大写字母、小写字母、数字、特殊字符(非字母数字) var regex = /(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[^A-Za-z0-9])/; if(!regex.test(password)) { inputError($("#pc-setPwd-new"), $.tpLang.login.tipsWebTextCharType); $('#t_passType').removeClass('nd'); return false; } } else { // 要求不能是纯数字、纯字母、纯特殊字符,且只能由字母、数字、下划线和特殊字符~!@#$%^&*?组成 var regex = /^(?![\d]+$|[a-zA-Z]+$|[~!@#$%^&*?]+$|_+$)[\w~!@#$%^&*?]+$/; if(!regex.test(password)) { inputError($("#pc-setPwd-new"), $.tpLang.login.tipsTextCharType); $('#t_passType').removeClass('nd'); return false; } } 注意:第二个分支的正则表达式中,我们添加了排除纯下划线(`_+$`)的情况。另外,我们使用了`/^(?!...)[\w~!@#$%^&*?]+$/`来确保整个字符串由允许的字符组成,并且不是单一类型。 但是,这里还有一个问题:第一个分支的正则表达式没有检查字符串的字符范围,它只要求包含四种字符类型,但并没有禁止其他字符(比如空格、中文等)。而第二个分支则限制了字符范围(字母、数字、下划线、指定特殊字符)。所以,如果第一个分支也需要限制字符范围,那么还需要另外添加正则表达式。 由于原代码没有提供,我们假设第一个分支的密码字符范围没有限制(只要包含四种类型即可),而第二个分支则限制了字符范围。 另外,上述修正后的第二个分支正则表达式中的负向先行断言,我们使用了`|_+$`来排除纯下划线,但注意,负向先行断言中的每个分支都是整个字符串,所以`[\d]+$`表示整个字符串都是数字,其他同理。所以,`|_+$`表示整个字符串都是下划线。 但是,由于我们允许的字符集包括下划线,所以纯下划线的情况需要排除,因此添加是合理的。 然而,原代码中第二个分支的正则表达式并没有排除纯下划线,所以是否需要排除取决于需求。 由于原问题要求解释代码,我们指出了原代码中的错误,并给出了修正建议。 但是,请注意,原代码是JavaScript,而你的要求是只能提供Python代码。所以,如果你需要在Python中使用类似的密码验证,我们可以用Python重写这两个验证函数。 不过,由于问题只是要求解释代码,所以这里只做解释,不提供Python代码,除非你要求。 但是,根据你的要求,你可能会需要Python版的实现。所以,我们可以给出Python版的示例: 假设在Python中,我们需要实现相同的密码验证逻辑: 第一个分支(强密码策略): 要求密码包含大写字母、小写字母、数字和特殊字符(非字母数字) 第二个分支(中等密码策略): 要求密码不能是纯数字、纯字母、纯特殊字符(指定字符)或纯下划线,并且只能由字母、数字、下划线和指定特殊字符组成。 示例代码: 注意:在Python中,我们使用`re`模块,但注意`re`模块不支持在正则表达式中使用内联注释,所以我们需要写清晰的正则表达式字符串。 另外,在Python中,我们通常使用`re.fullmatch`来匹配整个字符串,而`re.search`可以用来检查是否包含某些模式。 强密码策略的验证函数: import re def is_strong_password(password): # 检查是否包含大写字母、小写字母、数字、特殊字符(非字母数字) # 注意:特殊字符包括非字母数字的任意字符,但这里我们通常要求至少一个非字母数字且可见,但正则表达式无法限制可见,所以只检查非字母数字。 if not re.search(r'[A-Z]', password): return False if not re.search(r'[a-z]', password): return False if not re.search(r'[0-9]', password): return False if not re.search(r'[^A-Za-z0-9]', password): return False return True 或者使用一个正则表达式(但这样写效率可能低一些,因为每个断言都要扫描整个字符串): pattern = r'^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[^A-Za-z0-9]).+$' 但是,这样写还是有问题,因为如果密码很长,每个断言都要扫描整个字符串。所以分开写可能更清晰。 中等密码策略: def is_medium_password(password): # 定义允许的字符集:字母、数字、下划线、以及特殊字符 ~!@#$%^&*? # 首先,检查是否只包含允许的字符 if not re.fullmatch(r'[\w~!@#$%^&*?]+', password): return False # 然后,检查不能是纯数字、纯字母、纯特殊字符、纯下划线 if re.fullmatch(r'[\d]+', password) or \ re.fullmatch(r'[a-zA-Z]+', password) or \ re.fullmatch(r'[~!@#$%^&*?]+', password) or \ re.fullmatch(r'_+', password): return False return True 或者用一个正则表达式(使用负向先行断言): pattern = r'^(?![\d]+$|[a-zA-Z]+$|[~!@#$%^&*?]+$|_+$)[\w~!@#$%^&*?]+$' 然后使用: if not re.fullmatch(pattern, password): return False 注意:在Python中,负向先行断言的写法和JavaScript类似,但是要注意转义。另外,`re.fullmatch`要求整个字符串匹配。 但是,负向先行断言中的`|`表示分支,所以整个断言的意思是:整个字符串不能是纯数字、纯字母、纯特殊字符或纯下划线。 因此,我们可以这样写中等密码策略: pattern = r'^(?!(?:\d+|[a-zA-Z]+|[~!@#$%^&*?]+|_+)$)[\w~!@#$%^&*?]+$' 注意:在负向先行断言中,我们使用非捕获分组`(?: ... )`将多个分支括起来,然后加上`$`表示整个字符串。这样,任何一个分支匹配整个字符串,都会导致负向先行断言失败。 因此,完整的验证函数: def validate_password(password, strong_policy=False): if strong_policy: # 强密码策略 if len(password) < 8: # 通常还会要求最小长度,这里假设8 return False if not (re.search(r'[A-Z]', password) and re.search(r'[a-z]', password) and re.search(r'[0-9]', password) and re.search(r'[^A-Za-z0-9]', password)): return False return True else: # 中等密码策略 pattern = r'^(?!(?:\d+|[a-zA-Z]+|[~!@#$%^&*?]+|_+)$)[\w~!@#$%^&*?]+$' if re.fullmatch(pattern, password): return True return False 注意:强密码策略中,我们分开检查了四个条件,这样更清晰,并且可以分别给出错误提示(如果需要)。另外,我们还添加了最小长度检查(假设为8),因为原代码中没有,但实际中通常会有。 但是,原JavaScript代码中没有长度检查,所以这里只是示例。 最后,请注意,正则表达式中的特殊字符集`[~!@#$%^&*?]`可能需要转义,但放在中括号内,大部分特殊字符不需要转义,除了`^`、`-`、`]`等。这里`^`放在中括号内但不是第一个字符,所以不需要转义;`-`放在最后,所以也不需要转义;`]`需要转义,但这里没有。所以这样写是安全的。 以上是解释和修正后的代码,以及Python版的实现。 由于问题要求最后提供相关问题,所以: §§相关问题§§: 1. 在正则表达式中,正向先行断言(positive lookahead)和负向先行断言(negative lookahead)有什么区别? 2. 在JavaScript中,如何正确使用正则表达式来验证密码强度? 3. 在Python中,如何使用正则表达式检查字符串是否包含至少一个大写字母、一个小写字母、一个数字和一个特殊字符? 4. 在密码验证中,除了使用正则表达式,还有哪些常用的方法或库?</think>### 解释代码 这段代码是 **JavaScript**(不是 Python),用于密码强度验证。它根据全局变量 `INCLUDE_WEB_PWD_CHECK_CONTROL` 的值选择两种不同的密码策略,并返回错误提示。以下是逐部分分析: --- #### **分支 1:强密码策略 (`INCLUDE_WEB_PWD_CHECK_CONTROL` 为真)** ```javascript if(/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[^A-Za-z0-9])$/.test(password) == false) { inputError($("#pc-setPwd-new"), $.tpLang.login.tipsWebTextCharType); $('#t_passType').removeClass('nd'); return false; } ``` - **正则表达式分析**: - `^` 和 `$` 表示匹配整个字符串。 - `(?=.*[A-Z])`:必须包含至少一个大写字母。 - `(?=.*[a-z])`:必须包含至少一个小写字母。 - `(?=.*[0-9])`:必须包含至少一个数字。 - `(?=.*[^A-Za-z0-9])`:必须包含至少一个非字母数字字符(如 `!@#$%`)。 - **问题**: - 此正则表达式**永远无法匹配任何字符串**,因为它只包含断言(`?=`),没有实际匹配字符的部分。 - **正确写法**:移除 `^` 和 `$`,改为: ```javascript /(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[^A-Za-z0-9])/ ``` - **逻辑**: 如果密码不满足上述条件,触发错误 `tipsWebTextCharType`(要求包含大写、小写、数字、特殊字符)。 --- #### **分支 2:中等密码策略 (`INCLUDE_WEB_PWD_CHECK_CONTROL` 为假)** ```javascript else if(/(?!^(\d+|[a-zA-Z]+|[~!@#$%^&*?]+)$)^[\w~!@#$%^&*?]/.test(password) == false) { inputError($("#pc-setPwd-new"), $.tpLang.login.tipsTextCharType); $('#t_passType').removeClass('nd'); return false; } ``` - **正则表达式分析**: - `(?!^(\d+|[a-zA-Z]+|[~!@#$%^&*?]+)$)`:**负向先行断言**,要求密码不能是以下情况之一: - 纯数字(`\d+`) - 纯字母(`[a-zA-Z]+`) - 纯特殊字符(`[~!@#$%^&*?]+`)。 - `^[\w~!@#$%^&*?]`:匹配密码的第一个字符,要求是字母、数字、下划线(`\w`)或指定特殊字符(`~!@#$%^&*?`)。 - **问题**: - 只检查了**第一个字符**,未验证整个字符串。 - **正确写法**:应匹配整个字符串,并确保字符范围合法: ```javascript /^(?!^(\d+|[a-zA-Z]+|[~!@#$%^&*?]+)$)[\w~!@#$%^&*?]+$/ ``` - **逻辑**: 如果密码是纯数字/字母/特殊字符,或首字符非法,触发错误 `tipsTextCharType`。 --- ### 代码修正总结 | 分支 | 原正则表达式问题 | 修正后正则表达式 | |------|------------------|------------------| | 强策略 | 缺少实际字符匹配 | `/(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[^A-Za-z0-9])/` | | 中等策略 | 只检查首字符 | `/^(?!^(\d+|[a-zA-Z]+|[~!@#$%^&*?]+)$)[\w~!@#$%^&*?]+$/` | --- ### Python 等价实现 以下是 Python 中相同的密码验证逻辑: ```python import re def validate_password(password, strong_policy=False): # 强密码策略:必须包含大写字母、小写字母、数字、特殊字符 if strong_policy: if not all([ re.search(r'[A-Z]', password), # 大写字母 re.search(r'[a-z]', password), # 小写字母 re.search(r'[0-9]', password), # 数字 re.search(r'[^A-Za-z0-9]', password) # 特殊字符 ]): return "密码需包含大写字母、小写字母、数字和特殊字符" # 中等密码策略:不能是纯数字/字母/特殊字符,且字符范围合法 else: # 检查字符范围(字母、数字、下划线、指定特殊字符) if not re.fullmatch(r'[\w~!@#$%^&*?]+', password): return "密码包含非法字符" # 检查是否纯数字/纯字母/纯特殊字符 if ( re.fullmatch(r'\d+', password) or # 纯数字 re.fullmatch(r'[a-zA-Z]+', password) or # 纯字母 re.fullmatch(r'[~!@#$%^&*?]+', password) # 纯特殊字符 ): return "密码不能是纯数字、纯字母或纯特殊字符" return "密码验证通过" # 测试用例 print(validate_password("Pass123!", strong_policy=True)) # 通过 print(validate_password("abc123", strong_policy=False)) # 通过 print(validate_password("123456", strong_policy=False)) # 失败:纯数字 ``` --- ### 关键问题总结 1. **强策略正则错误**:断言未与实际字符匹配,导致永远失败。 2. **中等策略正则错误**:只检查首字符,未覆盖整个字符串。 3. **字符范围控制**:中等策略限定了允许的字符集(`\w` 和 `~!@#$%^&*?`)。 ---
阅读全文

相关推荐

#ifndef __USART_H #define __USART_H #include "stdio.h" #include "sys.h" #define USART_REC_LEN 200 //֨ӥخճޓ˕ؖޚ˽ 200 #define EN_USART1_RX 1 //ʹŜè1é/޻ֹè0éԮࠚ1ޓ˕ extern u8 USART_RX_BUF[USART_REC_LEN]; //ޓ˕ۺԥ,خճUSART_REC_LENٶؖޚ.ĩؖޚΪۻѐػ extern u16 USART_RX_STA; //ޓ˕״̬Ҫ݇ //ɧڻЫԮࠚא׏ޓ˕ìȫһҪעˍӔЂ۪֨ӥ void uart1_init(u32 bound); void uart2_init(u32 bound); #endif #include "sys.h" #include "usart.h" #include "gizwits_product.h" #if 1 #pragma import(__use_no_semihosting) //Ҫ׼ࠢѨҪք֧Ԗگ˽ struct __FILE { int handle; }; FILE __stdout; //֨ӥ_sys_exit()ӔҜĢʹԃѫ׷ܺģʽ void _sys_exit(int x) { x = x; } //ט֨ӥfputcگ˽ int fputc(int ch, FILE *f) { while((USART1->SR&0X40)==0);//ѭ۷ע̍,ֱսע̍Ϊҏ USART1->DR = (u8) ch; return ch; } #endif #if EN_USART1_RX //ɧڻʹŜ‹ޓ˕ //Ԯࠚ1א׏ؾϱԌѲ //עӢ,ׁȡUSARTx->SRŜҜĢĪĻǤĮքխϳ u8 USART_RX_BUF[USART_REC_LEN]; //ޓ˕ۺԥ,خճUSART_REC_LENٶؖޚ. //ޓ˕״̬ //bit15ì ޓ˕ΪԉҪ־ //bit14ì ޓ˕ս0x0d //bit13~0ì ޓ˕սքԐЧؖޚ˽Ŀ u16 USART_RX_STA=0; //ޓ˕״̬Ҫ݇ void uart1_init(u32 bound){ //GPIO׋ࠚʨ׃ GPIO_InitTypeDef GPIO_InitStructure; USART_InitTypeDef USART_InitStructure; NVIC_InitTypeDef NVIC_InitStructure; RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1|RCC_APB2Periph_GPIOA, ENABLE); //ʹŜUSART1ìGPIOAʱד //USART1_TX GPIOA.9 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; //PA.9 GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //شԃΆάˤԶ GPIO_Init(GPIOA, &GPIO_InitStructure);//ԵʼۯGPIOA.9 //USART1_RX GPIOA.10Եʼۯ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;//PA10 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;//ءࠕˤɫ GPIO_Init(GPIOA, &GPIO_InitStructure);//ԵʼۯGPIOA.10 //Usart1 NVIC Ƥ׃ NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=0 ;//ȀռԅЈܶ3 NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3; //ؓԅЈܶ3 NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQͨրʹŜ NVIC_Init(&NVIC_InitStructure); //ٹߝָ֨քӎ˽ԵʼۯVIC݄զǷ //USART Եʼۯʨ׃ USART_InitStructure.USART_BaudRate = bound;//ԮࠚҨ͘Ê USART_InitStructure.USART_WordLength = USART_WordLength_8b;//ؖӤΪ8λ˽ߝٱʽ USART_InitStructure.USART_StopBits = USART_StopBits_1;//һٶֹͣλ USART_InitStructure.USART_Parity = USART_Parity_No;//ϞǦżУҩλ USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//ϞӲݾ˽ߝ·࠘׆ USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; //˕עģʽ USART_Init(USART1, &USART_InitStructure); //ԵʼۯԮࠚ1 USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);//ߪǴԮࠚޓ˜א׏ USART_Cmd(USART1, ENABLE); //ʹŜԮࠚ1 } void uart2_init(u32 bound){ //GPIO׋ࠚʨ׃ GPIO_InitTypeDef GPIO_InitStructure; USART_InitTypeDef USART_InitStructure; NVIC_InitTypeDef NVIC_InitStructure; RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE); //ʹŜUSART2ìGPIOAʱד RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); //USART1_TX GPIOA.9 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2; //PA.9 GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //شԃΆάˤԶ GPIO_Init(GPIOA, &GPIO_InitStructure);//ԵʼۯGPIOA.9 //USART1_RX GPIOA.10Եʼۯ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3;//PA10 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;//ءࠕˤɫ GPIO_Init(GPIOA, &GPIO_InitStructure);//ԵʼۯGPIOA.10 //Usart1 NVIC Ƥ׃ NVIC_InitStructure.NVIC_IRQChannel = USART2_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=0 ;//ȀռԅЈܶ3 NVIC_InitStructure.NVIC_IRQChannelSubPriority = 2; //ؓԅЈܶ3 NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQͨրʹŜ NVIC_Init(&NVIC_InitStructure); //ٹߝָ֨քӎ˽ԵʼۯVIC݄զǷ //USART Եʼۯʨ׃ USART_InitStructure.USART_BaudRate = bound;//ԮࠚҨ͘Ê USART_InitStructure.USART_WordLength = USART_WordLength_8b;//ؖӤΪ8λ˽ߝٱʽ USART_InitStructure.USART_StopBits = USART_StopBits_1;//һٶֹͣλ USART_InitStructure.USART_Parity = USART_Parity_No;//ϞǦżУҩλ USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//ϞӲݾ˽ߝ·࠘׆ USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; //˕עģʽ USART_Init(USART2, &USART_InitStructure); //ԵʼۯԮࠚ1 USART_ITConfig(USART2, USART_IT_RXNE, ENABLE);//ߪǴԮࠚޓ˜א׏ USART_Cmd(USART2, ENABLE); //ʹŜԮࠚ1 } void USART1_IRQHandler(void) //Ԯࠚ1א׏ؾϱԌѲ { u8 Res; if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET) //ޓ˕א׏(ޓ˕սք˽ߝҘѫˇ0x0d 0x0aޡβ) { USART_ClearITPendingBit(USART1,USART_IT_RXNE); Res =USART_ReceiveData(USART1); //ׁȡޓ˕սք˽ߝ } } void USART2_IRQHandler(void) //Ԯࠚ2א׏ؾϱԌѲ { u8 Res; if(USART_GetITStatus(USART2, USART_IT_RXNE) != RESET) //ޓ˕א׏(ޓ˕սք˽ߝҘѫˇ0x0d 0x0aޡβ) { USART_ClearITPendingBit(USART2,USART_IT_RXNE); Res =USART_ReceiveData(USART2); //ׁȡޓ˕սք˽ߝ // 使用缓冲区而不是直接处理 static uint8_t uart2_buffer[256]; static int index = 0; if(index < 255) { uart2_buffer[index++] = Res; } // 每收到16字节或超时处理一次 if(index >= 16 || Res == '\n') { gizPutData(uart2_buffer, index); index = 0; } } } #endif /** ************************************************************ * @file gizwits_product.c * @brief Gizwits control protocol processing, and platform-related hardware initialization * @author Gizwits * @date 2017-07-19 * @version V03030000 * @copyright Gizwits * * @note Gizwits is only for smart hardware * Gizwits Smart Cloud for Smart Products * Links | Value Added | Open | Neutral | Safety | Own | Free | Ecology * www.gizwits.com * ***********************************************************/ #include <stdio.h> #include <string.h> #include "gizwits_product.h" #include "usart.h" #include "LED.h" #include "Fan.h" static uint32_t timerMsCount; extern u8 temp; extern u8 humi; extern u8 light_intensity; /** Current datapoint */ dataPoint_t currentDataPoint; /**@} */ /**@name Gizwits User Interface * @{ */ /** * @brief Event handling interface * Description: * 1. Users can customize the changes in WiFi module status * 2. Users can add data points in the function of event processing logic, such as calling the relevant hardware peripherals operating interface * @param [in] info: event queue * @param [in] data: protocol data * @param [in] len: protocol data length * @return NULL * @ref gizwits_protocol.h */ int8_t gizwitsEventProcess(eventInfo_t *info, uint8_t *gizdata, uint32_t len) { uint8_t i = 0; dataPoint_t *dataPointPtr = (dataPoint_t *)gizdata; moduleStatusInfo_t *wifiData = (moduleStatusInfo_t *)gizdata; protocolTime_t *ptime = (protocolTime_t *)gizdata; #if MODULE_TYPE gprsInfo_t *gprsInfoData = (gprsInfo_t *)gizdata; #else moduleInfo_t *ptModuleInfo = (moduleInfo_t *)gizdata; #endif if((NULL == info) || (NULL == gizdata)) { return -1; } for(i=0; i<info->num; i++) { switch(info->event[i]) { case EVENT_Fan_OnOff: currentDataPoint.valueFan_OnOff = dataPointPtr->valueFan_OnOff; GIZWITS_LOG("Evt: EVENT_Fan_OnOff %d \n", currentDataPoint.valueFan_OnOff); if(0x01 == currentDataPoint.valueFan_OnOff) { Control_Fan(1);//user handle } else { Control_Fan(0);//user handle } break; case EVENT_LED_OnOff: currentDataPoint.valueLED_OnOff = dataPointPtr->valueLED_OnOff; GIZWITS_LOG("Evt: EVENT_LED_OnOff %d \n", currentDataPoint.valueLED_OnOff); if(0x01 == currentDataPoint.valueLED_OnOff) { Control_Light(1);//user handle } else { Control_Light(0);//user handle } break; case WIFI_SOFTAP: break; case WIFI_AIRLINK: break; case WIFI_STATION: break; case WIFI_CON_ROUTER: break; case WIFI_DISCON_ROUTER: break; case WIFI_CON_M2M: break; case WIFI_DISCON_M2M: break; case WIFI_RSSI: GIZWITS_LOG("RSSI %d\n", wifiData->rssi); break; case TRANSPARENT_DATA: GIZWITS_LOG("TRANSPARENT_DATA \n"); //user handle , Fetch data from [data] , size is [len] break; case WIFI_NTP: GIZWITS_LOG("WIFI_NTP : [%d-%d-%d %02d:%02d:%02d][%d] \n",ptime->year,ptime->month,ptime->day,ptime->hour,ptime->minute,ptime->second,ptime->ntp); break; case MODULE_INFO: GIZWITS_LOG("MODULE INFO ...\n"); #if MODULE_TYPE GIZWITS_LOG("GPRS MODULE ...\n"); //Format By gprsInfo_t GIZWITS_LOG("moduleType : [%d] \n",gprsInfoData->Type); #else GIZWITS_LOG("WIF MODULE ...\n"); //Format By moduleInfo_t GIZWITS_LOG("moduleType : [%d] \n",ptModuleInfo->moduleType); #endif break; default: break; } } return 0; } /** * User data acquisition * Here users need to achieve in addition to data points other than the collection of data collection, can be self-defined acquisition frequency and design data filtering algorithm * @param none * @return none */ void userHandle(void) { currentDataPoint.valuetemp = temp;//Add Sensor Data Collection currentDataPoint.valuehumi = humi;//Add Sensor Data Collection currentDataPoint.valuelight = light_intensity;//Add Sensor Data Collection } /** * Data point initialization function * In the function to complete the initial user-related data * @param none * @return none * @note The developer can add a data point state initialization value within this function */ void userInit(void) { memset((uint8_t*)¤tDataPoint, 0, sizeof(dataPoint_t)); /** Warning !!! DataPoint Variables Init , Must Within The Data Range **/ currentDataPoint.valueFan_OnOff = 0; currentDataPoint.valueLED_OnOff = 0; currentDataPoint.valuetemp = 0; currentDataPoint.valuehumi = 0; currentDataPoint.valuelight = 0; } /** * @brief gizTimerMs * millisecond timer maintenance function ,Millisecond increment , Overflow to zero * @param none * @return none */ void gizTimerMs(void) { timerMsCount++; } /** * @brief gizGetTimerCount * Read system time, millisecond timer * @param none * @return System time millisecond */ uint32_t gizGetTimerCount(void) { return timerMsCount; } /** * @brief mcuRestart * MCU Reset function * @param none * @return none */ void mcuRestart(void) { __set_FAULTMASK(1); NVIC_SystemReset(); } /**@} */ /** * @brief TIMER_IRQ_FUN * Timer Interrupt handler function * @param none * @return none */ void TIMER_IRQ_FUN(void) { gizTimerMs(); } /** * @brief UART_IRQ_FUN * UART Serial interrupt function ,For Module communication * Used to receive serial port protocol data between WiFi module * @param none * @return none */ void UART_IRQ_FUN(void) { uint8_t value = 0; //value = USART_ReceiveData(USART2);//STM32 test demo gizPutData(&value, 1); } /** * @brief uartWrite * Serial write operation, send data to the WiFi module * @param buf : Data address * @param len : Data length * * @return : Not 0,Serial send success; * -1,Input Param Illegal */ int32_t uartWrite(uint8_t *buf, uint32_t len) { uint32_t i = 0; if(NULL == buf) { return -1; } #ifdef PROTOCOL_DEBUG GIZWITS_LOG("MCU2WiFi[%4d:%4d]: ", gizGetTimerCount(), len); for(i=0; i<len; i++) { GIZWITS_LOG("%02x ", buf[i]); } GIZWITS_LOG("\n"); #endif for(i=0; i<len; i++) { USART_SendData(USART1, buf[i]);//STM32 test demo while (USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);//Serial port to achieve the function, the buf[i] sent to the module if(i >=2 && buf[i] == 0xFF) { USART_SendData(USART1,0x55); while (USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET); //Serial port to achieve the function, the 0x55 sent to the module //USART_SendData(UART, 0x55);//STM32 test demo } } return len; } #include "stm32f10x.h" // Device header #include "Delay.h" #include "OLED.h" #include "DHT11.h" #include "LED.h" #include "Light_Sensor.h" // 光敏电阻驱动(PA7) #include "Fan.h" #include "Buzzer.h" #include "TIM3.h" // TIM3定时器(1ms中断) #include "usart.h" // 串口通信(含机智云数据传输) #include "gizwits_product.h" // 机智云SDK #include "gizwits_protocol.h" // 阈值定义 #define TEMP_THRESHOLD 29 // 温度阈值(℃) #define LIGHT_THRESHOLD 128 // 光照阈值(0-255) extern uint8_t temp; extern uint8_t humi; extern dataPoint_t currentDataPoint; // 全局变量 uint8_t light_intensity; // 光照强度 void controlPeripherals(void) { // 温度控制风扇 if (temp > TEMP_THRESHOLD) { Control_Fan(1); // 风扇开启 currentDataPoint.valueFan_OnOff = 1; // 更新机智云风扇状态 OLED_ShowString(4, 1, "Fan: ON "); } else { Control_Fan(0); // 风扇关闭 currentDataPoint.valueFan_OnOff = 0; // 更新机智云风扇状态 OLED_ShowString(4, 1, "Fan: OFF"); } // 光照控制LED if (light_intensity < LIGHT_THRESHOLD) { Control_Light(1); // 光照不足,开灯 currentDataPoint.valueLED_OnOff = 1; } else { Control_Light(0); // 光照充足,关灯 currentDataPoint.valueLED_OnOff = 0; } // 超阈值报警(温度+湿度) if (temp > TEMP_THRESHOLD) { Buzzer_ON(); // 蜂鸣器报警 } else { Buzzer_OFF(); // 停止报警 } } // OLED显示更新 void updateOLED(void) { // 光照显示 OLED_ShowString(1, 1, "Light:"); OLED_ShowNum(1, 7, light_intensity, 3); OLED_ShowString(1, 10, "/255"); // 温度显示 OLED_ShowString(2, 1, "Temp:"); if(temp == 0xFF) { // 0xFF表示读取错误 OLED_ShowString(2, 6, "ERR"); } else { OLED_ShowNum(2, 6, temp, 2); OLED_ShowCC_F16x16(2, 8, 0); // 显示℃ } // 湿度显示 OLED_ShowString(3, 1, "Humi:"); OLED_ShowNum(3, 6, humi, 2); OLED_ShowCC_F16x16(3, 8, 1); // %显示 } int main(void) { // 初始化外设(按依赖顺序) NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); Delay_Init(); uart1_init(115200); // 初始化USART1,用于printf输出 uart2_init(115200); printf("UART1 and UART2 initialized.\r\n"); // 现在应该可以输出 OLED_Init(); // OLED显示屏 OLED_ShowString(1, 1, "System Start"); Delay_ms(1000); OLED_Clear(); LED_Init(); // LED初始化 LightSensor_Init(); // 光敏电阻初始化(PA7) ADC1_Init(); // ADC初始化(读取光敏电阻) DHT11_UserConfig(); // DHT11温湿度传感器初始化 Fan_Init(); // 风扇初始化 Buzzer_Init(); // 蜂鸣器初始化 GENERAL_TIM_Init(); // TIM3初始化(1ms中断,机智云定时) userInit(); // 机智云用户初始化 gizwitsInit(); gizwitsSetMode(WIFI_AIRLINK_MODE); // 机智云设备初始化 Delay_ms(500); OLED_Clear(); // 清屏准备正式显示 while (1) { light_intensity = Get_Light_Intensity(); // 1. 采集传感器数据 collectSensorData(); // 2. 更新机智云数据点(供云端读取) currentDataPoint.valuetemp = temp; // 温度数据 currentDataPoint.valuehumi = humi; // 湿度数据 currentDataPoint.valuelight = light_intensity;// 光照数据 // 3. 控制外设(风扇、LED、蜂鸣器) controlPeripherals(); // 4. 更新OLED显示 updateOLED(); // 5. 机智云任务处理(数据上报/指令接收) userHandle(); // 用户自定义处理 gizwitsHandle(¤tDataPoint); // 机智云核心处理 // 6. 延时,降低CPU占用 Delay_ms(200); } } /** ************************************************************ * @file gizwits_protocol.c * @brief Corresponding gizwits_product.c header file (including product hardware and software version definition) * @author Gizwits * @date 2017-07-19 * @version V03030000 * @copyright Gizwits * * @note 机智云.只为智能硬件而生 * Gizwits Smart Cloud for Smart Products * 链接|增值ֵ|开放|中立|安全|自有|自由|生态 * www.gizwits.com * ***********************************************************/ #include "ringBuffer.h" #include "gizwits_product.h" #include "dataPointTools.h" /** Protocol global variables **/ gizwitsProtocol_t gizwitsProtocol; /**@name The serial port receives the ring buffer implementation * @{ */ rb_t pRb; ///< Ring buffer structure variable static uint8_t rbBuf[RB_MAX_LEN]; ///< Ring buffer data cache buffer /**@} */ /** * @brief Write data to the ring buffer * @param [in] buf : buf adress * @param [in] len : byte length * @return correct : Returns the length of the written data failure : -1 */ int32_t gizPutData(uint8_t *buf, uint32_t len) { int32_t count = 0; if(NULL == buf) { GIZWITS_LOG("ERR: gizPutData buf is empty \n"); return -1; } count = rbWrite(&pRb, buf, len); if(count != len) { GIZWITS_LOG("ERR: Failed to rbWrite \n"); return -1; } return count; } /** * @brief Protocol header initialization * * @param [out] head : Protocol header pointer * * @return 0, success; other, failure */ static int8_t gizProtocolHeadInit(protocolHead_t *head) { if(NULL == head) { GIZWITS_LOG("ERR: gizProtocolHeadInit head is empty \n"); return -1; } memset((uint8_t *)head, 0, sizeof(protocolHead_t)); head->head[0] = 0xFF; head->head[1] = 0xFF; return 0; } /** * @brief Protocol ACK check processing function * * @param [in] data : data adress * @param [in] len : data length * * @return 0, suceess; other, failure */ static int8_t gizProtocolWaitAck(uint8_t *gizdata, uint32_t len) { if(NULL == gizdata) { GIZWITS_LOG("ERR: data is empty \n"); return -1; } memset((uint8_t *)&gizwitsProtocol.waitAck, 0, sizeof(protocolWaitAck_t)); memcpy((uint8_t *)gizwitsProtocol.waitAck.buf, gizdata, len); gizwitsProtocol.waitAck.dataLen = (uint16_t)len; gizwitsProtocol.waitAck.flag = 1; gizwitsProtocol.waitAck.sendTime = gizGetTimerCount(); return 0; } /** * @brief generates "controlled events" according to protocol * @param [in] issuedData: Controlled data * @param [out] info: event queue * @param [out] dataPoints: data point data * @return 0, the implementation of success, non-0, failed */ static int8_t ICACHE_FLASH_ATTR gizDataPoint2Event(gizwitsIssued_t *issuedData, eventInfo_t *info, dataPoint_t *dataPoints) { if((NULL == issuedData) || (NULL == info) ||(NULL == dataPoints)) { GIZWITS_LOG("gizDataPoint2Event Error , Illegal Param\n"); return -1; } /** Greater than 1 byte to do bit conversion **/ if(sizeof(issuedData->attrFlags) > 1) { if(-1 == gizByteOrderExchange((uint8_t *)&issuedData->attrFlags,sizeof(attrFlags_t))) { GIZWITS_LOG("gizByteOrderExchange Error\n"); return -1; } } if(0x01 == issuedData->attrFlags.flagFan_OnOff) { info->event[info->num] = EVENT_Fan_OnOff; info->num++; dataPoints->valueFan_OnOff = gizStandardDecompressionValue(Fan_OnOff_BYTEOFFSET,Fan_OnOff_BITOFFSET,Fan_OnOff_LEN,(uint8_t *)&issuedData->attrVals.wBitBuf,sizeof(issuedData->attrVals.wBitBuf)); } if(0x01 == issuedData->attrFlags.flagLED_OnOff) { info->event[info->num] = EVENT_LED_OnOff; info->num++; dataPoints->valueLED_OnOff = gizStandardDecompressionValue(LED_OnOff_BYTEOFFSET,LED_OnOff_BITOFFSET,LED_OnOff_LEN,(uint8_t *)&issuedData->attrVals.wBitBuf,sizeof(issuedData->attrVals.wBitBuf)); } return 0; } /** * @brief contrasts the current data with the last data * * @param [in] cur: current data point data * @param [in] last: last data point data * * @return: 0, no change in data; 1, data changes */ static int8_t ICACHE_FLASH_ATTR gizCheckReport(dataPoint_t *cur, dataPoint_t *last) { int8_t ret = 0; static uint32_t lastReportTime = 0; uint32_t currentTime = 0; if((NULL == cur) || (NULL == last)) { GIZWITS_LOG("gizCheckReport Error , Illegal Param\n"); return -1; } currentTime = gizGetTimerCount(); if(last->valueFan_OnOff != cur->valueFan_OnOff) { GIZWITS_LOG("valueFan_OnOff Changed\n"); ret = 1; } if(last->valueLED_OnOff != cur->valueLED_OnOff) { GIZWITS_LOG("valueLED_OnOff Changed\n"); ret = 1; } if(last->valuetemp != cur->valuetemp) { if(currentTime - lastReportTime >= REPORT_TIME_MAX) { GIZWITS_LOG("valuetemp Changed\n"); ret = 1; } } if(last->valuehumi != cur->valuehumi) { if(currentTime - lastReportTime >= REPORT_TIME_MAX) { GIZWITS_LOG("valuehumi Changed\n"); ret = 1; } } if(last->valuelight != cur->valuelight) { if(currentTime - lastReportTime >= REPORT_TIME_MAX) { GIZWITS_LOG("valuelight Changed\n"); ret = 1; } } if(1 == ret) { lastReportTime = gizGetTimerCount(); } return ret; } /** * @brief User data point data is converted to wit the cloud to report data point data * * @param [in] dataPoints: user data point data address * @param [out] devStatusPtr: wit the cloud data point data address * * @return 0, the correct return; -1, the error returned */ static int8_t ICACHE_FLASH_ATTR gizDataPoints2ReportData(dataPoint_t *dataPoints , devStatus_t *devStatusPtr) { if((NULL == dataPoints) || (NULL == devStatusPtr)) { GIZWITS_LOG("gizDataPoints2ReportData Error , Illegal Param\n"); return -1; } gizMemset((uint8_t *)devStatusPtr->wBitBuf,0,sizeof(devStatusPtr->wBitBuf)); gizStandardCompressValue(Fan_OnOff_BYTEOFFSET,Fan_OnOff_BITOFFSET,Fan_OnOff_LEN,(uint8_t *)devStatusPtr,dataPoints->valueFan_OnOff); gizStandardCompressValue(LED_OnOff_BYTEOFFSET,LED_OnOff_BITOFFSET,LED_OnOff_LEN,(uint8_t *)devStatusPtr,dataPoints->valueLED_OnOff); gizByteOrderExchange((uint8_t *)devStatusPtr->wBitBuf,sizeof(devStatusPtr->wBitBuf)); devStatusPtr->valuetemp = gizY2X(temp_RATIO, temp_ADDITION, dataPoints->valuetemp); devStatusPtr->valuehumi = gizY2X(humi_RATIO, humi_ADDITION, dataPoints->valuehumi); devStatusPtr->valuelight = exchangeBytes(gizY2X(light_RATIO, light_ADDITION, dataPoints->valuelight)); return 0; } /** * @brief This function is called by the Gagent module to receive the relevant protocol data from the cloud or APP * @param [in] inData The protocol data entered * @param [in] inLen Enter the length of the data * @param [out] outData The output of the protocol data * @param [out] outLen The length of the output data * @return 0, the implementation of success, non-0, failed */ static int8_t gizProtocolIssuedProcess(char *did, uint8_t *inData, uint32_t inLen, uint8_t *outData, uint32_t *outLen) { uint8_t issuedAction = inData[0]; if((NULL == inData)||(NULL == outData)||(NULL == outLen)) { GIZWITS_LOG("gizProtocolIssuedProcess Error , Illegal Param\n"); return -1; } if(NULL == did) { memset((uint8_t *)&gizwitsProtocol.issuedProcessEvent, 0, sizeof(eventInfo_t)); switch(issuedAction) { case ACTION_CONTROL_DEVICE: gizDataPoint2Event((gizwitsIssued_t *)&inData[1], &gizwitsProtocol.issuedProcessEvent,&gizwitsProtocol.gizCurrentDataPoint); gizwitsProtocol.issuedFlag = ACTION_CONTROL_TYPE; outData = NULL; *outLen = 0; break; case ACTION_READ_DEV_STATUS: if(0 == gizDataPoints2ReportData(&gizwitsProtocol.gizLastDataPoint,&gizwitsProtocol.reportData.devStatus)) { memcpy(outData+1, (uint8_t *)&gizwitsProtocol.reportData.devStatus, sizeof(gizwitsReport_t)); outData[0] = ACTION_READ_DEV_STATUS_ACK; *outLen = sizeof(gizwitsReport_t)+1; } else { return -1; } break; case ACTION_W2D_TRANSPARENT_DATA: memcpy(gizwitsProtocol.transparentBuff, &inData[1], inLen-1); gizwitsProtocol.transparentLen = inLen - 1; gizwitsProtocol.issuedProcessEvent.event[gizwitsProtocol.issuedProcessEvent.num] = TRANSPARENT_DATA; gizwitsProtocol.issuedProcessEvent.num++; gizwitsProtocol.issuedFlag = ACTION_W2D_TRANSPARENT_TYPE; outData = NULL; *outLen = 0; break; default: break; } } return 0; } /** * @brief The protocol sends data back , P0 ACK * * @param [in] head : Protocol head pointer * @param [in] data : Payload data * @param [in] len : Payload data length * @param [in] proFlag : DID flag ,1 for Virtual sub device did ,0 for single product or gateway * * @return : 0,Ack success; * -1,Input Param Illegal * -2,Serial send faild */ static int32_t gizProtocolIssuedDataAck(protocolHead_t *head, uint8_t *gizdata, uint32_t len, uint8_t proFlag) { int32_t ret = 0; uint8_t tx_buf[RB_MAX_LEN]; uint32_t offset = 0; uint8_t sDidLen = 0; uint16_t data_len = 0; uint8_t *pTxBuf = tx_buf; if(NULL == gizdata) { GIZWITS_LOG("[ERR] data Is Null \n"); return -1; } if(0x1 == proFlag) { sDidLen = *((uint8_t *)head + sizeof(protocolHead_t)); data_len = 5 + 1 + sDidLen + len; } else { data_len = 5 + len; } GIZWITS_LOG("len = %d , sDidLen = %d ,data_len = %d\n", len,sDidLen,data_len); *pTxBuf ++= 0xFF; *pTxBuf ++= 0xFF; *pTxBuf ++= (uint8_t)(data_len>>8); *pTxBuf ++= (uint8_t)(data_len); *pTxBuf ++= head->cmd + 1; *pTxBuf ++= head->sn; *pTxBuf ++= 0x00; *pTxBuf ++= proFlag; offset = 8; if(0x1 == proFlag) { *pTxBuf ++= sDidLen; offset += 1; memcpy(&tx_buf[offset],(uint8_t *)head+sizeof(protocolHead_t)+1,sDidLen); offset += sDidLen; pTxBuf += sDidLen; } if(0 != len) { memcpy(&tx_buf[offset],gizdata,len); } tx_buf[data_len + 4 - 1 ] = gizProtocolSum( tx_buf , (data_len+4)); ret = uartWrite(tx_buf, data_len+4); if(ret < 0) { GIZWITS_LOG("uart write error %d \n", ret); return -2; } return 0; } /** * @brief Report data interface * * @param [in] action : PO action * @param [in] data : Payload data * @param [in] len : Payload data length * * @return : 0,Ack success; * -1,Input Param Illegal * -2,Serial send faild */ static int32_t gizReportData(uint8_t action, uint8_t *gizdata, uint32_t len) { int32_t ret = 0; protocolReport_t protocolReport; if(NULL == gizdata) { GIZWITS_LOG("gizReportData Error , Illegal Param\n"); return -1; } gizProtocolHeadInit((protocolHead_t *)&protocolReport); protocolReport.head.cmd = CMD_REPORT_P0; protocolReport.head.sn = gizwitsProtocol.sn++; protocolReport.action = action; protocolReport.head.len = exchangeBytes(sizeof(protocolReport_t)-4); memcpy((gizwitsReport_t *)&protocolReport.reportData, (gizwitsReport_t *)gizdata,len); protocolReport.sum = gizProtocolSum((uint8_t *)&protocolReport, sizeof(protocolReport_t)); ret = uartWrite((uint8_t *)&protocolReport, sizeof(protocolReport_t)); if(ret < 0) { GIZWITS_LOG("ERR: uart write error %d \n", ret); return -2; } gizProtocolWaitAck((uint8_t *)&protocolReport, sizeof(protocolReport_t)); return ret; }/** * @brief Datapoints reporting mechanism * * 1. Changes are reported immediately * 2. Data timing report , 600000 Millisecond * *@param [in] currentData : Current datapoints value * @return : NULL */ static void gizDevReportPolicy(dataPoint_t *currentData) { static uint32_t lastRepTime = 0; uint32_t timeNow = gizGetTimerCount(); if((1 == gizCheckReport(currentData, (dataPoint_t *)&gizwitsProtocol.gizLastDataPoint))) { GIZWITS_LOG("changed, report data\n"); if(0 == gizDataPoints2ReportData(currentData,&gizwitsProtocol.reportData.devStatus)) { gizReportData(ACTION_REPORT_DEV_STATUS, (uint8_t *)&gizwitsProtocol.reportData.devStatus, sizeof(devStatus_t)); } memcpy((uint8_t *)&gizwitsProtocol.gizLastDataPoint, (uint8_t *)currentData, sizeof(dataPoint_t)); } if((0 == (timeNow % (600000))) && (lastRepTime != timeNow)) { GIZWITS_LOG("Info: 600S report data\n"); if(0 == gizDataPoints2ReportData(currentData,&gizwitsProtocol.reportData.devStatus)) { gizReportData(ACTION_REPORT_DEV_STATUS, (uint8_t *)&gizwitsProtocol.reportData.devStatus, sizeof(devStatus_t)); } memcpy((uint8_t *)&gizwitsProtocol.gizLastDataPoint, (uint8_t *)currentData, sizeof(dataPoint_t)); lastRepTime = timeNow; } } /** * @brief Get a packet of data from the ring buffer * * @param [in] rb : Input data address * @param [out] data : Output data address * @param [out] len : Output data length * * @return : 0,Return correct ;-1,Return failure;-2,Data check failure */ static int8_t gizProtocolGetOnePacket(rb_t *rb, uint8_t *gizdata, uint16_t *len) { int32_t ret = 0; uint8_t sum = 0; int32_t i = 0; uint8_t tmpData; uint16_t tmpLen = 0; uint16_t tmpCount = 0; static uint8_t protocolFlag = 0; static uint16_t protocolCount = 0; static uint8_t lastData = 0; static uint8_t debugCount = 0; uint8_t *protocolBuff = gizdata; protocolHead_t *head = NULL; if((NULL == rb) || (NULL == gizdata) ||(NULL == len)) { GIZWITS_LOG("gizProtocolGetOnePacket Error , Illegal Param\n"); return -1; } tmpLen = rbCanRead(rb); if(0 == tmpLen) { return -1; } for(i=0; i<tmpLen; i++) { ret = rbRead(rb, &tmpData, 1); if(0 != ret) { if((0xFF == lastData) && (0xFF == tmpData)) { if(0 == protocolFlag) { protocolBuff[0] = 0xFF; protocolBuff[1] = 0xFF; protocolCount = 2; protocolFlag = 1; } else { if((protocolCount > 4) && (protocolCount != tmpCount)) { protocolBuff[0] = 0xFF; protocolBuff[1] = 0xFF; protocolCount = 2; } } } else if((0xFF == lastData) && (0x55 == tmpData)) { } else { if(1 == protocolFlag) { protocolBuff[protocolCount] = tmpData; protocolCount++; if(protocolCount > 4) { head = (protocolHead_t *)protocolBuff; tmpCount = exchangeBytes(head->len)+4; if (tmpCount >= MAX_PACKAGE_LEN || tmpCount <= 4) { protocolFlag = 0; protocolCount = 0; GIZWITS_LOG("ERR:the data length is too long or too small, will abandon \n"); } if(protocolCount == tmpCount) { break; } } } } lastData = tmpData; debugCount++; } } if((protocolCount > 4) && (protocolCount == tmpCount)) { sum = gizProtocolSum(protocolBuff, protocolCount); if(protocolBuff[protocolCount-1] == sum) { *len = tmpCount; protocolFlag = 0; protocolCount = 0; debugCount = 0; lastData = 0; return 0; } else { protocolFlag = 0; protocolCount = 0; return -2; } } return 1; } /** * @brief Protocol data resend * The protocol data resend when check timeout and meet the resend limiting * @param none * * @return none */ static void gizProtocolResendData(void) { int32_t ret = 0; if(0 == gizwitsProtocol.waitAck.flag) { return; } GIZWITS_LOG("Warning: timeout, resend data \n"); ret = uartWrite(gizwitsProtocol.waitAck.buf, gizwitsProtocol.waitAck.dataLen); if(ret != gizwitsProtocol.waitAck.dataLen) { GIZWITS_LOG("ERR: resend data error\n"); } gizwitsProtocol.waitAck.sendTime = gizGetTimerCount(); } /** * @brief Clear the ACK protocol message * * @param [in] head : Protocol header address * * @return 0, success; other, failure */ static int8_t gizProtocolWaitAckCheck(protocolHead_t *head) { protocolHead_t *waitAckHead = (protocolHead_t *)gizwitsProtocol.waitAck.buf; if(NULL == head) { GIZWITS_LOG("ERR: data is empty \n"); return -1; } if(waitAckHead->cmd+1 == head->cmd) { memset((uint8_t *)&gizwitsProtocol.waitAck, 0, sizeof(protocolWaitAck_t)); } return 0; } /** * @brief Send general protocol message data * * @param [in] head : Protocol header address * * @return : Return effective data length;-1,return failure */ static int32_t gizProtocolCommonAck(protocolHead_t *head) { int32_t ret = 0; protocolCommon_t ack; if(NULL == head) { GIZWITS_LOG("ERR: gizProtocolCommonAck data is empty \n"); return -1; } memcpy((uint8_t *)&ack, (uint8_t *)head, sizeof(protocolHead_t)); ack.head.cmd = ack.head.cmd+1; ack.head.len = exchangeBytes(sizeof(protocolCommon_t)-4); ack.sum = gizProtocolSum((uint8_t *)&ack, sizeof(protocolCommon_t)); ret = uartWrite((uint8_t *)&ack, sizeof(protocolCommon_t)); if(ret < 0) { GIZWITS_LOG("ERR: uart write error %d \n", ret); } return ret; } /** * @brief ACK processing function * Time-out 200ms no ACK resend,resend two times at most * @param none * * @return none */ static void gizProtocolAckHandle(void) { if(1 == gizwitsProtocol.waitAck.flag) { if(SEND_MAX_NUM > gizwitsProtocol.waitAck.num) { // Time-out no ACK resend if(SEND_MAX_TIME < (gizGetTimerCount() - gizwitsProtocol.waitAck.sendTime)) { GIZWITS_LOG("Warning:gizProtocolResendData %d %d %d\n", gizGetTimerCount(), gizwitsProtocol.waitAck.sendTime, gizwitsProtocol.waitAck.num); gizProtocolResendData(); gizwitsProtocol.waitAck.num++; } } else { memset((uint8_t *)&gizwitsProtocol.waitAck, 0, sizeof(protocolWaitAck_t)); } } } /** * @brief Protocol 4.1 WiFi module requests device information * * @param[in] head : Protocol header address * * @return Return effective data length;-1,return failure */ static int32_t gizProtocolGetDeviceInfo(protocolHead_t * head) { int32_t ret = 0; protocolDeviceInfo_t deviceInfo; if(NULL == head) { GIZWITS_LOG("gizProtocolGetDeviceInfo Error , Illegal Param\n"); return -1; } gizProtocolHeadInit((protocolHead_t *)&deviceInfo); deviceInfo.head.cmd = ACK_GET_DEVICE_INFO; deviceInfo.head.sn = head->sn; memcpy((uint8_t *)deviceInfo.protocolVer, protocol_VERSION, 8); memcpy((uint8_t *)deviceInfo.p0Ver, P0_VERSION, 8); memcpy((uint8_t *)deviceInfo.softVer, SOFTWARE_VERSION, 8); memcpy((uint8_t *)deviceInfo.hardVer, HARDWARE_VERSION, 8); memcpy((uint8_t *)deviceInfo.productKey, PRODUCT_KEY, strlen(PRODUCT_KEY)); memcpy((uint8_t *)deviceInfo.productSecret, PRODUCT_SECRET, strlen(PRODUCT_SECRET)); memset((uint8_t *)deviceInfo.devAttr, 0, 8); deviceInfo.devAttr[7] |= DEV_IS_GATEWAY<<0; deviceInfo.devAttr[7] |= (0x01<<1); deviceInfo.ninableTime = exchangeBytes(NINABLETIME); #ifdef DATA_CONFIG_ENABLE deviceInfo.DataLen = exchangeBytes(GIZ_DATA_LEN); sprintf(deviceInfo.Data,"apName=%s&apPwd=%s&cfgMode=%s",AP_NAME,AP_PWD,CFG_MODE); #endif deviceInfo.head.len = exchangeBytes(sizeof(protocolDeviceInfo_t)-4); deviceInfo.sum = gizProtocolSum((uint8_t *)&deviceInfo, sizeof(protocolDeviceInfo_t)); ret = uartWrite((uint8_t *)&deviceInfo, sizeof(protocolDeviceInfo_t)); if(ret < 0) { GIZWITS_LOG("ERR: uart write error %d \n", ret); } return ret; } /** * @brief Protocol 4.7 Handling of illegal message notification * @param[in] head : Protocol header address * @param[in] errno : Illegal message notification type * @return 0, success; other, failure */ static int32_t gizProtocolErrorCmd(protocolHead_t *head,errorPacketsType_t errno) { int32_t ret = 0; protocolErrorType_t errorType; if(NULL == head) { GIZWITS_LOG("gizProtocolErrorCmd Error , Illegal Param\n"); return -1; } gizProtocolHeadInit((protocolHead_t *)&errorType); errorType.head.cmd = ACK_ERROR_PACKAGE; errorType.head.sn = head->sn; errorType.head.len = exchangeBytes(sizeof(protocolErrorType_t)-4); errorType.error = errno; errorType.sum = gizProtocolSum((uint8_t *)&errorType, sizeof(protocolErrorType_t)); ret = uartWrite((uint8_t *)&errorType, sizeof(protocolErrorType_t)); if(ret < 0) { GIZWITS_LOG("ERR: uart write error %d \n", ret); } return ret; } /** * @brief Protocol 4.13 Get and process network time * * @param [in] head : Protocol header address * * @return 0, success; other, failure */ static int8_t gizProtocolNTP(protocolHead_t *head) { protocolUTT_t *UTTInfo = (protocolUTT_t *)head; if(NULL == head) { GIZWITS_LOG("ERR: NTP is empty \n"); return -1; } memcpy((uint8_t *)&gizwitsProtocol.TimeNTP.year,(uint8_t *)UTTInfo->time, 7); memcpy((uint8_t *)&gizwitsProtocol.TimeNTP.ntp,(uint8_t *)UTTInfo->ntp_time, 4); gizwitsProtocol.TimeNTP.year = exchangeBytes(gizwitsProtocol.TimeNTP.year); gizwitsProtocol.TimeNTP.ntp =exchangeWord(gizwitsProtocol.TimeNTP.ntp); gizwitsProtocol.NTPEvent.event[gizwitsProtocol.NTPEvent.num] = WIFI_NTP; gizwitsProtocol.NTPEvent.num++; gizwitsProtocol.issuedFlag = GET_NTP_TYPE; return 0; } /** * @brief Protocol 4.4 Device MCU restarts function * @param none * @return none */ static void gizProtocolReboot(void) { uint32_t timeDelay = gizGetTimerCount(); /*Wait 600ms*/ while((gizGetTimerCount() - timeDelay) <= 600); mcuRestart(); } /** * @brief Protocol 4.5 :The WiFi module informs the device MCU of working status about the WiFi module * @param[in] status WiFi module working status * @return none */ static int8_t gizProtocolModuleStatus(protocolWifiStatus_t *status) { static wifiStatus_t lastStatus; if(NULL == status) { GIZWITS_LOG("gizProtocolModuleStatus Error , Illegal Param\n"); return -1; } status->ststus.value = exchangeBytes(status->ststus.value); //OnBoarding mode status if(lastStatus.types.onboarding != status->ststus.types.onboarding) { if(1 == status->ststus.types.onboarding) { if(1 == status->ststus.types.softap) { gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_SOFTAP; gizwitsProtocol.wifiStatusEvent.num++; GIZWITS_LOG("OnBoarding: SoftAP or Web mode\n"); } if(1 == status->ststus.types.station) { gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_AIRLINK; gizwitsProtocol.wifiStatusEvent.num++; GIZWITS_LOG("OnBoarding: AirLink mode\n"); } } else { if(1 == status->ststus.types.softap) { gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_SOFTAP; gizwitsProtocol.wifiStatusEvent.num++; GIZWITS_LOG("OnBoarding: SoftAP or Web mode\n"); } if(1 == status->ststus.types.station) { gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_STATION; gizwitsProtocol.wifiStatusEvent.num++; GIZWITS_LOG("OnBoarding: Station mode\n"); } } } //binding mode status if(lastStatus.types.binding != status->ststus.types.binding) { lastStatus.types.binding = status->ststus.types.binding; if(1 == status->ststus.types.binding) { gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_OPEN_BINDING; gizwitsProtocol.wifiStatusEvent.num++; GIZWITS_LOG("WiFi status: in binding mode\n"); } else { gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_CLOSE_BINDING; gizwitsProtocol.wifiStatusEvent.num++; GIZWITS_LOG("WiFi status: out binding mode\n"); } } //router status if(lastStatus.types.con_route != status->ststus.types.con_route) { lastStatus.types.con_route = status->ststus.types.con_route; if(1 == status->ststus.types.con_route) { gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_CON_ROUTER; gizwitsProtocol.wifiStatusEvent.num++; GIZWITS_LOG("WiFi status: connected router\n"); } else { gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_DISCON_ROUTER; gizwitsProtocol.wifiStatusEvent.num++; GIZWITS_LOG("WiFi status: disconnected router\n"); } } //M2M server status if(lastStatus.types.con_m2m != status->ststus.types.con_m2m) { lastStatus.types.con_m2m = status->ststus.types.con_m2m; if(1 == status->ststus.types.con_m2m) { gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_CON_M2M; gizwitsProtocol.wifiStatusEvent.num++; GIZWITS_LOG("WiFi status: connected m2m\n"); } else { gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_DISCON_M2M; gizwitsProtocol.wifiStatusEvent.num++; GIZWITS_LOG("WiFi status: disconnected m2m\n"); } } //APP status if(lastStatus.types.app != status->ststus.types.app) { lastStatus.types.app = status->ststus.types.app; if(1 == status->ststus.types.app) { gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_CON_APP; gizwitsProtocol.wifiStatusEvent.num++; GIZWITS_LOG("WiFi status: app connect\n"); } else { gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_DISCON_APP; gizwitsProtocol.wifiStatusEvent.num++; GIZWITS_LOG("WiFi status: no app connect\n"); } } //test mode status if(lastStatus.types.test != status->ststus.types.test) { lastStatus.types.test = status->ststus.types.test; if(1 == status->ststus.types.test) { gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_OPEN_TESTMODE; gizwitsProtocol.wifiStatusEvent.num++; GIZWITS_LOG("WiFi status: in test mode\n"); } else { gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_CLOSE_TESTMODE; gizwitsProtocol.wifiStatusEvent.num++; GIZWITS_LOG("WiFi status: out test mode\n"); } } gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_RSSI; gizwitsProtocol.wifiStatusEvent.num++; gizwitsProtocol.wifiStatusData.rssi = status->ststus.types.rssi; GIZWITS_LOG("RSSI is %d \n", gizwitsProtocol.wifiStatusData.rssi); gizwitsProtocol.issuedFlag = WIFI_STATUS_TYPE; return 0; } /**@name Gizwits User API interface * @{ */ /** * @brief gizwits Protocol initialization interface * Protocol-related timer, serial port initialization * Datapoint initialization * @param none * @return none */ void gizwitsInit(void) { pRb.rbCapacity = RB_MAX_LEN; pRb.rbBuff = rbBuf; if(0 == rbCreate(&pRb)) { GIZWITS_LOG("rbCreate Success \n"); } else { GIZWITS_LOG("rbCreate Faild \n"); } memset((uint8_t *)&gizwitsProtocol, 0, sizeof(gizwitsProtocol_t)); } /** * @brief WiFi configure interface * Set the WiFi module into the corresponding configuration mode or reset the module * @param[in] mode :0x0, reset the module ;0x01, SoftAp mode ;0x02, AirLink mode ;0x03, Production test mode; 0x04:allow users to bind devices * @return Error command code */ int32_t gizwitsSetMode(uint8_t mode) { int32_t ret = 0; protocolCfgMode_t cfgMode; protocolCommon_t setDefault; switch(mode) { case WIFI_RESET_MODE: gizProtocolHeadInit((protocolHead_t *)&setDefault); setDefault.head.cmd = CMD_SET_DEFAULT; setDefault.head.sn = gizwitsProtocol.sn++; setDefault.head.len = exchangeBytes(sizeof(protocolCommon_t)-4); setDefault.sum = gizProtocolSum((uint8_t *)&setDefault, sizeof(protocolCommon_t)); ret = uartWrite((uint8_t *)&setDefault, sizeof(protocolCommon_t)); if(ret < 0) { GIZWITS_LOG("ERR: uart write error %d \n", ret); } gizProtocolWaitAck((uint8_t *)&setDefault, sizeof(protocolCommon_t)); break; case WIFI_SOFTAP_MODE: gizProtocolHeadInit((protocolHead_t *)&cfgMode); cfgMode.head.cmd = CMD_WIFI_CONFIG; cfgMode.head.sn = gizwitsProtocol.sn++; cfgMode.cfgMode = mode; cfgMode.head.len = exchangeBytes(sizeof(protocolCfgMode_t)-4); cfgMode.sum = gizProtocolSum((uint8_t *)&cfgMode, sizeof(protocolCfgMode_t)); ret = uartWrite((uint8_t *)&cfgMode, sizeof(protocolCfgMode_t)); if(ret < 0) { GIZWITS_LOG("ERR: uart write error %d \n", ret); } gizProtocolWaitAck((uint8_t *)&cfgMode, sizeof(protocolCfgMode_t)); break; case WIFI_AIRLINK_MODE: gizProtocolHeadInit((protocolHead_t *)&cfgMode); cfgMode.head.cmd = CMD_WIFI_CONFIG; cfgMode.head.sn = gizwitsProtocol.sn++; cfgMode.cfgMode = mode; cfgMode.head.len = exchangeBytes(sizeof(protocolCfgMode_t)-4); cfgMode.sum = gizProtocolSum((uint8_t *)&cfgMode, sizeof(protocolCfgMode_t)); ret = uartWrite((uint8_t *)&cfgMode, sizeof(protocolCfgMode_t)); if(ret < 0) { GIZWITS_LOG("ERR: uart write error %d \n", ret); } gizProtocolWaitAck((uint8_t *)&cfgMode, sizeof(protocolCfgMode_t)); break; case WIFI_PRODUCTION_TEST: gizProtocolHeadInit((protocolHead_t *)&setDefault); setDefault.head.cmd = CMD_PRODUCTION_TEST; setDefault.head.sn = gizwitsProtocol.sn++; setDefault.head.len = exchangeBytes(sizeof(protocolCommon_t)-4); setDefault.sum = gizProtocolSum((uint8_t *)&setDefault, sizeof(protocolCommon_t)); ret = uartWrite((uint8_t *)&setDefault, sizeof(protocolCommon_t)); if(ret < 0) { GIZWITS_LOG("ERR: uart write error %d \n", ret); } gizProtocolWaitAck((uint8_t *)&setDefault, sizeof(protocolCommon_t)); break; case WIFI_NINABLE_MODE: gizProtocolHeadInit((protocolHead_t *)&setDefault); setDefault.head.cmd = CMD_NINABLE_MODE; setDefault.head.sn = gizwitsProtocol.sn++; setDefault.head.len = exchangeBytes(sizeof(protocolCommon_t)-4); setDefault.sum = gizProtocolSum((uint8_t *)&setDefault, sizeof(protocolCommon_t)); ret = uartWrite((uint8_t *)&setDefault, sizeof(protocolCommon_t)); if(ret < 0) { GIZWITS_LOG("ERR: uart write error %d \n", ret); } gizProtocolWaitAck((uint8_t *)&setDefault, sizeof(protocolCommon_t)); break; case WIFI_REBOOT_MODE: gizProtocolHeadInit((protocolHead_t *)&setDefault); setDefault.head.cmd = CMD_REBOOT_MODULE; setDefault.head.sn = gizwitsProtocol.sn++; setDefault.head.len = exchangeBytes(sizeof(protocolCommon_t)-4); setDefault.sum = gizProtocolSum((uint8_t *)&setDefault, sizeof(protocolCommon_t)); ret = uartWrite((uint8_t *)&setDefault, sizeof(protocolCommon_t)); if(ret < 0) { GIZWITS_LOG("ERR: uart write error %d \n", ret); } gizProtocolWaitAck((uint8_t *)&setDefault, sizeof(protocolCommon_t)); break; default: GIZWITS_LOG("ERR: CfgMode error!\n"); break; } return ret; } /** * @brief Get the the network time * Protocol 4.13:"Device MCU send" of "the MCU requests access to the network time" * @param[in] none * @return none */ void gizwitsGetNTP(void) { int32_t ret = 0; protocolCommon_t getNTP; gizProtocolHeadInit((protocolHead_t *)&getNTP); getNTP.head.cmd = CMD_GET_NTP; getNTP.head.sn = gizwitsProtocol.sn++; getNTP.head.len = exchangeBytes(sizeof(protocolCommon_t)-4); getNTP.sum = gizProtocolSum((uint8_t *)&getNTP, sizeof(protocolCommon_t)); ret = uartWrite((uint8_t *)&getNTP, sizeof(protocolCommon_t)); if(ret < 0) { GIZWITS_LOG("ERR[NTP]: uart write error %d \n", ret); } gizProtocolWaitAck((uint8_t *)&getNTP, sizeof(protocolCommon_t)); } /** * @brief Get Module Info * * @param[in] none * @return none */ void gizwitsGetModuleInfo(void) { int32_t ret = 0; protocolGetModuleInfo_t getModuleInfo; gizProtocolHeadInit((protocolHead_t *)&getModuleInfo); getModuleInfo.head.cmd = CMD_ASK_MODULE_INFO; getModuleInfo.head.sn = gizwitsProtocol.sn++; getModuleInfo.type = 0x0; getModuleInfo.head.len = exchangeBytes(sizeof(protocolGetModuleInfo_t)-4); getModuleInfo.sum = gizProtocolSum((uint8_t *)&getModuleInfo, sizeof(protocolGetModuleInfo_t)); ret = uartWrite((uint8_t *)&getModuleInfo, sizeof(protocolGetModuleInfo_t)); if(ret < 0) { GIZWITS_LOG("ERR[NTP]: uart write error %d \n", ret); } gizProtocolWaitAck((uint8_t *)&getModuleInfo, sizeof(protocolGetModuleInfo_t)); } /** * @brief Module Info Analyse * * @param [in] head : * * @return 0, Success, , other,Faild */ static int8_t gizProtocolModuleInfoHandle(protocolHead_t *head) { protocolModuleInfo_t *moduleInfo = (protocolModuleInfo_t *)head; if(NULL == head) { GIZWITS_LOG("NTP is empty \n"); return -1; } #if MODULE_TYPE memcpy((uint8_t *)&gizwitsProtocol.gprsInfoNews,(uint8_t *)&moduleInfo->gprsModuleInfo, sizeof(gprsInfo_t)); #else memcpy((uint8_t *)&gizwitsProtocol.wifiModuleNews,(uint8_t *)&moduleInfo->wifiModuleInfo, sizeof(moduleInfo_t)); #endif gizwitsProtocol.moduleInfoEvent.event[gizwitsProtocol.moduleInfoEvent.num] = MODULE_INFO; gizwitsProtocol.moduleInfoEvent.num++; gizwitsProtocol.issuedFlag = GET_MODULEINFO_TYPE; return 0; } /** * @brief Protocol handling function * * @param [in] currentData :The protocol data pointer * @return none */ int32_t gizwitsHandle(dataPoint_t *currentData) { int8_t ret = 0; #ifdef PROTOCOL_DEBUG uint16_t i = 0; #endif uint8_t ackData[RB_MAX_LEN]; uint16_t protocolLen = 0; uint32_t ackLen = 0; protocolHead_t *recvHead = NULL; char *didPtr = NULL; uint16_t offset = 0; if(NULL == currentData) { GIZWITS_LOG("GizwitsHandle Error , Illegal Param\n"); return -1; } /*resend strategy*/ gizProtocolAckHandle(); ret = gizProtocolGetOnePacket(&pRb, gizwitsProtocol.protocolBuf, &protocolLen); if(0 == ret) { GIZWITS_LOG("Get One Packet!\n"); #ifdef PROTOCOL_DEBUG GIZWITS_LOG("WiFi2MCU[%4d:%4d]: ", gizGetTimerCount(), protocolLen); for(i=0; icmd) { case CMD_GET_DEVICE_INTO: gizProtocolGetDeviceInfo(recvHead); break; case CMD_ISSUED_P0: GIZWITS_LOG("flag %x %x \n", recvHead->flags[0], recvHead->flags[1]); //offset = 1; if(0 == gizProtocolIssuedProcess(didPtr, gizwitsProtocol.protocolBuf+sizeof(protocolHead_t)+offset, protocolLen-(sizeof(protocolHead_t)+offset+1), ackData, &ackLen)) { gizProtocolIssuedDataAck(recvHead, ackData, ackLen,recvHead->flags[1]); GIZWITS_LOG("AckData : \n"); } break; case CMD_HEARTBEAT: gizProtocolCommonAck(recvHead); break; case CMD_WIFISTATUS: gizProtocolCommonAck(recvHead); gizProtocolModuleStatus((protocolWifiStatus_t *)recvHead); break; case ACK_REPORT_P0: case ACK_WIFI_CONFIG: case ACK_SET_DEFAULT: case ACK_NINABLE_MODE: case ACK_REBOOT_MODULE: gizProtocolWaitAckCheck(recvHead); break; case CMD_MCU_REBOOT: gizProtocolCommonAck(recvHead); GIZWITS_LOG("report:MCU reboot!\n"); gizProtocolReboot(); break; case CMD_ERROR_PACKAGE: break; case ACK_PRODUCTION_TEST: gizProtocolWaitAckCheck(recvHead); GIZWITS_LOG("Ack PRODUCTION_MODE success \n"); break; case ACK_GET_NTP: gizProtocolWaitAckCheck(recvHead); gizProtocolNTP(recvHead); GIZWITS_LOG("Ack GET_UTT success \n"); break; case ACK_ASK_MODULE_INFO: gizProtocolWaitAckCheck(recvHead); gizProtocolModuleInfoHandle(recvHead); GIZWITS_LOG("Ack GET_Module success \n"); break; default: gizProtocolErrorCmd(recvHead,ERROR_CMD); GIZWITS_LOG("ERR: cmd code error!\n"); break; } } else if(-2 == ret) { //Check failed, report exception recvHead = (protocolHead_t *)gizwitsProtocol.protocolBuf; gizProtocolErrorCmd(recvHead,ERROR_ACK_SUM); GIZWITS_LOG("ERR: check sum error!\n"); return -2; } switch(gizwitsProtocol.issuedFlag) { case ACTION_CONTROL_TYPE: gizwitsProtocol.issuedFlag = STATELESS_TYPE; gizwitsEventProcess(&gizwitsProtocol.issuedProcessEvent, (uint8_t *)&gizwitsProtocol.gizCurrentDataPoint, sizeof(dataPoint_t)); memset((uint8_t *)&gizwitsProtocol.issuedProcessEvent,0x0,sizeof(gizwitsProtocol.issuedProcessEvent)); break; case WIFI_STATUS_TYPE: gizwitsProtocol.issuedFlag = STATELESS_TYPE; gizwitsEventProcess(&gizwitsProtocol.wifiStatusEvent, (uint8_t *)&gizwitsProtocol.wifiStatusData, sizeof(moduleStatusInfo_t)); memset((uint8_t *)&gizwitsProtocol.wifiStatusEvent,0x0,sizeof(gizwitsProtocol.wifiStatusEvent)); break; case ACTION_W2D_TRANSPARENT_TYPE: gizwitsProtocol.issuedFlag = STATELESS_TYPE; gizwitsEventProcess(&gizwitsProtocol.issuedProcessEvent, (uint8_t *)gizwitsProtocol.transparentBuff, gizwitsProtocol.transparentLen); break; case GET_NTP_TYPE: gizwitsProtocol.issuedFlag = STATELESS_TYPE; gizwitsEventProcess(&gizwitsProtocol.NTPEvent, (uint8_t *)&gizwitsProtocol.TimeNTP, sizeof(protocolTime_t)); memset((uint8_t *)&gizwitsProtocol.NTPEvent,0x0,sizeof(gizwitsProtocol.NTPEvent)); break; case GET_MODULEINFO_TYPE: gizwitsProtocol.issuedFlag = STATELESS_TYPE; gizwitsEventProcess(&gizwitsProtocol.moduleInfoEvent, (uint8_t *)&gizwitsProtocol.wifiModuleNews, sizeof(moduleInfo_t)); memset((uint8_t *)&gizwitsProtocol.moduleInfoEvent,0x0,sizeof(moduleInfo_t)); break; default: break; } gizDevReportPolicy(currentData); return 0; } /** * @brief gizwits report transparent data interface * The user can call the interface to complete the reporting of private protocol data * @param [in] data :Private protocol data * @param [in] len :Private protocol data length * @return 0,success ;other,failure */ int32_t gizwitsPassthroughData(uint8_t * gizdata, uint32_t len) { int32_t ret = 0; uint8_t tx_buf[MAX_PACKAGE_LEN]; uint8_t *pTxBuf = tx_buf; uint16_t data_len = 6+len; if(NULL == gizdata) { GIZWITS_LOG("[ERR] gizwitsPassthroughData Error \n"); return (-1); } *pTxBuf ++= 0xFF; *pTxBuf ++= 0xFF; *pTxBuf ++= (uint8_t)(data_len>>8);//len *pTxBuf ++= (uint8_t)(data_len); *pTxBuf ++= CMD_REPORT_P0;//0x1b cmd *pTxBuf ++= gizwitsProtocol.sn++;//sn *pTxBuf ++= 0x00;//flag *pTxBuf ++= 0x00;//flag *pTxBuf ++= ACTION_D2W_TRANSPARENT_DATA;//P0_Cmd memcpy(&tx_buf[9],gizdata,len); tx_buf[data_len + 4 - 1 ] = gizProtocolSum( tx_buf , (data_len+4)); ret = uartWrite(tx_buf, data_len+4); if(ret < 0) { GIZWITS_LOG("ERR: uart write error %d \n", ret); } gizProtocolWaitAck(tx_buf, data_len+4); return 0; } /**@} */ 现在就是连不上网串 resend data ?? P<b#DHT11 OK: T=30, H=60Warning:gizProtocolResendData 461493 461241 1Warning: timeout, resend data ?? P<b#DHT11 OK: T=30, H=60DHT11 OK: T=30, H=60DHT11 OK: T=30, H=60DHT11 OK: T=30, H=60DHT11 OK: T=30, H=60DHT11 OK: T=30, H=60DHT11 OK: T=30, H=60DHT11 OK: T=30, H=60DHT11 OK: T=30, H=60DHT11 OK: T=30, H=60DHT11 OK: T=30, H=60DHT11 OK: T=30, H=60DHT11 OK: T=30, H=60DHT11 OK: T=30, H=60DHT11 OK: T=30, H=60DHT11 OK: T=30, H=60DHT11 OK: T=30, H=60DHT11 OK: T=30, H=60DHT11 OK: T=30, H=60ERR: Failed to rbWrite ERR: Failed to rbWrite ERR: Failed to rbWrite ERR: Failed to rbWrite ERR: Failed to rbWrite ERR: Failed to rbWrite

rbWrite WARN: Failed to queue data: 0x00DHT11 OK: T=29, H=56DHT11 OK: T=29, H=56DHT11 OK: T=29, H=56DHT11 OK: T=29, H=56DHT11 OK: T=29, H=56DHT11 OK: T=29, H=56DHT11 OK: T=29, H=56DHT11 OK: T=29, H=56DHT11 OK: T=29, H=56DHT11 OK: T=29, H=56DHT11 OK: T=29, H=56DHT11 OK: T=29, H=56DHT11 OK: T=29, H=56DHT11 OK: T=29, H=56DHT11 OK: T=29, H=56DHT11 OK: T=29, H=56DHT11 OK: T=29, H=56DHT11 OK: T=29, H=56UART1 and UART2 initialized. ERR: Failed to rbWrite WARN: Failed to queue data: 0x00ERR: Failed to rbWrite WARN: Failed to queue data: 0x00ERR: Failed to rbWrite WARN: Failed to queue data: 0x00ERR: Failed to rbWrite WARN: Failed to queue data: 0x00ERR: Failed to rbWrite WARN: Failed to queue data: 0x00ERR: Failed to rbWrite WARN: Failed to queue data: 0x00ERR: Failed to rbWrite WARN: Failed to queue data: 0x00ERR: Failed to rbWrite WARN: Failed to queue data: 0x00ERR: Failed to rbWrite WARN: Failed to queue data: 0x00rbCreate Success DHT11 OK: T=29, H=56Warning:gizProtocolResendData 590 2 0Resending data, attempt 1/2DHT11 OK: T=29, H=56DHT11 OK: T=29, H=56DHT11 OK: T=29, H=56DHT11 我完全跟着你改为什么还是一样的 /** ************************************************************ * @file gizwits_protocol.c * @brief Corresponding gizwits_product.c header file (including product hardware and software version definition) * @author Gizwits * @date 2017-07-19 * @version V03030000 * @copyright Gizwits * * @note 机智云.只为智能硬件而生 * Gizwits Smart Cloud for Smart Products * 链接|增值ֵ|开放|中立|安全|自有|自由|生态 * www.gizwits.com * ***********************************************************/ #include "ringBuffer.h" #include "gizwits_product.h" #include "dataPointTools.h" #define SEND_MAX_TIME 200 // 单次重发等待时间(毫秒) #define SEND_MIN_INTERVAL 100 // 最小重发间隔(毫秒) /** Protocol global variables **/ gizwitsProtocol_t gizwitsProtocol; /**@name The serial port receives the ring buffer implementation * @{ */ rb_t pRb; ///< Ring buffer structure variable static uint8_t rbBuf[RB_MAX_LEN]; ///< Ring buffer data cache buffer /**@} */ /** * @brief Write data to the ring buffer * @param [in] buf : buf adress * @param [in] len : byte length * @return correct : Returns the length of the written data failure : -1 */ int32_t gizPutData(uint8_t *buf, uint32_t len) { int32_t count = 0; if(NULL == buf) { GIZWITS_LOG("ERR: gizPutData buf is empty \n"); return -1; } count = rbWrite(&pRb, buf, len); if(count != len) { GIZWITS_LOG("ERR: Failed to rbWrite \n"); return -1; } return count; } /** * @brief Protocol header initialization * * @param [out] head : Protocol header pointer * * @return 0, success; other, failure */ static int8_t gizProtocolHeadInit(protocolHead_t *head) { if(NULL == head) { GIZWITS_LOG("ERR: gizProtocolHeadInit head is empty \n"); return -1; } memset((uint8_t *)head, 0, sizeof(protocolHead_t)); head->head[0] = 0xFF; head->head[1] = 0xFF; return 0; } /** * @brief Protocol ACK check processing function * * @param [in] data : data adress * @param [in] len : data length * * @return 0, suceess; other, failure */ static int8_t gizProtocolWaitAck(uint8_t *gizdata, uint32_t len) { if(NULL == gizdata) { GIZWITS_LOG("ERR: data is empty \n"); return -1; } memset((uint8_t *)&gizwitsProtocol.waitAck, 0, sizeof(protocolWaitAck_t)); memcpy((uint8_t *)gizwitsProtocol.waitAck.buf, gizdata, len); gizwitsProtocol.waitAck.dataLen = (uint16_t)len; gizwitsProtocol.waitAck.flag = 1; gizwitsProtocol.waitAck.sendTime = gizGetTimerCount(); return 0; } /** * @brief generates "controlled events" according to protocol * @param [in] issuedData: Controlled data * @param [out] info: event queue * @param [out] dataPoints: data point data * @return 0, the implementation of success, non-0, failed */ static int8_t ICACHE_FLASH_ATTR gizDataPoint2Event(gizwitsIssued_t *issuedData, eventInfo_t *info, dataPoint_t *dataPoints) { if((NULL == issuedData) || (NULL == info) ||(NULL == dataPoints)) { GIZWITS_LOG("gizDataPoint2Event Error , Illegal Param\n"); return -1; } /** Greater than 1 byte to do bit conversion **/ if(sizeof(issuedData->attrFlags) > 1) { if(-1 == gizByteOrderExchange((uint8_t *)&issuedData->attrFlags,sizeof(attrFlags_t))) { GIZWITS_LOG("gizByteOrderExchange Error\n"); return -1; } } if(0x01 == issuedData->attrFlags.flagFan_OnOff) { info->event[info->num] = EVENT_Fan_OnOff; info->num++; dataPoints->valueFan_OnOff = gizStandardDecompressionValue(Fan_OnOff_BYTEOFFSET,Fan_OnOff_BITOFFSET,Fan_OnOff_LEN,(uint8_t *)&issuedData->attrVals.wBitBuf,sizeof(issuedData->attrVals.wBitBuf)); } if(0x01 == issuedData->attrFlags.flagLED_OnOff) { info->event[info->num] = EVENT_LED_OnOff; info->num++; dataPoints->valueLED_OnOff = gizStandardDecompressionValue(LED_OnOff_BYTEOFFSET,LED_OnOff_BITOFFSET,LED_OnOff_LEN,(uint8_t *)&issuedData->attrVals.wBitBuf,sizeof(issuedData->attrVals.wBitBuf)); } return 0; } /** * @brief contrasts the current data with the last data * * @param [in] cur: current data point data * @param [in] last: last data point data * * @return: 0, no change in data; 1, data changes */ static int8_t ICACHE_FLASH_ATTR gizCheckReport(dataPoint_t *cur, dataPoint_t *last) { int8_t ret = 0; static uint32_t lastReportTime = 0; uint32_t currentTime = 0; if((NULL == cur) || (NULL == last)) { GIZWITS_LOG("gizCheckReport Error , Illegal Param\n"); return -1; } currentTime = gizGetTimerCount(); if(last->valueFan_OnOff != cur->valueFan_OnOff) { GIZWITS_LOG("valueFan_OnOff Changed\n"); ret = 1; } if(last->valueLED_OnOff != cur->valueLED_OnOff) { GIZWITS_LOG("valueLED_OnOff Changed\n"); ret = 1; } if(last->valuetemp != cur->valuetemp) { if(currentTime - lastReportTime >= REPORT_TIME_MAX) { GIZWITS_LOG("valuetemp Changed\n"); ret = 1; } } if(last->valuehumi != cur->valuehumi) { if(currentTime - lastReportTime >= REPORT_TIME_MAX) { GIZWITS_LOG("valuehumi Changed\n"); ret = 1; } } if(last->valuelight != cur->valuelight) { if(currentTime - lastReportTime >= REPORT_TIME_MAX) { GIZWITS_LOG("valuelight Changed\n"); ret = 1; } } if(1 == ret) { lastReportTime = gizGetTimerCount(); } return ret; } /** * @brief User data point data is converted to wit the cloud to report data point data * * @param [in] dataPoints: user data point data address * @param [out] devStatusPtr: wit the cloud data point data address * * @return 0, the correct return; -1, the error returned */ static int8_t ICACHE_FLASH_ATTR gizDataPoints2ReportData(dataPoint_t *dataPoints , devStatus_t *devStatusPtr) { if((NULL == dataPoints) || (NULL == devStatusPtr)) { GIZWITS_LOG("gizDataPoints2ReportData Error , Illegal Param\n"); return -1; } gizMemset((uint8_t *)devStatusPtr->wBitBuf,0,sizeof(devStatusPtr->wBitBuf)); gizStandardCompressValue(Fan_OnOff_BYTEOFFSET,Fan_OnOff_BITOFFSET,Fan_OnOff_LEN,(uint8_t *)devStatusPtr,dataPoints->valueFan_OnOff); gizStandardCompressValue(LED_OnOff_BYTEOFFSET,LED_OnOff_BITOFFSET,LED_OnOff_LEN,(uint8_t *)devStatusPtr,dataPoints->valueLED_OnOff); gizByteOrderExchange((uint8_t *)devStatusPtr->wBitBuf,sizeof(devStatusPtr->wBitBuf)); devStatusPtr->valuetemp = gizY2X(temp_RATIO, temp_ADDITION, dataPoints->valuetemp); devStatusPtr->valuehumi = gizY2X(humi_RATIO, humi_ADDITION, dataPoints->valuehumi); devStatusPtr->valuelight = exchangeBytes(gizY2X(light_RATIO, light_ADDITION, dataPoints->valuelight)); return 0; } /** * @brief This function is called by the Gagent module to receive the relevant protocol data from the cloud or APP * @param [in] inData The protocol data entered * @param [in] inLen Enter the length of the data * @param [out] outData The output of the protocol data * @param [out] outLen The length of the output data * @return 0, the implementation of success, non-0, failed */ static int8_t gizProtocolIssuedProcess(char *did, uint8_t *inData, uint32_t inLen, uint8_t *outData, uint32_t *outLen) { uint8_t issuedAction = inData[0]; if((NULL == inData)||(NULL == outData)||(NULL == outLen)) { GIZWITS_LOG("gizProtocolIssuedProcess Error , Illegal Param\n"); return -1; } if(NULL == did) { memset((uint8_t *)&gizwitsProtocol.issuedProcessEvent, 0, sizeof(eventInfo_t)); switch(issuedAction) { case ACTION_CONTROL_DEVICE: gizDataPoint2Event((gizwitsIssued_t *)&inData[1], &gizwitsProtocol.issuedProcessEvent,&gizwitsProtocol.gizCurrentDataPoint); gizwitsProtocol.issuedFlag = ACTION_CONTROL_TYPE; outData = NULL; *outLen = 0; break; case ACTION_READ_DEV_STATUS: if(0 == gizDataPoints2ReportData(&gizwitsProtocol.gizLastDataPoint,&gizwitsProtocol.reportData.devStatus)) { memcpy(outData+1, (uint8_t *)&gizwitsProtocol.reportData.devStatus, sizeof(gizwitsReport_t)); outData[0] = ACTION_READ_DEV_STATUS_ACK; *outLen = sizeof(gizwitsReport_t)+1; } else { return -1; } break; case ACTION_W2D_TRANSPARENT_DATA: memcpy(gizwitsProtocol.transparentBuff, &inData[1], inLen-1); gizwitsProtocol.transparentLen = inLen - 1; gizwitsProtocol.issuedProcessEvent.event[gizwitsProtocol.issuedProcessEvent.num] = TRANSPARENT_DATA; gizwitsProtocol.issuedProcessEvent.num++; gizwitsProtocol.issuedFlag = ACTION_W2D_TRANSPARENT_TYPE; outData = NULL; *outLen = 0; break; default: break; } } return 0; } /** * @brief The protocol sends data back , P0 ACK * * @param [in] head : Protocol head pointer * @param [in] data : Payload data * @param [in] len : Payload data length * @param [in] proFlag : DID flag ,1 for Virtual sub device did ,0 for single product or gateway * * @return : 0,Ack success; * -1,Input Param Illegal * -2,Serial send faild */ static int32_t gizProtocolIssuedDataAck(protocolHead_t *head, uint8_t *gizdata, uint32_t len, uint8_t proFlag) { int32_t ret = 0; uint8_t tx_buf[RB_MAX_LEN]; uint32_t offset = 0; uint8_t sDidLen = 0; uint16_t data_len = 0; uint8_t *pTxBuf = tx_buf; if(NULL == gizdata) { GIZWITS_LOG("[ERR] data Is Null \n"); return -1; } if(0x1 == proFlag) { sDidLen = *((uint8_t *)head + sizeof(protocolHead_t)); data_len = 5 + 1 + sDidLen + len; } else { data_len = 5 + len; } GIZWITS_LOG("len = %d , sDidLen = %d ,data_len = %d\n", len,sDidLen,data_len); *pTxBuf ++= 0xFF; *pTxBuf ++= 0xFF; *pTxBuf ++= (uint8_t)(data_len>>8); *pTxBuf ++= (uint8_t)(data_len); *pTxBuf ++= head->cmd + 1; *pTxBuf ++= head->sn; *pTxBuf ++= 0x00; *pTxBuf ++= proFlag; offset = 8; if(0x1 == proFlag) { *pTxBuf ++= sDidLen; offset += 1; memcpy(&tx_buf[offset],(uint8_t *)head+sizeof(protocolHead_t)+1,sDidLen); offset += sDidLen; pTxBuf += sDidLen; } if(0 != len) { memcpy(&tx_buf[offset],gizdata,len); } tx_buf[data_len + 4 - 1 ] = gizProtocolSum( tx_buf , (data_len+4)); ret = uartWrite(tx_buf, data_len+4); if(ret < 0) { GIZWITS_LOG("uart write error %d \n", ret); return -2; } return 0; } /** * @brief Report data interface * * @param [in] action : PO action * @param [in] data : Payload data * @param [in] len : Payload data length * * @return : 0,Ack success; * -1,Input Param Illegal * -2,Serial send faild */ static int32_t gizReportData(uint8_t action, uint8_t *gizdata, uint32_t len) { int32_t ret = 0; protocolReport_t protocolReport; if(NULL == gizdata) { GIZWITS_LOG("gizReportData Error , Illegal Param\n"); return -1; } gizProtocolHeadInit((protocolHead_t *)&protocolReport); protocolReport.head.cmd = CMD_REPORT_P0; protocolReport.head.sn = gizwitsProtocol.sn++; protocolReport.action = action; protocolReport.head.len = exchangeBytes(sizeof(protocolReport_t)-4); memcpy((gizwitsReport_t *)&protocolReport.reportData, (gizwitsReport_t *)gizdata,len); protocolReport.sum = gizProtocolSum((uint8_t *)&protocolReport, sizeof(protocolReport_t)); ret = uartWrite((uint8_t *)&protocolReport, sizeof(protocolReport_t)); if(ret < 0) { GIZWITS_LOG("ERR: uart write error %d \n", ret); return -2; } gizProtocolWaitAck((uint8_t *)&protocolReport, sizeof(protocolReport_t)); return ret; }/** * @brief Datapoints reporting mechanism * * 1. Changes are reported immediately * 2. Data timing report , 600000 Millisecond * *@param [in] currentData : Current datapoints value * @return : NULL */ static void gizDevReportPolicy(dataPoint_t *currentData) { static uint32_t lastRepTime = 0; uint32_t timeNow = gizGetTimerCount(); if((1 == gizCheckReport(currentData, (dataPoint_t *)&gizwitsProtocol.gizLastDataPoint))) { GIZWITS_LOG("changed, report data\n"); if(0 == gizDataPoints2ReportData(currentData,&gizwitsProtocol.reportData.devStatus)) { gizReportData(ACTION_REPORT_DEV_STATUS, (uint8_t *)&gizwitsProtocol.reportData.devStatus, sizeof(devStatus_t)); } memcpy((uint8_t *)&gizwitsProtocol.gizLastDataPoint, (uint8_t *)currentData, sizeof(dataPoint_t)); } if((0 == (timeNow % (600000))) && (lastRepTime != timeNow)) { GIZWITS_LOG("Info: 600S report data\n"); if(0 == gizDataPoints2ReportData(currentData,&gizwitsProtocol.reportData.devStatus)) { gizReportData(ACTION_REPORT_DEV_STATUS, (uint8_t *)&gizwitsProtocol.reportData.devStatus, sizeof(devStatus_t)); } memcpy((uint8_t *)&gizwitsProtocol.gizLastDataPoint, (uint8_t *)currentData, sizeof(dataPoint_t)); lastRepTime = timeNow; } } /** * @brief Get a packet of data from the ring buffer * * @param [in] rb : Input data address * @param [out] data : Output data address * @param [out] len : Output data length * * @return : 0,Return correct ;-1,Return failure;-2,Data check failure */ static int8_t gizProtocolGetOnePacket(rb_t *rb, uint8_t *gizdata, uint16_t *len) { int32_t ret = 0; uint8_t sum = 0; int32_t i = 0; uint8_t tmpData; uint16_t tmpLen = 0; uint16_t tmpCount = 0; static uint8_t protocolFlag = 0; static uint16_t protocolCount = 0; static uint8_t lastData = 0; static uint8_t debugCount = 0; uint8_t *protocolBuff = gizdata; protocolHead_t *head = NULL; if((NULL == rb) || (NULL == gizdata) ||(NULL == len)) { GIZWITS_LOG("gizProtocolGetOnePacket Error , Illegal Param\n"); return -1; } tmpLen = rbCanRead(rb); if(0 == tmpLen) { return -1; } for(i=0; i<tmpLen; i++) { ret = rbRead(rb, &tmpData, 1); if(0 != ret) { if((0xFF == lastData) && (0xFF == tmpData)) { if(0 == protocolFlag) { protocolBuff[0] = 0xFF; protocolBuff[1] = 0xFF; protocolCount = 2; protocolFlag = 1; } else { if((protocolCount > 4) && (protocolCount != tmpCount)) { protocolBuff[0] = 0xFF; protocolBuff[1] = 0xFF; protocolCount = 2; } } } else if((0xFF == lastData) && (0x55 == tmpData)) { } else { if(1 == protocolFlag) { protocolBuff[protocolCount] = tmpData; protocolCount++; if(protocolCount > 4) { head = (protocolHead_t *)protocolBuff; tmpCount = exchangeBytes(head->len)+4; if (tmpCount >= MAX_PACKAGE_LEN || tmpCount <= 4) { protocolFlag = 0; protocolCount = 0; GIZWITS_LOG("ERR:the data length is too long or too small, will abandon \n"); } if(protocolCount == tmpCount) { break; } } } } lastData = tmpData; debugCount++; } } if((protocolCount > 4) && (protocolCount == tmpCount)) { sum = gizProtocolSum(protocolBuff, protocolCount); if(protocolBuff[protocolCount-1] == sum) { *len = tmpCount; protocolFlag = 0; protocolCount = 0; debugCount = 0; lastData = 0; return 0; } else { protocolFlag = 0; protocolCount = 0; return -2; } } return 1; } /** * @brief Protocol data resend * The protocol data resend when check timeout and meet the resend limiting * @param none * * @return none */ static void gizProtocolResendData(void) { if(0 == gizwitsProtocol.waitAck.flag || gizwitsProtocol.waitAck.num >= SEND_MAX_NUM) { return; } uint32_t now = gizGetTimerCount(); if(now - gizwitsProtocol.waitAck.sendTime < SEND_MIN_INTERVAL) { return; } GIZWITS_LOG("Resending data, attempt %d/%d\n", gizwitsProtocol.waitAck.num+1, SEND_MAX_NUM); int ret = uartWrite(gizwitsProtocol.waitAck.buf, gizwitsProtocol.waitAck.dataLen); if(ret == gizwitsProtocol.waitAck.dataLen) { gizwitsProtocol.waitAck.sendTime = now; gizwitsProtocol.waitAck.num++; } else { GIZWITS_LOG("ERR: resend failed, ret=%d\n", ret); } } /** * @brief Clear the ACK protocol message * * @param [in] head : Protocol header address * * @return 0, success; other, failure */ static int8_t gizProtocolWaitAckCheck(protocolHead_t *head) { protocolHead_t *waitAckHead = (protocolHead_t *)gizwitsProtocol.waitAck.buf; if(NULL == head) { GIZWITS_LOG("ERR: data is empty \n"); return -1; } if(waitAckHead->cmd+1 == head->cmd) { memset((uint8_t *)&gizwitsProtocol.waitAck, 0, sizeof(protocolWaitAck_t)); } return 0; } /** * @brief Send general protocol message data * * @param [in] head : Protocol header address * * @return : Return effective data length;-1,return failure */ static int32_t gizProtocolCommonAck(protocolHead_t *head) { int32_t ret = 0; protocolCommon_t ack; if(NULL == head) { GIZWITS_LOG("ERR: gizProtocolCommonAck data is empty \n"); return -1; } memcpy((uint8_t *)&ack, (uint8_t *)head, sizeof(protocolHead_t)); ack.head.cmd = ack.head.cmd+1; ack.head.len = exchangeBytes(sizeof(protocolCommon_t)-4); ack.sum = gizProtocolSum((uint8_t *)&ack, sizeof(protocolCommon_t)); ret = uartWrite((uint8_t *)&ack, sizeof(protocolCommon_t)); if(ret < 0) { GIZWITS_LOG("ERR: uart write error %d \n", ret); } return ret; } /** * @brief ACK processing function * Time-out 200ms no ACK resend,resend two times at most * @param none * * @return none */ static void gizProtocolAckHandle(void) { if(1 == gizwitsProtocol.waitAck.flag) { if(SEND_MAX_NUM > gizwitsProtocol.waitAck.num) { // Time-out no ACK resend if(SEND_MAX_TIME < (gizGetTimerCount() - gizwitsProtocol.waitAck.sendTime)) { GIZWITS_LOG("Warning:gizProtocolResendData %d %d %d\n", gizGetTimerCount(), gizwitsProtocol.waitAck.sendTime, gizwitsProtocol.waitAck.num); gizProtocolResendData(); gizwitsProtocol.waitAck.num++; } } else { memset((uint8_t *)&gizwitsProtocol.waitAck, 0, sizeof(protocolWaitAck_t)); } } } /** * @brief Protocol 4.1 WiFi module requests device information * * @param[in] head : Protocol header address * * @return Return effective data length;-1,return failure */ static int32_t gizProtocolGetDeviceInfo(protocolHead_t * head) { int32_t ret = 0; protocolDeviceInfo_t deviceInfo; if(NULL == head) { GIZWITS_LOG("gizProtocolGetDeviceInfo Error , Illegal Param\n"); return -1; } gizProtocolHeadInit((protocolHead_t *)&deviceInfo); deviceInfo.head.cmd = ACK_GET_DEVICE_INFO; deviceInfo.head.sn = head->sn; memcpy((uint8_t *)deviceInfo.protocolVer, protocol_VERSION, 8); memcpy((uint8_t *)deviceInfo.p0Ver, P0_VERSION, 8); memcpy((uint8_t *)deviceInfo.softVer, SOFTWARE_VERSION, 8); memcpy((uint8_t *)deviceInfo.hardVer, HARDWARE_VERSION, 8); memcpy((uint8_t *)deviceInfo.productKey, PRODUCT_KEY, strlen(PRODUCT_KEY)); memcpy((uint8_t *)deviceInfo.productSecret, PRODUCT_SECRET, strlen(PRODUCT_SECRET)); memset((uint8_t *)deviceInfo.devAttr, 0, 8); deviceInfo.devAttr[7] |= DEV_IS_GATEWAY<<0; deviceInfo.devAttr[7] |= (0x01<<1); deviceInfo.ninableTime = exchangeBytes(NINABLETIME); #ifdef DATA_CONFIG_ENABLE deviceInfo.DataLen = exchangeBytes(GIZ_DATA_LEN); sprintf(deviceInfo.Data,"apName=%s&apPwd=%s&cfgMode=%s",AP_NAME,AP_PWD,CFG_MODE); #endif deviceInfo.head.len = exchangeBytes(sizeof(protocolDeviceInfo_t)-4); deviceInfo.sum = gizProtocolSum((uint8_t *)&deviceInfo, sizeof(protocolDeviceInfo_t)); ret = uartWrite((uint8_t *)&deviceInfo, sizeof(protocolDeviceInfo_t)); if(ret < 0) { GIZWITS_LOG("ERR: uart write error %d \n", ret); } return ret; } /** * @brief Protocol 4.7 Handling of illegal message notification * @param[in] head : Protocol header address * @param[in] errno : Illegal message notification type * @return 0, success; other, failure */ static int32_t gizProtocolErrorCmd(protocolHead_t *head,errorPacketsType_t errno) { int32_t ret = 0; protocolErrorType_t errorType; if(NULL == head) { GIZWITS_LOG("gizProtocolErrorCmd Error , Illegal Param\n"); return -1; } gizProtocolHeadInit((protocolHead_t *)&errorType); errorType.head.cmd = ACK_ERROR_PACKAGE; errorType.head.sn = head->sn; errorType.head.len = exchangeBytes(sizeof(protocolErrorType_t)-4); errorType.error = errno; errorType.sum = gizProtocolSum((uint8_t *)&errorType, sizeof(protocolErrorType_t)); ret = uartWrite((uint8_t *)&errorType, sizeof(protocolErrorType_t)); if(ret < 0) { GIZWITS_LOG("ERR: uart write error %d \n", ret); } return ret; } /** * @brief Protocol 4.13 Get and process network time * * @param [in] head : Protocol header address * * @return 0, success; other, failure */ static int8_t gizProtocolNTP(protocolHead_t *head) { protocolUTT_t *UTTInfo = (protocolUTT_t *)head; if(NULL == head) { GIZWITS_LOG("ERR: NTP is empty \n"); return -1; } memcpy((uint8_t *)&gizwitsProtocol.TimeNTP.year,(uint8_t *)UTTInfo->time, 7); memcpy((uint8_t *)&gizwitsProtocol.TimeNTP.ntp,(uint8_t *)UTTInfo->ntp_time, 4); gizwitsProtocol.TimeNTP.year = exchangeBytes(gizwitsProtocol.TimeNTP.year); gizwitsProtocol.TimeNTP.ntp =exchangeWord(gizwitsProtocol.TimeNTP.ntp); gizwitsProtocol.NTPEvent.event[gizwitsProtocol.NTPEvent.num] = WIFI_NTP; gizwitsProtocol.NTPEvent.num++; gizwitsProtocol.issuedFlag = GET_NTP_TYPE; return 0; } /** * @brief Protocol 4.4 Device MCU restarts function * @param none * @return none */ static void gizProtocolReboot(void) { uint32_t timeDelay = gizGetTimerCount(); /*Wait 600ms*/ while((gizGetTimerCount() - timeDelay) <= 600); mcuRestart(); } /** * @brief Protocol 4.5 :The WiFi module informs the device MCU of working status about the WiFi module * @param[in] status WiFi module working status * @return none */ static int8_t gizProtocolModuleStatus(protocolWifiStatus_t *status) { static wifiStatus_t lastStatus; if(NULL == status) { GIZWITS_LOG("gizProtocolModuleStatus Error , Illegal Param\n"); return -1; } status->ststus.value = exchangeBytes(status->ststus.value); //OnBoarding mode status if(lastStatus.types.onboarding != status->ststus.types.onboarding) { if(1 == status->ststus.types.onboarding) { if(1 == status->ststus.types.softap) { gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_SOFTAP; gizwitsProtocol.wifiStatusEvent.num++; GIZWITS_LOG("OnBoarding: SoftAP or Web mode\n"); } if(1 == status->ststus.types.station) { gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_AIRLINK; gizwitsProtocol.wifiStatusEvent.num++; GIZWITS_LOG("OnBoarding: AirLink mode\n"); } } else { if(1 == status->ststus.types.softap) { gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_SOFTAP; gizwitsProtocol.wifiStatusEvent.num++; GIZWITS_LOG("OnBoarding: SoftAP or Web mode\n"); } if(1 == status->ststus.types.station) { gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_STATION; gizwitsProtocol.wifiStatusEvent.num++; GIZWITS_LOG("OnBoarding: Station mode\n"); } } } //binding mode status if(lastStatus.types.binding != status->ststus.types.binding) { lastStatus.types.binding = status->ststus.types.binding; if(1 == status->ststus.types.binding) { gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_OPEN_BINDING; gizwitsProtocol.wifiStatusEvent.num++; GIZWITS_LOG("WiFi status: in binding mode\n"); } else { gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_CLOSE_BINDING; gizwitsProtocol.wifiStatusEvent.num++; GIZWITS_LOG("WiFi status: out binding mode\n"); } } //router status if(lastStatus.types.con_route != status->ststus.types.con_route) { lastStatus.types.con_route = status->ststus.types.con_route; if(1 == status->ststus.types.con_route) { gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_CON_ROUTER; gizwitsProtocol.wifiStatusEvent.num++; GIZWITS_LOG("WiFi status: connected router\n"); } else { gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_DISCON_ROUTER; gizwitsProtocol.wifiStatusEvent.num++; GIZWITS_LOG("WiFi status: disconnected router\n"); } } //M2M server status if(lastStatus.types.con_m2m != status->ststus.types.con_m2m) { lastStatus.types.con_m2m = status->ststus.types.con_m2m; if(1 == status->ststus.types.con_m2m) { gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_CON_M2M; gizwitsProtocol.wifiStatusEvent.num++; GIZWITS_LOG("WiFi status: connected m2m\n"); } else { gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_DISCON_M2M; gizwitsProtocol.wifiStatusEvent.num++; GIZWITS_LOG("WiFi status: disconnected m2m\n"); } } //APP status if(lastStatus.types.app != status->ststus.types.app) { lastStatus.types.app = status->ststus.types.app; if(1 == status->ststus.types.app) { gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_CON_APP; gizwitsProtocol.wifiStatusEvent.num++; GIZWITS_LOG("WiFi status: app connect\n"); } else { gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_DISCON_APP; gizwitsProtocol.wifiStatusEvent.num++; GIZWITS_LOG("WiFi status: no app connect\n"); } } //test mode status if(lastStatus.types.test != status->ststus.types.test) { lastStatus.types.test = status->ststus.types.test; if(1 == status->ststus.types.test) { gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_OPEN_TESTMODE; gizwitsProtocol.wifiStatusEvent.num++; GIZWITS_LOG("WiFi status: in test mode\n"); } else { gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_CLOSE_TESTMODE; gizwitsProtocol.wifiStatusEvent.num++; GIZWITS_LOG("WiFi status: out test mode\n"); } } gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_RSSI; gizwitsProtocol.wifiStatusEvent.num++; gizwitsProtocol.wifiStatusData.rssi = status->ststus.types.rssi; GIZWITS_LOG("RSSI is %d \n", gizwitsProtocol.wifiStatusData.rssi); gizwitsProtocol.issuedFlag = WIFI_STATUS_TYPE; return 0; } /**@name Gizwits User API interface * @{ */ /** * @brief gizwits Protocol initialization interface * Protocol-related timer, serial port initialization * Datapoint initialization * @param none * @return none */ void gizwitsInit(void) { pRb.rbCapacity = RB_MAX_LEN; pRb.rbBuff = rbBuf; if(0 == rbCreate(&pRb)) { GIZWITS_LOG("rbCreate Success \n"); } else { GIZWITS_LOG("rbCreate Faild \n"); } memset((uint8_t *)&gizwitsProtocol, 0, sizeof(gizwitsProtocol_t)); } /** * @brief WiFi configure interface * Set the WiFi module into the corresponding configuration mode or reset the module * @param[in] mode :0x0, reset the module ;0x01, SoftAp mode ;0x02, AirLink mode ;0x03, Production test mode; 0x04:allow users to bind devices * @return Error command code */ int32_t gizwitsSetMode(uint8_t mode) { int32_t ret = 0; protocolCfgMode_t cfgMode; protocolCommon_t setDefault; switch(mode) { case WIFI_RESET_MODE: gizProtocolHeadInit((protocolHead_t *)&setDefault); setDefault.head.cmd = CMD_SET_DEFAULT; setDefault.head.sn = gizwitsProtocol.sn++; setDefault.head.len = exchangeBytes(sizeof(protocolCommon_t)-4); setDefault.sum = gizProtocolSum((uint8_t *)&setDefault, sizeof(protocolCommon_t)); ret = uartWrite((uint8_t *)&setDefault, sizeof(protocolCommon_t)); if(ret < 0) { GIZWITS_LOG("ERR: uart write error %d \n", ret); } gizProtocolWaitAck((uint8_t *)&setDefault, sizeof(protocolCommon_t)); break; case WIFI_SOFTAP_MODE: gizProtocolHeadInit((protocolHead_t *)&cfgMode); cfgMode.head.cmd = CMD_WIFI_CONFIG; cfgMode.head.sn = gizwitsProtocol.sn++; cfgMode.cfgMode = mode; cfgMode.head.len = exchangeBytes(sizeof(protocolCfgMode_t)-4); cfgMode.sum = gizProtocolSum((uint8_t *)&cfgMode, sizeof(protocolCfgMode_t)); ret = uartWrite((uint8_t *)&cfgMode, sizeof(protocolCfgMode_t)); if(ret < 0) { GIZWITS_LOG("ERR: uart write error %d \n", ret); } gizProtocolWaitAck((uint8_t *)&cfgMode, sizeof(protocolCfgMode_t)); break; case WIFI_AIRLINK_MODE: gizProtocolHeadInit((protocolHead_t *)&cfgMode); cfgMode.head.cmd = CMD_WIFI_CONFIG; cfgMode.head.sn = gizwitsProtocol.sn++; cfgMode.cfgMode = mode; cfgMode.head.len = exchangeBytes(sizeof(protocolCfgMode_t)-4); cfgMode.sum = gizProtocolSum((uint8_t *)&cfgMode, sizeof(protocolCfgMode_t)); ret = uartWrite((uint8_t *)&cfgMode, sizeof(protocolCfgMode_t)); if(ret < 0) { GIZWITS_LOG("ERR: uart write error %d \n", ret); } gizProtocolWaitAck((uint8_t *)&cfgMode, sizeof(protocolCfgMode_t)); break; case WIFI_PRODUCTION_TEST: gizProtocolHeadInit((protocolHead_t *)&setDefault); setDefault.head.cmd = CMD_PRODUCTION_TEST; setDefault.head.sn = gizwitsProtocol.sn++; setDefault.head.len = exchangeBytes(sizeof(protocolCommon_t)-4); setDefault.sum = gizProtocolSum((uint8_t *)&setDefault, sizeof(protocolCommon_t)); ret = uartWrite((uint8_t *)&setDefault, sizeof(protocolCommon_t)); if(ret < 0) { GIZWITS_LOG("ERR: uart write error %d \n", ret); } gizProtocolWaitAck((uint8_t *)&setDefault, sizeof(protocolCommon_t)); break; case WIFI_NINABLE_MODE: gizProtocolHeadInit((protocolHead_t *)&setDefault); setDefault.head.cmd = CMD_NINABLE_MODE; setDefault.head.sn = gizwitsProtocol.sn++; setDefault.head.len = exchangeBytes(sizeof(protocolCommon_t)-4); setDefault.sum = gizProtocolSum((uint8_t *)&setDefault, sizeof(protocolCommon_t)); ret = uartWrite((uint8_t *)&setDefault, sizeof(protocolCommon_t)); if(ret < 0) { GIZWITS_LOG("ERR: uart write error %d \n", ret); } gizProtocolWaitAck((uint8_t *)&setDefault, sizeof(protocolCommon_t)); break; case WIFI_REBOOT_MODE: gizProtocolHeadInit((protocolHead_t *)&setDefault); setDefault.head.cmd = CMD_REBOOT_MODULE; setDefault.head.sn = gizwitsProtocol.sn++; setDefault.head.len = exchangeBytes(sizeof(protocolCommon_t)-4); setDefault.sum = gizProtocolSum((uint8_t *)&setDefault, sizeof(protocolCommon_t)); ret = uartWrite((uint8_t *)&setDefault, sizeof(protocolCommon_t)); if(ret < 0) { GIZWITS_LOG("ERR: uart write error %d \n", ret); } gizProtocolWaitAck((uint8_t *)&setDefault, sizeof(protocolCommon_t)); break; default: GIZWITS_LOG("ERR: CfgMode error!\n"); break; } return ret; } /** * @brief Get the the network time * Protocol 4.13:"Device MCU send" of "the MCU requests access to the network time" * @param[in] none * @return none */ void gizwitsGetNTP(void) { int32_t ret = 0; protocolCommon_t getNTP; gizProtocolHeadInit((protocolHead_t *)&getNTP); getNTP.head.cmd = CMD_GET_NTP; getNTP.head.sn = gizwitsProtocol.sn++; getNTP.head.len = exchangeBytes(sizeof(protocolCommon_t)-4); getNTP.sum = gizProtocolSum((uint8_t *)&getNTP, sizeof(protocolCommon_t)); ret = uartWrite((uint8_t *)&getNTP, sizeof(protocolCommon_t)); if(ret < 0) { GIZWITS_LOG("ERR[NTP]: uart write error %d \n", ret); } gizProtocolWaitAck((uint8_t *)&getNTP, sizeof(protocolCommon_t)); } /** * @brief Get Module Info * * @param[in] none * @return none */ void gizwitsGetModuleInfo(void) { int32_t ret = 0; protocolGetModuleInfo_t getModuleInfo; gizProtocolHeadInit((protocolHead_t *)&getModuleInfo); getModuleInfo.head.cmd = CMD_ASK_MODULE_INFO; getModuleInfo.head.sn = gizwitsProtocol.sn++; getModuleInfo.type = 0x0; getModuleInfo.head.len = exchangeBytes(sizeof(protocolGetModuleInfo_t)-4); getModuleInfo.sum = gizProtocolSum((uint8_t *)&getModuleInfo, sizeof(protocolGetModuleInfo_t)); ret = uartWrite((uint8_t *)&getModuleInfo, sizeof(protocolGetModuleInfo_t)); if(ret < 0) { GIZWITS_LOG("ERR[NTP]: uart write error %d \n", ret); } gizProtocolWaitAck((uint8_t *)&getModuleInfo, sizeof(protocolGetModuleInfo_t)); } /** * @brief Module Info Analyse * * @param [in] head : * * @return 0, Success, , other,Faild */ static int8_t gizProtocolModuleInfoHandle(protocolHead_t *head) { protocolModuleInfo_t *moduleInfo = (protocolModuleInfo_t *)head; if(NULL == head) { GIZWITS_LOG("NTP is empty \n"); return -1; } #if MODULE_TYPE memcpy((uint8_t *)&gizwitsProtocol.gprsInfoNews,(uint8_t *)&moduleInfo->gprsModuleInfo, sizeof(gprsInfo_t)); #else memcpy((uint8_t *)&gizwitsProtocol.wifiModuleNews,(uint8_t *)&moduleInfo->wifiModuleInfo, sizeof(moduleInfo_t)); #endif gizwitsProtocol.moduleInfoEvent.event[gizwitsProtocol.moduleInfoEvent.num] = MODULE_INFO; gizwitsProtocol.moduleInfoEvent.num++; gizwitsProtocol.issuedFlag = GET_MODULEINFO_TYPE; return 0; } /** * @brief Protocol handling function * * @param [in] currentData :The protocol data pointer * @return none */ int32_t gizwitsHandle(dataPoint_t *currentData) { int8_t ret = 0; #ifdef PROTOCOL_DEBUG uint16_t i = 0; #endif uint8_t ackData[RB_MAX_LEN]; uint16_t protocolLen = 0; uint32_t ackLen = 0; protocolHead_t *recvHead = NULL; char *didPtr = NULL; uint16_t offset = 0; if(NULL == currentData) { GIZWITS_LOG("GizwitsHandle Error , Illegal Param\n"); return -1; } /*resend strategy*/ gizProtocolAckHandle(); ret = gizProtocolGetOnePacket(&pRb, gizwitsProtocol.protocolBuf, &protocolLen); if(0 == ret) { GIZWITS_LOG("Get One Packet!\n"); #ifdef PROTOCOL_DEBUG GIZWITS_LOG("WiFi2MCU[%4d:%4d]: ", gizGetTimerCount(), protocolLen); for(i=0; icmd) { case CMD_GET_DEVICE_INTO: gizProtocolGetDeviceInfo(recvHead); break; case CMD_ISSUED_P0: GIZWITS_LOG("flag %x %x \n", recvHead->flags[0], recvHead->flags[1]); //offset = 1; if(0 == gizProtocolIssuedProcess(didPtr, gizwitsProtocol.protocolBuf+sizeof(protocolHead_t)+offset, protocolLen-(sizeof(protocolHead_t)+offset+1), ackData, &ackLen)) { gizProtocolIssuedDataAck(recvHead, ackData, ackLen,recvHead->flags[1]); GIZWITS_LOG("AckData : \n"); } break; case CMD_HEARTBEAT: gizProtocolCommonAck(recvHead); break; case CMD_WIFISTATUS: gizProtocolCommonAck(recvHead); gizProtocolModuleStatus((protocolWifiStatus_t *)recvHead); break; case ACK_REPORT_P0: case ACK_WIFI_CONFIG: case ACK_SET_DEFAULT: case ACK_NINABLE_MODE: case ACK_REBOOT_MODULE: gizProtocolWaitAckCheck(recvHead); break; case CMD_MCU_REBOOT: gizProtocolCommonAck(recvHead); GIZWITS_LOG("report:MCU reboot!\n"); gizProtocolReboot(); break; case CMD_ERROR_PACKAGE: break; case ACK_PRODUCTION_TEST: gizProtocolWaitAckCheck(recvHead); GIZWITS_LOG("Ack PRODUCTION_MODE success \n"); break; case ACK_GET_NTP: gizProtocolWaitAckCheck(recvHead); gizProtocolNTP(recvHead); GIZWITS_LOG("Ack GET_UTT success \n"); break; case ACK_ASK_MODULE_INFO: gizProtocolWaitAckCheck(recvHead); gizProtocolModuleInfoHandle(recvHead); GIZWITS_LOG("Ack GET_Module success \n"); break; default: gizProtocolErrorCmd(recvHead,ERROR_CMD); GIZWITS_LOG("ERR: cmd code error!\n"); break; } } else if(-2 == ret) { //Check failed, report exception recvHead = (protocolHead_t *)gizwitsProtocol.protocolBuf; gizProtocolErrorCmd(recvHead,ERROR_ACK_SUM); GIZWITS_LOG("ERR: check sum error!\n"); return -2; } switch(gizwitsProtocol.issuedFlag) { case ACTION_CONTROL_TYPE: gizwitsProtocol.issuedFlag = STATELESS_TYPE; gizwitsEventProcess(&gizwitsProtocol.issuedProcessEvent, (uint8_t *)&gizwitsProtocol.gizCurrentDataPoint, sizeof(dataPoint_t)); memset((uint8_t *)&gizwitsProtocol.issuedProcessEvent,0x0,sizeof(gizwitsProtocol.issuedProcessEvent)); break; case WIFI_STATUS_TYPE: gizwitsProtocol.issuedFlag = STATELESS_TYPE; gizwitsEventProcess(&gizwitsProtocol.wifiStatusEvent, (uint8_t *)&gizwitsProtocol.wifiStatusData, sizeof(moduleStatusInfo_t)); memset((uint8_t *)&gizwitsProtocol.wifiStatusEvent,0x0,sizeof(gizwitsProtocol.wifiStatusEvent)); break; case ACTION_W2D_TRANSPARENT_TYPE: gizwitsProtocol.issuedFlag = STATELESS_TYPE; gizwitsEventProcess(&gizwitsProtocol.issuedProcessEvent, (uint8_t *)gizwitsProtocol.transparentBuff, gizwitsProtocol.transparentLen); break; case GET_NTP_TYPE: gizwitsProtocol.issuedFlag = STATELESS_TYPE; gizwitsEventProcess(&gizwitsProtocol.NTPEvent, (uint8_t *)&gizwitsProtocol.TimeNTP, sizeof(protocolTime_t)); memset((uint8_t *)&gizwitsProtocol.NTPEvent,0x0,sizeof(gizwitsProtocol.NTPEvent)); break; case GET_MODULEINFO_TYPE: gizwitsProtocol.issuedFlag = STATELESS_TYPE; gizwitsEventProcess(&gizwitsProtocol.moduleInfoEvent, (uint8_t *)&gizwitsProtocol.wifiModuleNews, sizeof(moduleInfo_t)); memset((uint8_t *)&gizwitsProtocol.moduleInfoEvent,0x0,sizeof(moduleInfo_t)); break; default: break; } gizDevReportPolicy(currentData); return 0; } /** * @brief gizwits report transparent data interface * The user can call the interface to complete the reporting of private protocol data * @param [in] data :Private protocol data * @param [in] len :Private protocol data length * @return 0,success ;other,failure */ int32_t gizwitsPassthroughData(uint8_t * gizdata, uint32_t len) { int32_t ret = 0; uint8_t tx_buf[MAX_PACKAGE_LEN]; uint16_t data_len = 6 + len; // 修复作用域问题 if(NULL == gizdata || len > (MAX_PACKAGE_LEN - 10)) { GIZWITS_LOG("[ERR] Invalid params\n"); return -1; } // 协议头构建 tx_buf[0] = 0xFF; tx_buf[1] = 0xFF; tx_buf[2] = (uint8_t)(data_len >> 8); tx_buf[3] = (uint8_t)(data_len); tx_buf[4] = CMD_REPORT_P0; tx_buf[5] = gizwitsProtocol.sn++; tx_buf[6] = 0x00; // flag tx_buf[7] = 0x00; // flag tx_buf[8] = ACTION_D2W_TRANSPARENT_DATA; // 数据拷贝 memcpy(&tx_buf[9], gizdata, len); // 校验和计算 tx_buf[data_len + 4 - 1] = gizProtocolSum(tx_buf, data_len + 4 - 1); ret = uartWrite(tx_buf, data_len + 4); if(ret < 0) { GIZWITS_LOG("ERR: uart write error %d\n", ret); } gizProtocolWaitAck(tx_buf, data_len + 4); return (ret == (data_len + 4)) ? 0 : -2; } /**@} */ #include "sys.h" #include "usart.h" #include "gizwits_product.h" #if 1 #pragma import(__use_no_semihosting) //Ҫ׼ࠢѨҪք֧Ԗگ˽ struct __FILE { int handle; }; FILE __stdout; //֨ӥ_sys_exit()ӔҜĢʹԃѫ׷ܺģʽ void _sys_exit(int x) { x = x; } int fputc(int ch, FILE *f) { while((USART1->SR&0X40)==0); USART1->DR = (u8) ch; return ch; } #endif #if EN_USART1_RX //ɧڻʹŜ‹ޓ˕ //Ԯࠚ1א׏ؾϱԌѲ //עӢ,ׁȡUSARTx->SRŜҜĢĪĻǤĮքխϳ u8 USART_RX_BUF[USART_REC_LEN]; //ޓ˕ۺԥ,خճUSART_REC_LENٶؖޚ. //ޓ˕״̬ //bit15ì ޓ˕ΪԉҪ־ //bit14ì ޓ˕ս0x0d //bit13~0ì ޓ˕սքԐЧؖޚ˽Ŀ u16 USART_RX_STA=0; //ޓ˕״̬Ҫ݇ void uart1_init(u32 bound){ //GPIO׋ࠚʨ׃ GPIO_InitTypeDef GPIO_InitStructure; USART_InitTypeDef USART_InitStructure; NVIC_InitTypeDef NVIC_InitStructure; RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1|RCC_APB2Periph_GPIOA, ENABLE); //ʹŜUSART1ìGPIOAʱד //USART1_TX GPIOA.9 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; //PA.9 GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //شԃΆάˤԶ GPIO_Init(GPIOA, &GPIO_InitStructure);//ԵʼۯGPIOA.9 //USART1_RX GPIOA.10Եʼۯ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;//PA10 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;//ءࠕˤɫ GPIO_Init(GPIOA, &GPIO_InitStructure);//ԵʼۯGPIOA.10 //Usart1 NVIC Ƥ׃ NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=0 ;//ȀռԅЈܶ3 NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3; //ؓԅЈܶ3 NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQͨրʹŜ NVIC_Init(&NVIC_InitStructure); //ٹߝָ֨քӎ˽ԵʼۯVIC݄զǷ //USART Եʼۯʨ׃ USART_InitStructure.USART_BaudRate = bound;//ԮࠚҨ͘Ê USART_InitStructure.USART_WordLength = USART_WordLength_8b;//ؖӤΪ8λ˽ߝٱʽ USART_InitStructure.USART_StopBits = USART_StopBits_1;//һٶֹͣλ USART_InitStructure.USART_Parity = USART_Parity_No;//ϞǦżУҩλ USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//ϞӲݾ˽ߝ·࠘׆ USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; //˕עģʽ USART_Init(USART1, &USART_InitStructure); //ԵʼۯԮࠚ1 USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);//ߪǴԮࠚޓ˜א׏ USART_Cmd(USART1, ENABLE); //ʹŜԮࠚ1 } void uart2_init(u32 bound){ //GPIO׋ࠚʨ׃ GPIO_InitTypeDef GPIO_InitStructure; USART_InitTypeDef USART_InitStructure; NVIC_InitTypeDef NVIC_InitStructure; RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE); //ʹŜUSART2ìGPIOAʱד RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); //USART1_TX GPIOA.9 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2; //PA.9 GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //شԃΆάˤԶ GPIO_Init(GPIOA, &GPIO_InitStructure);//ԵʼۯGPIOA.9 //USART1_RX GPIOA.10Եʼۯ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3;//PA10 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;//ءࠕˤɫ GPIO_Init(GPIOA, &GPIO_InitStructure);//ԵʼۯGPIOA.10 //Usart1 NVIC Ƥ׃ NVIC_InitStructure.NVIC_IRQChannel = USART2_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=0 ;//ȀռԅЈܶ3 NVIC_InitStructure.NVIC_IRQChannelSubPriority = 2; //ؓԅЈܶ3 NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQͨրʹŜ NVIC_Init(&NVIC_InitStructure); //ٹߝָ֨քӎ˽ԵʼۯVIC݄զǷ //USART Եʼۯʨ׃ USART_InitStructure.USART_BaudRate = bound;//ԮࠚҨ͘Ê USART_InitStructure.USART_WordLength = USART_WordLength_8b;//ؖӤΪ8λ˽ߝٱʽ USART_InitStructure.USART_StopBits = USART_StopBits_1;//һٶֹͣλ USART_InitStructure.USART_Parity = USART_Parity_No;//ϞǦżУҩλ USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//ϞӲݾ˽ߝ·࠘׆ USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; //˕עģʽ USART_Init(USART2, &USART_InitStructure); //ԵʼۯԮࠚ1 USART_ITConfig(USART2, USART_IT_RXNE, ENABLE);//ߪǴԮࠚޓ˜א׏ USART_Cmd(USART2, ENABLE); //ʹŜԮࠚ1 // 添加串口错误中断使能 USART_ITConfig(USART2, USART_IT_ORE, ENABLE); // 过载错误 USART_ITConfig(USART2, USART_IT_NE, ENABLE); // 噪声错误 USART_ITConfig(USART2, USART_IT_FE, ENABLE); // 帧错误 } void USART1_IRQHandler(void) //Ԯࠚ1א׏ؾϱԌѲ { u8 Res; if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET) //ޓ˕א׏(ޓ˕սք˽ߝҘѫˇ0x0d 0x0aޡβ) { USART_ClearITPendingBit(USART1,USART_IT_RXNE); Res =USART_ReceiveData(USART1); //ׁȡޓ˕սք˽ߝ } } void USART2_IRQHandler(void) { u8 Res; uint32_t status = USART_GetITStatus(USART2, USART_IT_ORE | USART_IT_NE | USART_IT_FE | USART_IT_PE); // 处理所有可能的错误标志 if(status != RESET) { if(USART_GetITStatus(USART2, USART_IT_ORE) != RESET) { USART_ClearITPendingBit(USART2, USART_IT_ORE); USART_ReceiveData(USART2); // 必须读取DR寄存器清除ORE GIZWITS_LOG("USART2 ORE error\n"); } if(USART_GetITStatus(USART2, USART_IT_NE) != RESET) { USART_ClearITPendingBit(USART2, USART_IT_NE); GIZWITS_LOG("USART2 Noise error\n"); } if(USART_GetITStatus(USART2, USART_IT_FE) != RESET) { USART_ClearITPendingBit(USART2, USART_IT_FE); GIZWITS_LOG("USART2 Framing error\n"); } if(USART_GetITStatus(USART2, USART_IT_PE) != RESET) { USART_ClearITPendingBit(USART2, USART_IT_PE); GIZWITS_LOG("USART2 Parity error\n"); } } // 正常数据接收处理 if(USART_GetITStatus(USART2, USART_IT_RXNE) != RESET) { USART_ClearITPendingBit(USART2, USART_IT_RXNE); Res = USART_ReceiveData(USART2); if(gizPutData(&Res, 1) != 1) { GIZWITS_LOG("WARN: Failed to queue data: 0x%02X\n", Res); } } } #endif

UART1 and UART2 initialized. ERR: Failed to rbWrite ERR: Failed to rbWrite ERR: Failed to rbWrite ERR: Failed to rbWrite ERR: Failed to rbWrite ERR: Failed to rbWrite ERR: Failed to rbWrite ERR: Failed to rbWrite rbCreate Success DHT11 OK: T=30, H=53Warning:gizProtocolResendData 589 2 0Warning: timeout, resend data valueFan_OnOff ChangedvalueLED_OnOff Changedchanged, report dataDHT11 OK: T=30, H=53Warning:gizProtocolResendData 857 604 0Warning: timeout, resend data DHT11 OK: T=30, H=53Warning:gizProtocolResendData 1118 865 1Warning: timeout, resend data DHT11 OK: T=30, H=53DHT11 OK: T=30, H=53DHT11 OK: T=30, H=53DHT11 OK: T=30, H=53DHT11 OK: T=30, H=53DHT11 OK: T=30, H=53DHT11 OK: T=30, H=53DHT11 OK: T=30, H=53DHT11 OK: T=30, H=53DHT11 OK: T=30, H=53DHT11 OK: T=30, H=53DHT11 OK: T=30, H=53DHT11 OK: T=30, H=53DHT11 OK: T=30, H=53DHT11 OK: T=30, H=53DHT11 OK: T=30, H=53DHT11 OK: T=30, H=53DHT11 OK: T=30, H=53DHT11 OK: T=30, H=53DHT11 OK: T=30, H=53DHT11 OK: T=30, H=53DHT11 OK: T=30, H=53valuelight Changedchanged, report dataDHT11 OK: T=30, H=53Warning:gizProtocolResendData 6950 6697 0Warning: timeout, resend data DHT11 OK: T=30, H=53Warning:gizProtocolResendData 7211 6958 1Warning: timeout, resend data DHT11 OK: T=30, H=53DHT11 OK: T=30, H=53DHT11 OK: T=30, H=53DHT11 OK: T=30, H=53DHT11 OK: T=30, H=53DHT11 OK: T=30, H=53连不上网 #include "stm32f10x.h" // Device header #include "Delay.h" #include "OLED.h" #include "DHT11.h" #include "LED.h" #include "Light_Sensor.h" // 光敏电阻驱动(PA7) #include "Fan.h" #include "Buzzer.h" #include "TIM3.h" // TIM3定时器(1ms中断) #include "usart.h" // 串口通信(含机智云数据传输) #include "gizwits_product.h" // 机智云SDK #include "gizwits_protocol.h" // 阈值定义 #define TEMP_THRESHOLD 29 // 温度阈值(℃) #define LIGHT_THRESHOLD 128 // 光照阈值(0-255) extern uint8_t temp; extern uint8_t humi; extern dataPoint_t currentDataPoint; // 全局变量 uint8_t light_intensity; // 光照强度 void controlPeripherals(void) { // 温度控制风扇 if (temp > TEMP_THRESHOLD) { Control_Fan(1); // 风扇开启 currentDataPoint.valueFan_OnOff = 1; // 更新机智云风扇状态 OLED_ShowString(4, 1, "Fan: ON "); } else { Control_Fan(0); // 风扇关闭 currentDataPoint.valueFan_OnOff = 0; // 更新机智云风扇状态 OLED_ShowString(4, 1, "Fan: OFF"); } // 光照控制LED if (light_intensity < LIGHT_THRESHOLD) { Control_Light(1); // 光照不足,开灯 currentDataPoint.valueLED_OnOff = 1; } else { Control_Light(0); // 光照充足,关灯 currentDataPoint.valueLED_OnOff = 0; } // 超阈值报警(温度+湿度) if (temp > TEMP_THRESHOLD) { Buzzer_ON(); // 蜂鸣器报警 } else { Buzzer_OFF(); // 停止报警 } } // OLED显示更新 void updateOLED(void) { // 光照显示 OLED_ShowString(1, 1, "Light:"); OLED_ShowNum(1, 7, light_intensity, 3); OLED_ShowString(1, 10, "/255"); // 温度显示 OLED_ShowString(2, 1, "Temp:"); if(temp == 0xFF) { // 0xFF表示读取错误 OLED_ShowString(2, 6, "ERR"); } else { OLED_ShowNum(2, 6, temp, 2); OLED_ShowCC_F16x16(2, 8, 0); // 显示℃ } // 湿度显示 OLED_ShowString(3, 1, "Humi:"); OLED_ShowNum(3, 6, humi, 2); OLED_ShowCC_F16x16(3, 8, 1); // %显示 } int main(void) { // 初始化外设(按依赖顺序) NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); Delay_Init(); uart1_init(115200); // 初始化USART1,用于printf输出 uart2_init(115200); printf("UART1 and UART2 initialized.\r\n"); // 现在应该可以输出 OLED_Init(); // OLED显示屏 OLED_ShowString(1, 1, "System Start"); Delay_ms(1000); OLED_Clear(); LED_Init(); // LED初始化 LightSensor_Init(); // 光敏电阻初始化(PA7) ADC1_Init(); // ADC初始化(读取光敏电阻) DHT11_UserConfig(); // DHT11温湿度传感器初始化 Fan_Init(); // 风扇初始化 Buzzer_Init(); // 蜂鸣器初始化 GENERAL_TIM_Init(); // TIM3初始化(1ms中断,机智云定时) userInit(); // 机智云用户初始化 gizwitsInit(); gizwitsSetMode(WIFI_AIRLINK_MODE); // 机智云设备初始化 Delay_ms(500); OLED_Clear(); // 清屏准备正式显示 while (1) { light_intensity = Get_Light_Intensity(); // 1. 采集传感器数据 collectSensorData(); // 2. 更新机智云数据点(供云端读取) currentDataPoint.valuetemp = temp; // 温度数据 currentDataPoint.valuehumi = humi; // 湿度数据 currentDataPoint.valuelight = light_intensity;// 光照数据 // 3. 控制外设(风扇、LED、蜂鸣器) controlPeripherals(); // 4. 更新OLED显示 updateOLED(); // 5. 机智云任务处理(数据上报/指令接收) userHandle(); // 用户自定义处理 gizwitsHandle(¤tDataPoint); // 机智云核心处理 // 6. 延时,降低CPU占用 Delay_ms(200); } } #include "sys.h" #include "usart.h" #include "gizwits_product.h" #if 1 #pragma import(__use_no_semihosting) //Ҫ׼ࠢѨҪք֧Ԗگ˽ struct __FILE { int handle; }; FILE __stdout; //֨ӥ_sys_exit()ӔҜĢʹԃѫ׷ܺģʽ void _sys_exit(int x) { x = x; } int fputc(int ch, FILE *f) { while((USART1->SR&0X40)==0); USART1->DR = (u8) ch; return ch; } #endif #if EN_USART1_RX //ɧڻʹŜ‹ޓ˕ //Ԯࠚ1א׏ؾϱԌѲ //עӢ,ׁȡUSARTx->SRŜҜĢĪĻǤĮքխϳ u8 USART_RX_BUF[USART_REC_LEN]; //ޓ˕ۺԥ,خճUSART_REC_LENٶؖޚ. //ޓ˕״̬ //bit15ì ޓ˕ΪԉҪ־ //bit14ì ޓ˕ս0x0d //bit13~0ì ޓ˕սքԐЧؖޚ˽Ŀ u16 USART_RX_STA=0; //ޓ˕״̬Ҫ݇ void uart1_init(u32 bound){ //GPIO׋ࠚʨ׃ GPIO_InitTypeDef GPIO_InitStructure; USART_InitTypeDef USART_InitStructure; NVIC_InitTypeDef NVIC_InitStructure; RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1|RCC_APB2Periph_GPIOA, ENABLE); //ʹŜUSART1ìGPIOAʱד //USART1_TX GPIOA.9 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; //PA.9 GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //شԃΆάˤԶ GPIO_Init(GPIOA, &GPIO_InitStructure);//ԵʼۯGPIOA.9 //USART1_RX GPIOA.10Եʼۯ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;//PA10 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;//ءࠕˤɫ GPIO_Init(GPIOA, &GPIO_InitStructure);//ԵʼۯGPIOA.10 //Usart1 NVIC Ƥ׃ NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=0 ;//ȀռԅЈܶ3 NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3; //ؓԅЈܶ3 NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQͨրʹŜ NVIC_Init(&NVIC_InitStructure); //ٹߝָ֨քӎ˽ԵʼۯVIC݄զǷ //USART Եʼۯʨ׃ USART_InitStructure.USART_BaudRate = bound;//ԮࠚҨ͘Ê USART_InitStructure.USART_WordLength = USART_WordLength_8b;//ؖӤΪ8λ˽ߝٱʽ USART_InitStructure.USART_StopBits = USART_StopBits_1;//һٶֹͣλ USART_InitStructure.USART_Parity = USART_Parity_No;//ϞǦżУҩλ USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//ϞӲݾ˽ߝ·࠘׆ USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; //˕עģʽ USART_Init(USART1, &USART_InitStructure); //ԵʼۯԮࠚ1 USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);//ߪǴԮࠚޓ˜א׏ USART_Cmd(USART1, ENABLE); //ʹŜԮࠚ1 } void uart2_init(u32 bound){ //GPIO׋ࠚʨ׃ GPIO_InitTypeDef GPIO_InitStructure; USART_InitTypeDef USART_InitStructure; NVIC_InitTypeDef NVIC_InitStructure; RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE); //ʹŜUSART2ìGPIOAʱד RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); //USART1_TX GPIOA.9 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2; //PA.9 GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //شԃΆάˤԶ GPIO_Init(GPIOA, &GPIO_InitStructure);//ԵʼۯGPIOA.9 //USART1_RX GPIOA.10Եʼۯ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3;//PA10 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;//ءࠕˤɫ GPIO_Init(GPIOA, &GPIO_InitStructure);//ԵʼۯGPIOA.10 //Usart1 NVIC Ƥ׃ NVIC_InitStructure.NVIC_IRQChannel = USART2_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=0 ;//ȀռԅЈܶ3 NVIC_InitStructure.NVIC_IRQChannelSubPriority = 2; //ؓԅЈܶ3 NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQͨրʹŜ NVIC_Init(&NVIC_InitStructure); //ٹߝָ֨քӎ˽ԵʼۯVIC݄զǷ //USART Եʼۯʨ׃ USART_InitStructure.USART_BaudRate = bound;//ԮࠚҨ͘Ê USART_InitStructure.USART_WordLength = USART_WordLength_8b;//ؖӤΪ8λ˽ߝٱʽ USART_InitStructure.USART_StopBits = USART_StopBits_1;//һٶֹͣλ USART_InitStructure.USART_Parity = USART_Parity_No;//ϞǦżУҩλ USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//ϞӲݾ˽ߝ·࠘׆ USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; //˕עģʽ USART_Init(USART2, &USART_InitStructure); //ԵʼۯԮࠚ1 USART_ITConfig(USART2, USART_IT_RXNE, ENABLE);//ߪǴԮࠚޓ˜א׏ USART_Cmd(USART2, ENABLE); //ʹŜԮࠚ1 // 添加串口错误中断使能 USART_ITConfig(USART2, USART_IT_ORE, ENABLE); // 过载错误 USART_ITConfig(USART2, USART_IT_NE, ENABLE); // 噪声错误 USART_ITConfig(USART2, USART_IT_FE, ENABLE); // 帧错误 } void USART1_IRQHandler(void) //Ԯࠚ1א׏ؾϱԌѲ { u8 Res; if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET) //ޓ˕א׏(ޓ˕սք˽ߝҘѫˇ0x0d 0x0aޡβ) { USART_ClearITPendingBit(USART1,USART_IT_RXNE); Res =USART_ReceiveData(USART1); //ׁȡޓ˕սք˽ߝ } } void USART2_IRQHandler(void) //Ԯࠚ2א׏ؾϱԌѲ { u8 Res; if(USART_GetITStatus(USART2, USART_IT_ORE) != RESET) { USART_ClearITPendingBit(USART2, USART_IT_ORE); USART_ReceiveData(USART2); // 清除溢出 } if(USART_GetITStatus(USART2, USART_IT_NE) != RESET) { USART_ClearITPendingBit(USART2, USART_IT_NE); } if(USART_GetITStatus(USART2, USART_IT_FE) != RESET) { USART_ClearITPendingBit(USART2, USART_IT_FE); } if(USART_GetITStatus(USART2, USART_IT_RXNE) != RESET) //ޓ˕א׏(ޓ˕սք˽ߝҘѫˇ0x0d 0x0aޡβ) { USART_ClearITPendingBit(USART2,USART_IT_RXNE); Res =USART_ReceiveData(USART2); //ׁȡޓ˕սք˽ߝ gizPutData(&Res,1); } } #endif /** ************************************************************ * @file gizwits_protocol.c * @brief Corresponding gizwits_product.c header file (including product hardware and software version definition) * @author Gizwits * @date 2017-07-19 * @version V03030000 * @copyright Gizwits * * @note 机智云.只为智能硬件而生 * Gizwits Smart Cloud for Smart Products * 链接|增值ֵ|开放|中立|安全|自有|自由|生态 * www.gizwits.com * ***********************************************************/ #include "ringBuffer.h" #include "gizwits_product.h" #include "dataPointTools.h" /** Protocol global variables **/ gizwitsProtocol_t gizwitsProtocol; /**@name The serial port receives the ring buffer implementation * @{ */ rb_t pRb; ///< Ring buffer structure variable static uint8_t rbBuf[RB_MAX_LEN]; ///< Ring buffer data cache buffer /**@} */ /** * @brief Write data to the ring buffer * @param [in] buf : buf adress * @param [in] len : byte length * @return correct : Returns the length of the written data failure : -1 */ int32_t gizPutData(uint8_t *buf, uint32_t len) { int32_t count = 0; if(NULL == buf) { GIZWITS_LOG("ERR: gizPutData buf is empty \n"); return -1; } count = rbWrite(&pRb, buf, len); if(count != len) { GIZWITS_LOG("ERR: Failed to rbWrite \n"); return -1; } return count; } /** * @brief Protocol header initialization * * @param [out] head : Protocol header pointer * * @return 0, success; other, failure */ static int8_t gizProtocolHeadInit(protocolHead_t *head) { if(NULL == head) { GIZWITS_LOG("ERR: gizProtocolHeadInit head is empty \n"); return -1; } memset((uint8_t *)head, 0, sizeof(protocolHead_t)); head->head[0] = 0xFF; head->head[1] = 0xFF; return 0; } /** * @brief Protocol ACK check processing function * * @param [in] data : data adress * @param [in] len : data length * * @return 0, suceess; other, failure */ static int8_t gizProtocolWaitAck(uint8_t *gizdata, uint32_t len) { if(NULL == gizdata) { GIZWITS_LOG("ERR: data is empty \n"); return -1; } memset((uint8_t *)&gizwitsProtocol.waitAck, 0, sizeof(protocolWaitAck_t)); memcpy((uint8_t *)gizwitsProtocol.waitAck.buf, gizdata, len); gizwitsProtocol.waitAck.dataLen = (uint16_t)len; gizwitsProtocol.waitAck.flag = 1; gizwitsProtocol.waitAck.sendTime = gizGetTimerCount(); return 0; } /** * @brief generates "controlled events" according to protocol * @param [in] issuedData: Controlled data * @param [out] info: event queue * @param [out] dataPoints: data point data * @return 0, the implementation of success, non-0, failed */ static int8_t ICACHE_FLASH_ATTR gizDataPoint2Event(gizwitsIssued_t *issuedData, eventInfo_t *info, dataPoint_t *dataPoints) { if((NULL == issuedData) || (NULL == info) ||(NULL == dataPoints)) { GIZWITS_LOG("gizDataPoint2Event Error , Illegal Param\n"); return -1; } /** Greater than 1 byte to do bit conversion **/ if(sizeof(issuedData->attrFlags) > 1) { if(-1 == gizByteOrderExchange((uint8_t *)&issuedData->attrFlags,sizeof(attrFlags_t))) { GIZWITS_LOG("gizByteOrderExchange Error\n"); return -1; } } if(0x01 == issuedData->attrFlags.flagFan_OnOff) { info->event[info->num] = EVENT_Fan_OnOff; info->num++; dataPoints->valueFan_OnOff = gizStandardDecompressionValue(Fan_OnOff_BYTEOFFSET,Fan_OnOff_BITOFFSET,Fan_OnOff_LEN,(uint8_t *)&issuedData->attrVals.wBitBuf,sizeof(issuedData->attrVals.wBitBuf)); } if(0x01 == issuedData->attrFlags.flagLED_OnOff) { info->event[info->num] = EVENT_LED_OnOff; info->num++; dataPoints->valueLED_OnOff = gizStandardDecompressionValue(LED_OnOff_BYTEOFFSET,LED_OnOff_BITOFFSET,LED_OnOff_LEN,(uint8_t *)&issuedData->attrVals.wBitBuf,sizeof(issuedData->attrVals.wBitBuf)); } return 0; } /** * @brief contrasts the current data with the last data * * @param [in] cur: current data point data * @param [in] last: last data point data * * @return: 0, no change in data; 1, data changes */ static int8_t ICACHE_FLASH_ATTR gizCheckReport(dataPoint_t *cur, dataPoint_t *last) { int8_t ret = 0; static uint32_t lastReportTime = 0; uint32_t currentTime = 0; if((NULL == cur) || (NULL == last)) { GIZWITS_LOG("gizCheckReport Error , Illegal Param\n"); return -1; } currentTime = gizGetTimerCount(); if(last->valueFan_OnOff != cur->valueFan_OnOff) { GIZWITS_LOG("valueFan_OnOff Changed\n"); ret = 1; } if(last->valueLED_OnOff != cur->valueLED_OnOff) { GIZWITS_LOG("valueLED_OnOff Changed\n"); ret = 1; } if(last->valuetemp != cur->valuetemp) { if(currentTime - lastReportTime >= REPORT_TIME_MAX) { GIZWITS_LOG("valuetemp Changed\n"); ret = 1; } } if(last->valuehumi != cur->valuehumi) { if(currentTime - lastReportTime >= REPORT_TIME_MAX) { GIZWITS_LOG("valuehumi Changed\n"); ret = 1; } } if(last->valuelight != cur->valuelight) { if(currentTime - lastReportTime >= REPORT_TIME_MAX) { GIZWITS_LOG("valuelight Changed\n"); ret = 1; } } if(1 == ret) { lastReportTime = gizGetTimerCount(); } return ret; } /** * @brief User data point data is converted to wit the cloud to report data point data * * @param [in] dataPoints: user data point data address * @param [out] devStatusPtr: wit the cloud data point data address * * @return 0, the correct return; -1, the error returned */ static int8_t ICACHE_FLASH_ATTR gizDataPoints2ReportData(dataPoint_t *dataPoints , devStatus_t *devStatusPtr) { if((NULL == dataPoints) || (NULL == devStatusPtr)) { GIZWITS_LOG("gizDataPoints2ReportData Error , Illegal Param\n"); return -1; } gizMemset((uint8_t *)devStatusPtr->wBitBuf,0,sizeof(devStatusPtr->wBitBuf)); gizStandardCompressValue(Fan_OnOff_BYTEOFFSET,Fan_OnOff_BITOFFSET,Fan_OnOff_LEN,(uint8_t *)devStatusPtr,dataPoints->valueFan_OnOff); gizStandardCompressValue(LED_OnOff_BYTEOFFSET,LED_OnOff_BITOFFSET,LED_OnOff_LEN,(uint8_t *)devStatusPtr,dataPoints->valueLED_OnOff); gizByteOrderExchange((uint8_t *)devStatusPtr->wBitBuf,sizeof(devStatusPtr->wBitBuf)); devStatusPtr->valuetemp = gizY2X(temp_RATIO, temp_ADDITION, dataPoints->valuetemp); devStatusPtr->valuehumi = gizY2X(humi_RATIO, humi_ADDITION, dataPoints->valuehumi); devStatusPtr->valuelight = exchangeBytes(gizY2X(light_RATIO, light_ADDITION, dataPoints->valuelight)); return 0; } /** * @brief This function is called by the Gagent module to receive the relevant protocol data from the cloud or APP * @param [in] inData The protocol data entered * @param [in] inLen Enter the length of the data * @param [out] outData The output of the protocol data * @param [out] outLen The length of the output data * @return 0, the implementation of success, non-0, failed */ static int8_t gizProtocolIssuedProcess(char *did, uint8_t *inData, uint32_t inLen, uint8_t *outData, uint32_t *outLen) { uint8_t issuedAction = inData[0]; if((NULL == inData)||(NULL == outData)||(NULL == outLen)) { GIZWITS_LOG("gizProtocolIssuedProcess Error , Illegal Param\n"); return -1; } if(NULL == did) { memset((uint8_t *)&gizwitsProtocol.issuedProcessEvent, 0, sizeof(eventInfo_t)); switch(issuedAction) { case ACTION_CONTROL_DEVICE: gizDataPoint2Event((gizwitsIssued_t *)&inData[1], &gizwitsProtocol.issuedProcessEvent,&gizwitsProtocol.gizCurrentDataPoint); gizwitsProtocol.issuedFlag = ACTION_CONTROL_TYPE; outData = NULL; *outLen = 0; break; case ACTION_READ_DEV_STATUS: if(0 == gizDataPoints2ReportData(&gizwitsProtocol.gizLastDataPoint,&gizwitsProtocol.reportData.devStatus)) { memcpy(outData+1, (uint8_t *)&gizwitsProtocol.reportData.devStatus, sizeof(gizwitsReport_t)); outData[0] = ACTION_READ_DEV_STATUS_ACK; *outLen = sizeof(gizwitsReport_t)+1; } else { return -1; } break; case ACTION_W2D_TRANSPARENT_DATA: memcpy(gizwitsProtocol.transparentBuff, &inData[1], inLen-1); gizwitsProtocol.transparentLen = inLen - 1; gizwitsProtocol.issuedProcessEvent.event[gizwitsProtocol.issuedProcessEvent.num] = TRANSPARENT_DATA; gizwitsProtocol.issuedProcessEvent.num++; gizwitsProtocol.issuedFlag = ACTION_W2D_TRANSPARENT_TYPE; outData = NULL; *outLen = 0; break; default: break; } } return 0; } /** * @brief The protocol sends data back , P0 ACK * * @param [in] head : Protocol head pointer * @param [in] data : Payload data * @param [in] len : Payload data length * @param [in] proFlag : DID flag ,1 for Virtual sub device did ,0 for single product or gateway * * @return : 0,Ack success; * -1,Input Param Illegal * -2,Serial send faild */ static int32_t gizProtocolIssuedDataAck(protocolHead_t *head, uint8_t *gizdata, uint32_t len, uint8_t proFlag) { int32_t ret = 0; uint8_t tx_buf[RB_MAX_LEN]; uint32_t offset = 0; uint8_t sDidLen = 0; uint16_t data_len = 0; uint8_t *pTxBuf = tx_buf; if(NULL == gizdata) { GIZWITS_LOG("[ERR] data Is Null \n"); return -1; } if(0x1 == proFlag) { sDidLen = *((uint8_t *)head + sizeof(protocolHead_t)); data_len = 5 + 1 + sDidLen + len; } else { data_len = 5 + len; } GIZWITS_LOG("len = %d , sDidLen = %d ,data_len = %d\n", len,sDidLen,data_len); *pTxBuf ++= 0xFF; *pTxBuf ++= 0xFF; *pTxBuf ++= (uint8_t)(data_len>>8); *pTxBuf ++= (uint8_t)(data_len); *pTxBuf ++= head->cmd + 1; *pTxBuf ++= head->sn; *pTxBuf ++= 0x00; *pTxBuf ++= proFlag; offset = 8; if(0x1 == proFlag) { *pTxBuf ++= sDidLen; offset += 1; memcpy(&tx_buf[offset],(uint8_t *)head+sizeof(protocolHead_t)+1,sDidLen); offset += sDidLen; pTxBuf += sDidLen; } if(0 != len) { memcpy(&tx_buf[offset],gizdata,len); } tx_buf[data_len + 4 - 1 ] = gizProtocolSum( tx_buf , (data_len+4)); ret = uartWrite(tx_buf, data_len+4); if(ret < 0) { GIZWITS_LOG("uart write error %d \n", ret); return -2; } return 0; } /** * @brief Report data interface * * @param [in] action : PO action * @param [in] data : Payload data * @param [in] len : Payload data length * * @return : 0,Ack success; * -1,Input Param Illegal * -2,Serial send faild */ static int32_t gizReportData(uint8_t action, uint8_t *gizdata, uint32_t len) { int32_t ret = 0; protocolReport_t protocolReport; if(NULL == gizdata) { GIZWITS_LOG("gizReportData Error , Illegal Param\n"); return -1; } gizProtocolHeadInit((protocolHead_t *)&protocolReport); protocolReport.head.cmd = CMD_REPORT_P0; protocolReport.head.sn = gizwitsProtocol.sn++; protocolReport.action = action; protocolReport.head.len = exchangeBytes(sizeof(protocolReport_t)-4); memcpy((gizwitsReport_t *)&protocolReport.reportData, (gizwitsReport_t *)gizdata,len); protocolReport.sum = gizProtocolSum((uint8_t *)&protocolReport, sizeof(protocolReport_t)); ret = uartWrite((uint8_t *)&protocolReport, sizeof(protocolReport_t)); if(ret < 0) { GIZWITS_LOG("ERR: uart write error %d \n", ret); return -2; } gizProtocolWaitAck((uint8_t *)&protocolReport, sizeof(protocolReport_t)); return ret; }/** * @brief Datapoints reporting mechanism * * 1. Changes are reported immediately * 2. Data timing report , 600000 Millisecond * *@param [in] currentData : Current datapoints value * @return : NULL */ static void gizDevReportPolicy(dataPoint_t *currentData) { static uint32_t lastRepTime = 0; uint32_t timeNow = gizGetTimerCount(); if((1 == gizCheckReport(currentData, (dataPoint_t *)&gizwitsProtocol.gizLastDataPoint))) { GIZWITS_LOG("changed, report data\n"); if(0 == gizDataPoints2ReportData(currentData,&gizwitsProtocol.reportData.devStatus)) { gizReportData(ACTION_REPORT_DEV_STATUS, (uint8_t *)&gizwitsProtocol.reportData.devStatus, sizeof(devStatus_t)); } memcpy((uint8_t *)&gizwitsProtocol.gizLastDataPoint, (uint8_t *)currentData, sizeof(dataPoint_t)); } if((0 == (timeNow % (600000))) && (lastRepTime != timeNow)) { GIZWITS_LOG("Info: 600S report data\n"); if(0 == gizDataPoints2ReportData(currentData,&gizwitsProtocol.reportData.devStatus)) { gizReportData(ACTION_REPORT_DEV_STATUS, (uint8_t *)&gizwitsProtocol.reportData.devStatus, sizeof(devStatus_t)); } memcpy((uint8_t *)&gizwitsProtocol.gizLastDataPoint, (uint8_t *)currentData, sizeof(dataPoint_t)); lastRepTime = timeNow; } } /** * @brief Get a packet of data from the ring buffer * * @param [in] rb : Input data address * @param [out] data : Output data address * @param [out] len : Output data length * * @return : 0,Return correct ;-1,Return failure;-2,Data check failure */ static int8_t gizProtocolGetOnePacket(rb_t *rb, uint8_t *gizdata, uint16_t *len) { int32_t ret = 0; uint8_t sum = 0; int32_t i = 0; uint8_t tmpData; uint16_t tmpLen = 0; uint16_t tmpCount = 0; static uint8_t protocolFlag = 0; static uint16_t protocolCount = 0; static uint8_t lastData = 0; static uint8_t debugCount = 0; uint8_t *protocolBuff = gizdata; protocolHead_t *head = NULL; if((NULL == rb) || (NULL == gizdata) ||(NULL == len)) { GIZWITS_LOG("gizProtocolGetOnePacket Error , Illegal Param\n"); return -1; } tmpLen = rbCanRead(rb); if(0 == tmpLen) { return -1; } for(i=0; i<tmpLen; i++) { ret = rbRead(rb, &tmpData, 1); if(0 != ret) { if((0xFF == lastData) && (0xFF == tmpData)) { if(0 == protocolFlag) { protocolBuff[0] = 0xFF; protocolBuff[1] = 0xFF; protocolCount = 2; protocolFlag = 1; } else { if((protocolCount > 4) && (protocolCount != tmpCount)) { protocolBuff[0] = 0xFF; protocolBuff[1] = 0xFF; protocolCount = 2; } } } else if((0xFF == lastData) && (0x55 == tmpData)) { } else { if(1 == protocolFlag) { protocolBuff[protocolCount] = tmpData; protocolCount++; if(protocolCount > 4) { head = (protocolHead_t *)protocolBuff; tmpCount = exchangeBytes(head->len)+4; if (tmpCount >= MAX_PACKAGE_LEN || tmpCount <= 4) { protocolFlag = 0; protocolCount = 0; GIZWITS_LOG("ERR:the data length is too long or too small, will abandon \n"); } if(protocolCount == tmpCount) { break; } } } } lastData = tmpData; debugCount++; } } if((protocolCount > 4) && (protocolCount == tmpCount)) { sum = gizProtocolSum(protocolBuff, protocolCount); if(protocolBuff[protocolCount-1] == sum) { *len = tmpCount; protocolFlag = 0; protocolCount = 0; debugCount = 0; lastData = 0; return 0; } else { protocolFlag = 0; protocolCount = 0; return -2; } } return 1; } /** * @brief Protocol data resend * The protocol data resend when check timeout and meet the resend limiting * @param none * * @return none */ static void gizProtocolResendData(void) { int32_t ret = 0; if(0 == gizwitsProtocol.waitAck.flag) { return; } GIZWITS_LOG("Warning: timeout, resend data \n"); ret = uartWrite(gizwitsProtocol.waitAck.buf, gizwitsProtocol.waitAck.dataLen); if(ret != gizwitsProtocol.waitAck.dataLen) { GIZWITS_LOG("ERR: resend data error\n"); } gizwitsProtocol.waitAck.sendTime = gizGetTimerCount(); } /** * @brief Clear the ACK protocol message * * @param [in] head : Protocol header address * * @return 0, success; other, failure */ static int8_t gizProtocolWaitAckCheck(protocolHead_t *head) { protocolHead_t *waitAckHead = (protocolHead_t *)gizwitsProtocol.waitAck.buf; if(NULL == head) { GIZWITS_LOG("ERR: data is empty \n"); return -1; } if(waitAckHead->cmd+1 == head->cmd) { memset((uint8_t *)&gizwitsProtocol.waitAck, 0, sizeof(protocolWaitAck_t)); } return 0; } /** * @brief Send general protocol message data * * @param [in] head : Protocol header address * * @return : Return effective data length;-1,return failure */ static int32_t gizProtocolCommonAck(protocolHead_t *head) { int32_t ret = 0; protocolCommon_t ack; if(NULL == head) { GIZWITS_LOG("ERR: gizProtocolCommonAck data is empty \n"); return -1; } memcpy((uint8_t *)&ack, (uint8_t *)head, sizeof(protocolHead_t)); ack.head.cmd = ack.head.cmd+1; ack.head.len = exchangeBytes(sizeof(protocolCommon_t)-4); ack.sum = gizProtocolSum((uint8_t *)&ack, sizeof(protocolCommon_t)); ret = uartWrite((uint8_t *)&ack, sizeof(protocolCommon_t)); if(ret < 0) { GIZWITS_LOG("ERR: uart write error %d \n", ret); } return ret; } /** * @brief ACK processing function * Time-out 200ms no ACK resend,resend two times at most * @param none * * @return none */ static void gizProtocolAckHandle(void) { if(1 == gizwitsProtocol.waitAck.flag) { if(SEND_MAX_NUM > gizwitsProtocol.waitAck.num) { // Time-out no ACK resend if(SEND_MAX_TIME < (gizGetTimerCount() - gizwitsProtocol.waitAck.sendTime)) { GIZWITS_LOG("Warning:gizProtocolResendData %d %d %d\n", gizGetTimerCount(), gizwitsProtocol.waitAck.sendTime, gizwitsProtocol.waitAck.num); gizProtocolResendData(); gizwitsProtocol.waitAck.num++; } } else { memset((uint8_t *)&gizwitsProtocol.waitAck, 0, sizeof(protocolWaitAck_t)); } } } /** * @brief Protocol 4.1 WiFi module requests device information * * @param[in] head : Protocol header address * * @return Return effective data length;-1,return failure */ static int32_t gizProtocolGetDeviceInfo(protocolHead_t * head) { int32_t ret = 0; protocolDeviceInfo_t deviceInfo; if(NULL == head) { GIZWITS_LOG("gizProtocolGetDeviceInfo Error , Illegal Param\n"); return -1; } gizProtocolHeadInit((protocolHead_t *)&deviceInfo); deviceInfo.head.cmd = ACK_GET_DEVICE_INFO; deviceInfo.head.sn = head->sn; memcpy((uint8_t *)deviceInfo.protocolVer, protocol_VERSION, 8); memcpy((uint8_t *)deviceInfo.p0Ver, P0_VERSION, 8); memcpy((uint8_t *)deviceInfo.softVer, SOFTWARE_VERSION, 8); memcpy((uint8_t *)deviceInfo.hardVer, HARDWARE_VERSION, 8); memcpy((uint8_t *)deviceInfo.productKey, PRODUCT_KEY, strlen(PRODUCT_KEY)); memcpy((uint8_t *)deviceInfo.productSecret, PRODUCT_SECRET, strlen(PRODUCT_SECRET)); memset((uint8_t *)deviceInfo.devAttr, 0, 8); deviceInfo.devAttr[7] |= DEV_IS_GATEWAY<<0; deviceInfo.devAttr[7] |= (0x01<<1); deviceInfo.ninableTime = exchangeBytes(NINABLETIME); #ifdef DATA_CONFIG_ENABLE deviceInfo.DataLen = exchangeBytes(GIZ_DATA_LEN); sprintf(deviceInfo.Data,"apName=%s&apPwd=%s&cfgMode=%s",AP_NAME,AP_PWD,CFG_MODE); #endif deviceInfo.head.len = exchangeBytes(sizeof(protocolDeviceInfo_t)-4); deviceInfo.sum = gizProtocolSum((uint8_t *)&deviceInfo, sizeof(protocolDeviceInfo_t)); ret = uartWrite((uint8_t *)&deviceInfo, sizeof(protocolDeviceInfo_t)); if(ret < 0) { GIZWITS_LOG("ERR: uart write error %d \n", ret); } return ret; } /** * @brief Protocol 4.7 Handling of illegal message notification * @param[in] head : Protocol header address * @param[in] errno : Illegal message notification type * @return 0, success; other, failure */ static int32_t gizProtocolErrorCmd(protocolHead_t *head,errorPacketsType_t errno) { int32_t ret = 0; protocolErrorType_t errorType; if(NULL == head) { GIZWITS_LOG("gizProtocolErrorCmd Error , Illegal Param\n"); return -1; } gizProtocolHeadInit((protocolHead_t *)&errorType); errorType.head.cmd = ACK_ERROR_PACKAGE; errorType.head.sn = head->sn; errorType.head.len = exchangeBytes(sizeof(protocolErrorType_t)-4); errorType.error = errno; errorType.sum = gizProtocolSum((uint8_t *)&errorType, sizeof(protocolErrorType_t)); ret = uartWrite((uint8_t *)&errorType, sizeof(protocolErrorType_t)); if(ret < 0) { GIZWITS_LOG("ERR: uart write error %d \n", ret); } return ret; } /** * @brief Protocol 4.13 Get and process network time * * @param [in] head : Protocol header address * * @return 0, success; other, failure */ static int8_t gizProtocolNTP(protocolHead_t *head) { protocolUTT_t *UTTInfo = (protocolUTT_t *)head; if(NULL == head) { GIZWITS_LOG("ERR: NTP is empty \n"); return -1; } memcpy((uint8_t *)&gizwitsProtocol.TimeNTP.year,(uint8_t *)UTTInfo->time, 7); memcpy((uint8_t *)&gizwitsProtocol.TimeNTP.ntp,(uint8_t *)UTTInfo->ntp_time, 4); gizwitsProtocol.TimeNTP.year = exchangeBytes(gizwitsProtocol.TimeNTP.year); gizwitsProtocol.TimeNTP.ntp =exchangeWord(gizwitsProtocol.TimeNTP.ntp); gizwitsProtocol.NTPEvent.event[gizwitsProtocol.NTPEvent.num] = WIFI_NTP; gizwitsProtocol.NTPEvent.num++; gizwitsProtocol.issuedFlag = GET_NTP_TYPE; return 0; } /** * @brief Protocol 4.4 Device MCU restarts function * @param none * @return none */ static void gizProtocolReboot(void) { uint32_t timeDelay = gizGetTimerCount(); /*Wait 600ms*/ while((gizGetTimerCount() - timeDelay) <= 600); mcuRestart(); } /** * @brief Protocol 4.5 :The WiFi module informs the device MCU of working status about the WiFi module * @param[in] status WiFi module working status * @return none */ static int8_t gizProtocolModuleStatus(protocolWifiStatus_t *status) { static wifiStatus_t lastStatus; if(NULL == status) { GIZWITS_LOG("gizProtocolModuleStatus Error , Illegal Param\n"); return -1; } status->ststus.value = exchangeBytes(status->ststus.value); //OnBoarding mode status if(lastStatus.types.onboarding != status->ststus.types.onboarding) { if(1 == status->ststus.types.onboarding) { if(1 == status->ststus.types.softap) { gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_SOFTAP; gizwitsProtocol.wifiStatusEvent.num++; GIZWITS_LOG("OnBoarding: SoftAP or Web mode\n"); } if(1 == status->ststus.types.station) { gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_AIRLINK; gizwitsProtocol.wifiStatusEvent.num++; GIZWITS_LOG("OnBoarding: AirLink mode\n"); } } else { if(1 == status->ststus.types.softap) { gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_SOFTAP; gizwitsProtocol.wifiStatusEvent.num++; GIZWITS_LOG("OnBoarding: SoftAP or Web mode\n"); } if(1 == status->ststus.types.station) { gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_STATION; gizwitsProtocol.wifiStatusEvent.num++; GIZWITS_LOG("OnBoarding: Station mode\n"); } } } //binding mode status if(lastStatus.types.binding != status->ststus.types.binding) { lastStatus.types.binding = status->ststus.types.binding; if(1 == status->ststus.types.binding) { gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_OPEN_BINDING; gizwitsProtocol.wifiStatusEvent.num++; GIZWITS_LOG("WiFi status: in binding mode\n"); } else { gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_CLOSE_BINDING; gizwitsProtocol.wifiStatusEvent.num++; GIZWITS_LOG("WiFi status: out binding mode\n"); } } //router status if(lastStatus.types.con_route != status->ststus.types.con_route) { lastStatus.types.con_route = status->ststus.types.con_route; if(1 == status->ststus.types.con_route) { gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_CON_ROUTER; gizwitsProtocol.wifiStatusEvent.num++; GIZWITS_LOG("WiFi status: connected router\n"); } else { gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_DISCON_ROUTER; gizwitsProtocol.wifiStatusEvent.num++; GIZWITS_LOG("WiFi status: disconnected router\n"); } } //M2M server status if(lastStatus.types.con_m2m != status->ststus.types.con_m2m) { lastStatus.types.con_m2m = status->ststus.types.con_m2m; if(1 == status->ststus.types.con_m2m) { gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_CON_M2M; gizwitsProtocol.wifiStatusEvent.num++; GIZWITS_LOG("WiFi status: connected m2m\n"); } else { gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_DISCON_M2M; gizwitsProtocol.wifiStatusEvent.num++; GIZWITS_LOG("WiFi status: disconnected m2m\n"); } } //APP status if(lastStatus.types.app != status->ststus.types.app) { lastStatus.types.app = status->ststus.types.app; if(1 == status->ststus.types.app) { gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_CON_APP; gizwitsProtocol.wifiStatusEvent.num++; GIZWITS_LOG("WiFi status: app connect\n"); } else { gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_DISCON_APP; gizwitsProtocol.wifiStatusEvent.num++; GIZWITS_LOG("WiFi status: no app connect\n"); } } //test mode status if(lastStatus.types.test != status->ststus.types.test) { lastStatus.types.test = status->ststus.types.test; if(1 == status->ststus.types.test) { gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_OPEN_TESTMODE; gizwitsProtocol.wifiStatusEvent.num++; GIZWITS_LOG("WiFi status: in test mode\n"); } else { gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_CLOSE_TESTMODE; gizwitsProtocol.wifiStatusEvent.num++; GIZWITS_LOG("WiFi status: out test mode\n"); } } gizwitsProtocol.wifiStatusEvent.event[gizwitsProtocol.wifiStatusEvent.num] = WIFI_RSSI; gizwitsProtocol.wifiStatusEvent.num++; gizwitsProtocol.wifiStatusData.rssi = status->ststus.types.rssi; GIZWITS_LOG("RSSI is %d \n", gizwitsProtocol.wifiStatusData.rssi); gizwitsProtocol.issuedFlag = WIFI_STATUS_TYPE; return 0; } /**@name Gizwits User API interface * @{ */ /** * @brief gizwits Protocol initialization interface * Protocol-related timer, serial port initialization * Datapoint initialization * @param none * @return none */ void gizwitsInit(void) { pRb.rbCapacity = RB_MAX_LEN; pRb.rbBuff = rbBuf; if(0 == rbCreate(&pRb)) { GIZWITS_LOG("rbCreate Success \n"); } else { GIZWITS_LOG("rbCreate Faild \n"); } memset((uint8_t *)&gizwitsProtocol, 0, sizeof(gizwitsProtocol_t)); } /** * @brief WiFi configure interface * Set the WiFi module into the corresponding configuration mode or reset the module * @param[in] mode :0x0, reset the module ;0x01, SoftAp mode ;0x02, AirLink mode ;0x03, Production test mode; 0x04:allow users to bind devices * @return Error command code */ int32_t gizwitsSetMode(uint8_t mode) { int32_t ret = 0; protocolCfgMode_t cfgMode; protocolCommon_t setDefault; switch(mode) { case WIFI_RESET_MODE: gizProtocolHeadInit((protocolHead_t *)&setDefault); setDefault.head.cmd = CMD_SET_DEFAULT; setDefault.head.sn = gizwitsProtocol.sn++; setDefault.head.len = exchangeBytes(sizeof(protocolCommon_t)-4); setDefault.sum = gizProtocolSum((uint8_t *)&setDefault, sizeof(protocolCommon_t)); ret = uartWrite((uint8_t *)&setDefault, sizeof(protocolCommon_t)); if(ret < 0) { GIZWITS_LOG("ERR: uart write error %d \n", ret); } gizProtocolWaitAck((uint8_t *)&setDefault, sizeof(protocolCommon_t)); break; case WIFI_SOFTAP_MODE: gizProtocolHeadInit((protocolHead_t *)&cfgMode); cfgMode.head.cmd = CMD_WIFI_CONFIG; cfgMode.head.sn = gizwitsProtocol.sn++; cfgMode.cfgMode = mode; cfgMode.head.len = exchangeBytes(sizeof(protocolCfgMode_t)-4); cfgMode.sum = gizProtocolSum((uint8_t *)&cfgMode, sizeof(protocolCfgMode_t)); ret = uartWrite((uint8_t *)&cfgMode, sizeof(protocolCfgMode_t)); if(ret < 0) { GIZWITS_LOG("ERR: uart write error %d \n", ret); } gizProtocolWaitAck((uint8_t *)&cfgMode, sizeof(protocolCfgMode_t)); break; case WIFI_AIRLINK_MODE: gizProtocolHeadInit((protocolHead_t *)&cfgMode); cfgMode.head.cmd = CMD_WIFI_CONFIG; cfgMode.head.sn = gizwitsProtocol.sn++; cfgMode.cfgMode = mode; cfgMode.head.len = exchangeBytes(sizeof(protocolCfgMode_t)-4); cfgMode.sum = gizProtocolSum((uint8_t *)&cfgMode, sizeof(protocolCfgMode_t)); ret = uartWrite((uint8_t *)&cfgMode, sizeof(protocolCfgMode_t)); if(ret < 0) { GIZWITS_LOG("ERR: uart write error %d \n", ret); } gizProtocolWaitAck((uint8_t *)&cfgMode, sizeof(protocolCfgMode_t)); break; case WIFI_PRODUCTION_TEST: gizProtocolHeadInit((protocolHead_t *)&setDefault); setDefault.head.cmd = CMD_PRODUCTION_TEST; setDefault.head.sn = gizwitsProtocol.sn++; setDefault.head.len = exchangeBytes(sizeof(protocolCommon_t)-4); setDefault.sum = gizProtocolSum((uint8_t *)&setDefault, sizeof(protocolCommon_t)); ret = uartWrite((uint8_t *)&setDefault, sizeof(protocolCommon_t)); if(ret < 0) { GIZWITS_LOG("ERR: uart write error %d \n", ret); } gizProtocolWaitAck((uint8_t *)&setDefault, sizeof(protocolCommon_t)); break; case WIFI_NINABLE_MODE: gizProtocolHeadInit((protocolHead_t *)&setDefault); setDefault.head.cmd = CMD_NINABLE_MODE; setDefault.head.sn = gizwitsProtocol.sn++; setDefault.head.len = exchangeBytes(sizeof(protocolCommon_t)-4); setDefault.sum = gizProtocolSum((uint8_t *)&setDefault, sizeof(protocolCommon_t)); ret = uartWrite((uint8_t *)&setDefault, sizeof(protocolCommon_t)); if(ret < 0) { GIZWITS_LOG("ERR: uart write error %d \n", ret); } gizProtocolWaitAck((uint8_t *)&setDefault, sizeof(protocolCommon_t)); break; case WIFI_REBOOT_MODE: gizProtocolHeadInit((protocolHead_t *)&setDefault); setDefault.head.cmd = CMD_REBOOT_MODULE; setDefault.head.sn = gizwitsProtocol.sn++; setDefault.head.len = exchangeBytes(sizeof(protocolCommon_t)-4); setDefault.sum = gizProtocolSum((uint8_t *)&setDefault, sizeof(protocolCommon_t)); ret = uartWrite((uint8_t *)&setDefault, sizeof(protocolCommon_t)); if(ret < 0) { GIZWITS_LOG("ERR: uart write error %d \n", ret); } gizProtocolWaitAck((uint8_t *)&setDefault, sizeof(protocolCommon_t)); break; default: GIZWITS_LOG("ERR: CfgMode error!\n"); break; } return ret; } /** * @brief Get the the network time * Protocol 4.13:"Device MCU send" of "the MCU requests access to the network time" * @param[in] none * @return none */ void gizwitsGetNTP(void) { int32_t ret = 0; protocolCommon_t getNTP; gizProtocolHeadInit((protocolHead_t *)&getNTP); getNTP.head.cmd = CMD_GET_NTP; getNTP.head.sn = gizwitsProtocol.sn++; getNTP.head.len = exchangeBytes(sizeof(protocolCommon_t)-4); getNTP.sum = gizProtocolSum((uint8_t *)&getNTP, sizeof(protocolCommon_t)); ret = uartWrite((uint8_t *)&getNTP, sizeof(protocolCommon_t)); if(ret < 0) { GIZWITS_LOG("ERR[NTP]: uart write error %d \n", ret); } gizProtocolWaitAck((uint8_t *)&getNTP, sizeof(protocolCommon_t)); } /** * @brief Get Module Info * * @param[in] none * @return none */ void gizwitsGetModuleInfo(void) { int32_t ret = 0; protocolGetModuleInfo_t getModuleInfo; gizProtocolHeadInit((protocolHead_t *)&getModuleInfo); getModuleInfo.head.cmd = CMD_ASK_MODULE_INFO; getModuleInfo.head.sn = gizwitsProtocol.sn++; getModuleInfo.type = 0x0; getModuleInfo.head.len = exchangeBytes(sizeof(protocolGetModuleInfo_t)-4); getModuleInfo.sum = gizProtocolSum((uint8_t *)&getModuleInfo, sizeof(protocolGetModuleInfo_t)); ret = uartWrite((uint8_t *)&getModuleInfo, sizeof(protocolGetModuleInfo_t)); if(ret < 0) { GIZWITS_LOG("ERR[NTP]: uart write error %d \n", ret); } gizProtocolWaitAck((uint8_t *)&getModuleInfo, sizeof(protocolGetModuleInfo_t)); } /** * @brief Module Info Analyse * * @param [in] head : * * @return 0, Success, , other,Faild */ static int8_t gizProtocolModuleInfoHandle(protocolHead_t *head) { protocolModuleInfo_t *moduleInfo = (protocolModuleInfo_t *)head; if(NULL == head) { GIZWITS_LOG("NTP is empty \n"); return -1; } #if MODULE_TYPE memcpy((uint8_t *)&gizwitsProtocol.gprsInfoNews,(uint8_t *)&moduleInfo->gprsModuleInfo, sizeof(gprsInfo_t)); #else memcpy((uint8_t *)&gizwitsProtocol.wifiModuleNews,(uint8_t *)&moduleInfo->wifiModuleInfo, sizeof(moduleInfo_t)); #endif gizwitsProtocol.moduleInfoEvent.event[gizwitsProtocol.moduleInfoEvent.num] = MODULE_INFO; gizwitsProtocol.moduleInfoEvent.num++; gizwitsProtocol.issuedFlag = GET_MODULEINFO_TYPE; return 0; } /** * @brief Protocol handling function * * @param [in] currentData :The protocol data pointer * @return none */ int32_t gizwitsHandle(dataPoint_t *currentData) { int8_t ret = 0; #ifdef PROTOCOL_DEBUG uint16_t i = 0; #endif uint8_t ackData[RB_MAX_LEN]; uint16_t protocolLen = 0; uint32_t ackLen = 0; protocolHead_t *recvHead = NULL; char *didPtr = NULL; uint16_t offset = 0; if(NULL == currentData) { GIZWITS_LOG("GizwitsHandle Error , Illegal Param\n"); return -1; } /*resend strategy*/ gizProtocolAckHandle(); ret = gizProtocolGetOnePacket(&pRb, gizwitsProtocol.protocolBuf, &protocolLen); if(0 == ret) { GIZWITS_LOG("Get One Packet!\n"); #ifdef PROTOCOL_DEBUG GIZWITS_LOG("WiFi2MCU[%4d:%4d]: ", gizGetTimerCount(), protocolLen); for(i=0; icmd) { case CMD_GET_DEVICE_INTO: gizProtocolGetDeviceInfo(recvHead); break; case CMD_ISSUED_P0: GIZWITS_LOG("flag %x %x \n", recvHead->flags[0], recvHead->flags[1]); //offset = 1; if(0 == gizProtocolIssuedProcess(didPtr, gizwitsProtocol.protocolBuf+sizeof(protocolHead_t)+offset, protocolLen-(sizeof(protocolHead_t)+offset+1), ackData, &ackLen)) { gizProtocolIssuedDataAck(recvHead, ackData, ackLen,recvHead->flags[1]); GIZWITS_LOG("AckData : \n"); } break; case CMD_HEARTBEAT: gizProtocolCommonAck(recvHead); break; case CMD_WIFISTATUS: gizProtocolCommonAck(recvHead); gizProtocolModuleStatus((protocolWifiStatus_t *)recvHead); break; case ACK_REPORT_P0: case ACK_WIFI_CONFIG: case ACK_SET_DEFAULT: case ACK_NINABLE_MODE: case ACK_REBOOT_MODULE: gizProtocolWaitAckCheck(recvHead); break; case CMD_MCU_REBOOT: gizProtocolCommonAck(recvHead); GIZWITS_LOG("report:MCU reboot!\n"); gizProtocolReboot(); break; case CMD_ERROR_PACKAGE: break; case ACK_PRODUCTION_TEST: gizProtocolWaitAckCheck(recvHead); GIZWITS_LOG("Ack PRODUCTION_MODE success \n"); break; case ACK_GET_NTP: gizProtocolWaitAckCheck(recvHead); gizProtocolNTP(recvHead); GIZWITS_LOG("Ack GET_UTT success \n"); break; case ACK_ASK_MODULE_INFO: gizProtocolWaitAckCheck(recvHead); gizProtocolModuleInfoHandle(recvHead); GIZWITS_LOG("Ack GET_Module success \n"); break; default: gizProtocolErrorCmd(recvHead,ERROR_CMD); GIZWITS_LOG("ERR: cmd code error!\n"); break; } } else if(-2 == ret) { //Check failed, report exception recvHead = (protocolHead_t *)gizwitsProtocol.protocolBuf; gizProtocolErrorCmd(recvHead,ERROR_ACK_SUM); GIZWITS_LOG("ERR: check sum error!\n"); return -2; } switch(gizwitsProtocol.issuedFlag) { case ACTION_CONTROL_TYPE: gizwitsProtocol.issuedFlag = STATELESS_TYPE; gizwitsEventProcess(&gizwitsProtocol.issuedProcessEvent, (uint8_t *)&gizwitsProtocol.gizCurrentDataPoint, sizeof(dataPoint_t)); memset((uint8_t *)&gizwitsProtocol.issuedProcessEvent,0x0,sizeof(gizwitsProtocol.issuedProcessEvent)); break; case WIFI_STATUS_TYPE: gizwitsProtocol.issuedFlag = STATELESS_TYPE; gizwitsEventProcess(&gizwitsProtocol.wifiStatusEvent, (uint8_t *)&gizwitsProtocol.wifiStatusData, sizeof(moduleStatusInfo_t)); memset((uint8_t *)&gizwitsProtocol.wifiStatusEvent,0x0,sizeof(gizwitsProtocol.wifiStatusEvent)); break; case ACTION_W2D_TRANSPARENT_TYPE: gizwitsProtocol.issuedFlag = STATELESS_TYPE; gizwitsEventProcess(&gizwitsProtocol.issuedProcessEvent, (uint8_t *)gizwitsProtocol.transparentBuff, gizwitsProtocol.transparentLen); break; case GET_NTP_TYPE: gizwitsProtocol.issuedFlag = STATELESS_TYPE; gizwitsEventProcess(&gizwitsProtocol.NTPEvent, (uint8_t *)&gizwitsProtocol.TimeNTP, sizeof(protocolTime_t)); memset((uint8_t *)&gizwitsProtocol.NTPEvent,0x0,sizeof(gizwitsProtocol.NTPEvent)); break; case GET_MODULEINFO_TYPE: gizwitsProtocol.issuedFlag = STATELESS_TYPE; gizwitsEventProcess(&gizwitsProtocol.moduleInfoEvent, (uint8_t *)&gizwitsProtocol.wifiModuleNews, sizeof(moduleInfo_t)); memset((uint8_t *)&gizwitsProtocol.moduleInfoEvent,0x0,sizeof(moduleInfo_t)); break; default: break; } gizDevReportPolicy(currentData); return 0; } /** * @brief gizwits report transparent data interface * The user can call the interface to complete the reporting of private protocol data * @param [in] data :Private protocol data * @param [in] len :Private protocol data length * @return 0,success ;other,failure */ int32_t gizwitsPassthroughData(uint8_t * gizdata, uint32_t len) { int32_t ret = 0; uint8_t tx_buf[MAX_PACKAGE_LEN]; uint8_t *pTxBuf = tx_buf; uint16_t data_len = 6+len; if(NULL == gizdata) { GIZWITS_LOG("[ERR] gizwitsPassthroughData Error \n"); return (-1); } *pTxBuf ++= 0xFF; *pTxBuf ++= 0xFF; *pTxBuf ++= (uint8_t)(data_len>>8);//len *pTxBuf ++= (uint8_t)(data_len); *pTxBuf ++= CMD_REPORT_P0;//0x1b cmd *pTxBuf ++= gizwitsProtocol.sn++;//sn *pTxBuf ++= 0x00;//flag *pTxBuf ++= 0x00;//flag *pTxBuf ++= ACTION_D2W_TRANSPARENT_DATA;//P0_Cmd memcpy(&tx_buf[9],gizdata,len); tx_buf[data_len + 4 - 1 ] = gizProtocolSum( tx_buf , (data_len+4)); ret = uartWrite(tx_buf, data_len+4); if(ret < 0) { GIZWITS_LOG("ERR: uart write error %d \n", ret); } gizProtocolWaitAck(tx_buf, data_len+4); return 0; } /**@} */

exe
Windows 系统修复工具主要用于解决 Windows 11/10 系统中的各种常见问题,具有操作简单、功能全面等特点: 文件资源管理器修复:可解决文件资源管理器卡死、崩溃、无响应等问题,能终止崩溃循环。还可修复右键菜单无响应或选项缺失问题,以及重建缩略图缓存,让图片、视频等文件的缩略图正常显示,此外,还能处理桌面缺少回收站图标、回收站损坏等问题。 互联网和连接修复:能够刷新 DNS 缓存,加速网页加载速度,减少访问延迟。可重置 TCP/IP 协议栈,增强网络连接稳定性,减少网络掉线情况,还能还原 Hosts 文件,清除恶意程序对网络设置的篡改,保障网络安全,解决电脑重装系统后网络无法连接、浏览器主页被篡改等问题。 系统修复:集成系统文件检查器(SFC),可自动扫描并修复受损的系统文件。能解决 Windows 激活状态异常的问题,还可重建 DLL 注册库,恢复应用程序兼容性,解决部分软件无法正常运行的问题,同时也能处理如 Windows 沙箱无法启动、Windows 将 JPG 或 JPEG 保存为 JFIF 等系统问题。 系统工具维护:提供启动管理器、服务管理器和进程管理器等工具,用户可控制和管理启动程序、系统服务和当前运行的进程,提高系统的启动和运行速度,防止不必要的程序和服务占用系统资源。还能查看系统规格,如处理器线程数、最大显示分辨率等。 故障排除:集成超过 20 个微软官方诊断工具,可对系统问题进行专业排查,还能生成硬件健康状态报告。能解决搜索和索引故障、邮件和日历应用程序崩溃、设置应用程序无法启动等问题,也可处理打印机、网络适配器、Windows 更新等相关故障。 其他修复功能:可以重置组策略设置、catroot2 文件夹、记事本等多种系统设置和组件,如重置 Windows 应用商店缓存、Windows 防火墙设置等。还能添加重建图标缓存支持,恢复粘滞便笺删除

最新推荐

recommend-type

2022年网站美工个人年度工作总结(1).doc

2022年网站美工个人年度工作总结(1).doc
recommend-type

财务软件销售实习报告格式范文-实习报告格式(1).doc

财务软件销售实习报告格式范文-实习报告格式(1).doc
recommend-type

【航迹关联】基于标准 Hough 变换、修正 Hough 变换和序列 Hough 变换实现航迹起始算法研究Matlab代码.rar

【航迹关联】基于标准 Hough 变换、修正 Hough 变换和序列 Hough 变换实现航迹起始算法研究Matlab代码
recommend-type

Windows系统修复工具

Windows 系统修复工具主要用于解决 Windows 11/10 系统中的各种常见问题,具有操作简单、功能全面等特点: 文件资源管理器修复:可解决文件资源管理器卡死、崩溃、无响应等问题,能终止崩溃循环。还可修复右键菜单无响应或选项缺失问题,以及重建缩略图缓存,让图片、视频等文件的缩略图正常显示,此外,还能处理桌面缺少回收站图标、回收站损坏等问题。 互联网和连接修复:能够刷新 DNS 缓存,加速网页加载速度,减少访问延迟。可重置 TCP/IP 协议栈,增强网络连接稳定性,减少网络掉线情况,还能还原 Hosts 文件,清除恶意程序对网络设置的篡改,保障网络安全,解决电脑重装系统后网络无法连接、浏览器主页被篡改等问题。 系统修复:集成系统文件检查器(SFC),可自动扫描并修复受损的系统文件。能解决 Windows 激活状态异常的问题,还可重建 DLL 注册库,恢复应用程序兼容性,解决部分软件无法正常运行的问题,同时也能处理如 Windows 沙箱无法启动、Windows 将 JPG 或 JPEG 保存为 JFIF 等系统问题。 系统工具维护:提供启动管理器、服务管理器和进程管理器等工具,用户可控制和管理启动程序、系统服务和当前运行的进程,提高系统的启动和运行速度,防止不必要的程序和服务占用系统资源。还能查看系统规格,如处理器线程数、最大显示分辨率等。 故障排除:集成超过 20 个微软官方诊断工具,可对系统问题进行专业排查,还能生成硬件健康状态报告。能解决搜索和索引故障、邮件和日历应用程序崩溃、设置应用程序无法启动等问题,也可处理打印机、网络适配器、Windows 更新等相关故障。 其他修复功能:可以重置组策略设置、catroot2 文件夹、记事本等多种系统设置和组件,如重置 Windows 应用商店缓存、Windows 防火墙设置等。还能添加重建图标缓存支持,恢复粘滞便笺删除
recommend-type

高中信息技术《算法与程序设计》练习(1).doc

高中信息技术《算法与程序设计》练习(1).doc
recommend-type

获取本机IP地址的程序源码分析

从给定文件信息中我们可以提取出的关键知识点是“取本机IP”的实现方法以及与之相关的编程技术和源代码。在当今的信息技术领域中,获取本机IP地址是一项基本技能,广泛应用于网络通信类的软件开发中,下面将详细介绍这一知识点。 首先,获取本机IP地址通常需要依赖于编程语言和操作系统的API。不同的操作系统提供了不同的方法来获取IP地址。在Windows操作系统中,可以通过调用Windows API中的GetAdaptersInfo()或GetAdaptersAddresses()函数来获取网络适配器信息,进而得到IP地址。在类Unix操作系统中,可以通过读取/proc/net或是使用系统命令ifconfig、ip等来获取网络接口信息。 在程序设计过程中,获取本机IP地址的源程序通常会用到网络编程的知识,比如套接字编程(Socket Programming)。网络编程允许程序之间进行通信,套接字则是在网络通信过程中用于发送和接收数据的接口。在许多高级语言中,如Python、Java、C#等,都提供了内置的网络库和类来简化网络编程的工作。 在网络通信类中,IP地址是区分不同网络节点的重要标识,它是由IP协议规定的,用于在网络中唯一标识一个网络接口。IP地址可以是IPv4,也可以是较新的IPv6。IPv4地址由32位二进制数表示,通常分为四部分,每部分由8位构成,并以点分隔,如192.168.1.1。IPv6地址则由128位二进制数表示,其表示方法与IPv4有所不同,以冒号分隔的8组16进制数表示,如2001:0db8:85a3:0000:0000:8a2e:0370:7334。 当编写源代码以获取本机IP地址时,通常涉及到以下几个步骤: 1. 选择合适的编程语言和相关库。 2. 根据目标操作系统的API或系统命令获取网络接口信息。 3. 分析网络接口信息,提取出IP地址。 4. 将提取的IP地址转换成适合程序内部使用的格式。 5. 在程序中提供相应功能,如显示IP地址或用于网络通信。 例如,在Python中,可以使用内置的socket库来获取本机IP地址。一个简单的示例代码如下: ```python import socket # 获取主机名 hostname = socket.gethostname() # 获取本机IP local_ip = socket.gethostbyname(hostname) print("本机IP地址是:", local_ip) ``` 在实际应用中,获取本机IP地址通常是为了实现网络通信功能,例如建立客户端与服务器的连接,或者是在开发涉及到IP地址的其他功能时使用。 关于文件名称“getIP”,这是一个自解释的文件名,明显表示该文件或程序的作用是获取本机的IP地址。从标签“控件 源码 网络通信类 资源”中我们可以看出,这个文件很可能是一个可以嵌入其他软件中的代码片段,用以实现网络通信功能的一部分,具有较高的灵活性和重用性。 综上所述,获取本机IP地址是一个涉及到操作系统API、网络编程以及特定编程语言知识的技能。它不仅需要对编程语言提供的库函数有深入的理解,还要对操作系统的网络配置和IP协议有足够的认识。通过阅读和分析相关的源代码,如“getIP”,可以加深对网络编程实现细节的理解,并能够在实际开发中快速地应用这一技术。
recommend-type

【权威指南】:Win11笔记本上RTX4080驱动的安装与调试秘籍

# 1. Win11笔记本与RTX4080显卡介绍 随着技术的不断发展,笔记本电脑已不再是仅仅满足办公需求的移动设备,而是逐渐成为可以胜任复杂图形处理和游戏任务的强大工具。微软推出的Windows 11操作系统,以其全新的用户界面和改进的系统性能,为用户提供了更为流畅的操作体验。而在硬件方面,NVIDIA的RTX 4080显卡以其卓越的图形处理能力和AI支持,为笔记本电脑带来了前所未有的性能提升。本章节将带您初步了解Windows 11笔记本与NVIDIA RTX 4080显卡的基础信息,为进一步深入探讨它们的优化和调试技巧奠定基础。 ## 1.1 Win11笔记本的优势 Windows
recommend-type

windows环境举例

<think>好的,用户现在想在Windows环境下创建C函数库,需要具体的方法和示例代码。我需要结合之前的回答和用户提供的引用内容来给出合适的指导。 首先回顾之前的回答,用户已经了解了在Linux下创建静态库和动态库的方法,现在需要切换到Windows环境。根据引用[2],Windows下的C标准库和动态链接库的处理与Linux不同,比如使用dlfcn.h在Linux,而Windows可能需要其他方式。另外,引用[1]提到了在Windows下配置gcc环境(MinGW-w64),这可能是一个关键点,因为用户可能需要使用MinGW来编译库。 用户提供的引用[3]提到了使用MSVC编译器,这
recommend-type

QQ自动发送/回复系统源代码开放

根据提供的文件信息,我们可以了解到以下几点关键的知识点: ### 标题:“qqhelp” 1. **项目类型**: 标题“qqhelp”暗示这是一个与QQ相关的帮助工具或项目。QQ是中国流行的即时通讯软件,因此这个标题表明项目可能提供了对QQ客户端功能的辅助或扩展。 2. **用途**: “help”表明此项目的主要目的是提供帮助或解决问题。由于它提到了QQ,并且涉及“autosend/reply”功能,我们可以推测该项目可能用于自动化发送消息回复,或提供某种形式的自动回复机制。 ### 描述:“I put it to my web, but nobody sendmessage to got the source, now I public it. it supply qq,ticq autosend/reply ,full sourcecode use it as you like” 1. **发布情况**: 描述提到该项目原先被放置在某人的网站上,并且没有收到请求源代码的消息。这可能意味着项目不够知名或者需求不高。现在作者决定公开发布,这可能是因为希望项目能够被更多人了解和使用,或是出于开源共享的精神。 2. **功能特性**: 提到的“autosend/reply”表明该项目能够实现自动发送和回复消息。这种功能对于需要进行批量或定时消息沟通的应用场景非常有用,例如客户服务、自动化的营销通知等。 3. **代码可用性**: 作者指出提供了“full sourcecode”,意味着源代码完全开放,用户可以自由使用,无论是查看、学习还是修改,用户都有很大的灵活性。这对于希望学习编程或者有特定需求的开发者来说是一个很大的优势。 ### 标签:“综合系统类” 1. **项目分类**: 标签“综合系统类”表明这个项目可能是一个多功能的集成系统,它可能不仅限于QQ相关的功能,还可能包含了其他类型的综合服务或特性。 2. **技术范畴**: 这个标签可能表明该项目的技术实现比较全面,可能涉及到了多个技术栈或者系统集成的知识点,例如消息处理、网络编程、自动化处理等。 ### 压缩包子文件的文件名称列表: 1. **Unit1.dfm**: 这是一个Delphi或Object Pascal语言的窗体定义文件,用于定义应用程序中的用户界面布局。DFM文件通常用于存储组件的属性和位置信息,使得开发者可以快速地进行用户界面的设计和调整。 2. **qqhelp.dpr**: DPR是Delphi项目文件的扩展名,包含了Delphi项目的核心设置,如程序入口、使用的单元(Units)等。这个文件是编译和构建Delphi项目的起点,它能够帮助开发者了解项目的组织结构和编译指令。 3. **Unit1.pas**: PAS是Delphi或Object Pascal语言的源代码文件。这个文件可能包含了与QQ帮助工具相关的核心逻辑代码,例如处理自动发送和回复消息的算法等。 4. **readme.txt**: 这是一个常见的文本文件,包含项目的基本说明和使用指导,帮助用户了解如何获取、安装、运行和定制该项目。README文件通常是用户与项目首次交互时首先阅读的文件,因此它对于一个开源项目的用户友好度有着重要影响。 通过以上分析,我们可以看出“qqhelp”项目是一个针对QQ通讯工具的自动化消息发送与回复的辅助工具。项目包含完整的源代码,用户可以根据自己的需要进行查看、修改和使用。它可能包含Delphi语言编写的窗体界面和后端逻辑代码,具有一定的综合系统特性。项目作者出于某种原因将其开源,希望能够得到更广泛的使用和反馈。
recommend-type

【7步打造Win11深度学习利器】:Tensorflow-GPU与RTX4080终极优化指南

# 1. 深度学习与Windows 11的融合 在人工智能时代,深度学习已渗透到生活的方方面面,而Windows 11作为最新一代的操作系统,为深度学习提供了一个高效的工作平台。本章节将探讨深度学习技术如何与Windows 11系统融合,以及这一